var u2=Object.defineProperty;var l2=(r,e,t)=>e in r?u2(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var we=(r,e,t)=>l2(r,typeof e!="symbol"?e+"":e,t);import{PGlite as c2}from"https://cdn.jsdelivr.net/npm/@electric-sql/pglite/dist/index.js";import{vector as d2}from"https://cdn.jsdelivr.net/npm/@electric-sql/pglite/dist/vector/index.js";var Ba={},tw={"./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm":(r,e,t)=>{r.exports=t.p+"ort-wasm-simd-threaded.jsep.wasm"},"./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs?46eb":(r,e,t)=>{r.exports=t.p+"ort.bundle.min.mjs"},"?2ce3":()=>{},"?7a2c":()=>{},"?a42a":()=>{},"?2b25":()=>{},"?569f":()=>{},"?3f59":()=>{},"?154a":()=>{},"./node_modules/@huggingface/jinja/dist/index.js":(r,e,t)=>{t.r(e),t.d(e,{Environment:()=>st,Interpreter:()=>ht,Template:()=>gt,parse:()=>pe,tokenize:()=>y});var n=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",BooleanLiteral:"BooleanLiteral",NullLiteral:"NullLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",OpenCurlyBracket:"OpenCurlyBracket",CloseCurlyBracket:"CloseCurlyBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Set:"Set",If:"If",For:"For",In:"In",Is:"Is",NotIn:"NotIn",Else:"Else",EndIf:"EndIf",ElseIf:"ElseIf",EndFor:"EndFor",And:"And",Or:"Or",Not:"UnaryOperator",Macro:"Macro",EndMacro:"EndMacro"}),a=Object.freeze({set:n.Set,for:n.For,in:n.In,is:n.Is,if:n.If,else:n.Else,endif:n.EndIf,elif:n.ElseIf,endfor:n.EndFor,and:n.And,or:n.Or,not:n.Not,"not in":n.NotIn,macro:n.Macro,endmacro:n.EndMacro,true:n.BooleanLiteral,false:n.BooleanLiteral,none:n.NullLiteral,True:n.BooleanLiteral,False:n.BooleanLiteral,None:n.NullLiteral}),o=class{constructor(W,de){this.value=W,this.type=de}};function u(W){return/\w/.test(W)}function d(W){return/[0-9]/.test(W)}var c=[["{%",n.OpenStatement],["%}",n.CloseStatement],["{{",n.OpenExpression],["}}",n.CloseExpression],["(",n.OpenParen],[")",n.CloseParen],["{",n.OpenCurlyBracket],["}",n.CloseCurlyBracket],["[",n.OpenSquareBracket],["]",n.CloseSquareBracket],[",",n.Comma],[".",n.Dot],[":",n.Colon],["|",n.Pipe],["<=",n.ComparisonBinaryOperator],[">=",n.ComparisonBinaryOperator],["==",n.ComparisonBinaryOperator],["!=",n.ComparisonBinaryOperator],["<",n.ComparisonBinaryOperator],[">",n.ComparisonBinaryOperator],["+",n.AdditiveBinaryOperator],["-",n.AdditiveBinaryOperator],["*",n.MultiplicativeBinaryOperator],["/",n.MultiplicativeBinaryOperator],["%",n.MultiplicativeBinaryOperator],["=",n.Equals]],h=new Map([["n",` `],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function _(W,de={}){return W.endsWith(` `)&&(W=W.slice(0,-1)),W=W.replace(/{#.*?#}/gs,"{##}"),de.lstrip_blocks&&(W=W.replace(/^[ \t]*({[#%])/gm,"$1")),de.trim_blocks&&(W=W.replace(/([#%]})\n/g,"$1")),W.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}function y(W,de={}){var rt,dt,bt;const J=[],Ee=_(W,de);let Fe=0;const Ze=Ct=>{let Lt="";for(;Ct(Ee[Fe]);){if(Ee[Fe]==="\\"){if(++Fe,Fe>=Ee.length)throw new SyntaxError("Unexpected end of input");const Nt=Ee[Fe++],br=h.get(Nt);if(br===void 0)throw new SyntaxError(`Unexpected escaped character: ${Nt}`);Lt+=br;continue}if(Lt+=Ee[Fe++],Fe>=Ee.length)throw new SyntaxError("Unexpected end of input")}return Lt};e:for(;Fe0){J.push(new o(Nt,n.Text));continue}}Ze(Nt=>/\s/.test(Nt));const Lt=Ee[Fe];if(Lt==="-"||Lt==="+"){const Nt=(dt=J.at(-1))==null?void 0:dt.type;if(Nt===n.Text||Nt===void 0)throw new SyntaxError(`Unexpected character: ${Lt}`);switch(Nt){case n.Identifier:case n.NumericLiteral:case n.BooleanLiteral:case n.NullLiteral:case n.StringLiteral:case n.CloseParen:case n.CloseSquareBracket:break;default:{++Fe;const br=Ze(d);J.push(new o(`${Lt}${br}`,br.length>0?n.NumericLiteral:n.UnaryOperator));continue}}}for(const[Nt,br]of c)if(Ee.slice(Fe,Fe+Nt.length)===Nt){J.push(new o(Nt,br)),Fe+=Nt.length;continue e}if(Lt==="'"||Lt==='"'){++Fe;const Nt=Ze(br=>br!==Lt);J.push(new o(Nt,n.StringLiteral)),++Fe;continue}if(d(Lt)){const Nt=Ze(d);J.push(new o(Nt,n.NumericLiteral));continue}if(u(Lt)){const Nt=Ze(u),br=Object.hasOwn(a,Nt)?a[Nt]:n.Identifier;br===n.In&&((bt=J.at(-1))==null?void 0:bt.type)===n.Not?(J.pop(),J.push(new o("not in",n.NotIn))):J.push(new o(Nt,br));continue}throw new SyntaxError(`Unexpected character: ${Lt}`)}return J}var w=class{constructor(){we(this,"type","Statement")}},M=class extends w{constructor(de){super();we(this,"type","Program");this.body=de}},S=class extends w{constructor(de,J,Ee){super();we(this,"type","If");this.test=de,this.body=J,this.alternate=Ee}},G=class extends w{constructor(de,J,Ee,Fe){super();we(this,"type","For");this.loopvar=de,this.iterable=J,this.body=Ee,this.defaultBlock=Fe}},H=class extends w{constructor(de,J){super();we(this,"type","Set");this.assignee=de,this.value=J}},B=class extends w{constructor(de,J,Ee){super();we(this,"type","Macro");this.name=de,this.args=J,this.body=Ee}},z=class extends w{constructor(){super(...arguments);we(this,"type","Expression")}},U=class extends z{constructor(de,J,Ee){super();we(this,"type","MemberExpression");this.object=de,this.property=J,this.computed=Ee}},F=class extends z{constructor(de,J){super();we(this,"type","CallExpression");this.callee=de,this.args=J}},I=class extends z{constructor(de){super();we(this,"type","Identifier");this.value=de}},k=class extends z{constructor(de){super();we(this,"type","Literal");this.value=de}},$=class extends k{constructor(){super(...arguments);we(this,"type","NumericLiteral")}},j=class extends k{constructor(){super(...arguments);we(this,"type","StringLiteral")}},ce=class extends k{constructor(){super(...arguments);we(this,"type","BooleanLiteral")}},ue=class extends k{constructor(){super(...arguments);we(this,"type","NullLiteral")}},Pe=class extends k{constructor(){super(...arguments);we(this,"type","ArrayLiteral")}},Te=class extends k{constructor(){super(...arguments);we(this,"type","TupleLiteral")}},ie=class extends k{constructor(){super(...arguments);we(this,"type","ObjectLiteral")}},oe=class extends z{constructor(de,J,Ee){super();we(this,"type","BinaryExpression");this.operator=de,this.left=J,this.right=Ee}},re=class extends z{constructor(de,J){super();we(this,"type","FilterExpression");this.operand=de,this.filter=J}},ge=class extends z{constructor(de,J){super();we(this,"type","SelectExpression");this.iterable=de,this.test=J}},ve=class extends z{constructor(de,J,Ee){super();we(this,"type","TestExpression");this.operand=de,this.negate=J,this.test=Ee}},me=class extends z{constructor(de,J){super();we(this,"type","UnaryExpression");this.operator=de,this.argument=J}},Le=class extends z{constructor(de=void 0,J=void 0,Ee=void 0){super();we(this,"type","SliceExpression");this.start=de,this.stop=J,this.step=Ee}},$e=class extends z{constructor(de,J){super();we(this,"type","KeywordArgumentExpression");this.key=de,this.value=J}};function pe(W){const de=new M([]);let J=0;function Ee(ot,At){const Ut=W[J++];if(!Ut||Ut.type!==ot)throw new Error(`Parser Error: ${At}. ${Ut.type} !== ${ot}.`);return Ut}function Fe(){switch(W[J].type){case n.Text:return dt();case n.OpenStatement:return bt();case n.OpenExpression:return Ct();default:throw new SyntaxError(`Unexpected token type: ${W[J].type}`)}}function Ze(...ot){return J+ot.length<=W.length&&ot.some((At,Ut)=>At!==W[J+Ut].type)}function rt(...ot){return J+ot.length<=W.length&&ot.every((At,Ut)=>At===W[J+Ut].type)}function dt(){return new j(Ee(n.Text,"Expected text token").value)}function bt(){Ee(n.OpenStatement,"Expected opening statement token");let ot;switch(W[J].type){case n.Set:++J,ot=Lt(),Ee(n.CloseStatement,"Expected closing statement token");break;case n.If:++J,ot=Nt(),Ee(n.OpenStatement,"Expected {% token"),Ee(n.EndIf,"Expected endif token"),Ee(n.CloseStatement,"Expected %} token");break;case n.Macro:++J,ot=br(),Ee(n.OpenStatement,"Expected {% token"),Ee(n.EndMacro,"Expected endmacro token"),Ee(n.CloseStatement,"Expected %} token");break;case n.For:++J,ot=Yr(),Ee(n.OpenStatement,"Expected {% token"),Ee(n.EndFor,"Expected endfor token"),Ee(n.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${W[J].type}`)}return ot}function Ct(){Ee(n.OpenExpression,"Expected opening expression token");const ot=nn();return Ee(n.CloseExpression,"Expected closing expression token"),ot}function Lt(){const ot=nn();if(rt(n.Equals)){++J;const At=Lt();return new H(ot,At)}return ot}function Nt(){var pn,Ds,Ps,Dr,zn,en,ps,fr;const ot=nn();Ee(n.CloseStatement,"Expected closing statement token");const At=[],Ut=[];for(;!(((pn=W[J])==null?void 0:pn.type)===n.OpenStatement&&(((Ds=W[J+1])==null?void 0:Ds.type)===n.ElseIf||((Ps=W[J+1])==null?void 0:Ps.type)===n.Else||((Dr=W[J+1])==null?void 0:Dr.type)===n.EndIf));)At.push(Fe());if(((zn=W[J])==null?void 0:zn.type)===n.OpenStatement&&((en=W[J+1])==null?void 0:en.type)!==n.EndIf)if(++J,rt(n.ElseIf))Ee(n.ElseIf,"Expected elseif token"),Ut.push(Nt());else for(Ee(n.Else,"Expected else token"),Ee(n.CloseStatement,"Expected closing statement token");!(((ps=W[J])==null?void 0:ps.type)===n.OpenStatement&&((fr=W[J+1])==null?void 0:fr.type)===n.EndIf);)Ut.push(Fe());return new S(ot,At,Ut)}function br(){const ot=jn();if(ot.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const At=xs();Ee(n.CloseStatement,"Expected closing statement token");const Ut=[];for(;Ze(n.OpenStatement,n.EndMacro);)Ut.push(Fe());return new B(ot,At,Ut)}function Rr(ot=!1){const At=ot?jn:nn,Ut=[At()],pn=rt(n.Comma);for(;pn&&(++J,Ut.push(At()),!!rt(n.Comma)););return pn?new Te(Ut):Ut[0]}function Yr(){const ot=Rr(!0);if(!(ot instanceof I||ot instanceof Te))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${ot.type} instead`);Ee(n.In,"Expected `in` keyword following loop variable");const At=nn();Ee(n.CloseStatement,"Expected closing statement token");const Ut=[];for(;Ze(n.OpenStatement,n.EndFor)&&Ze(n.OpenStatement,n.Else);)Ut.push(Fe());const pn=[];if(rt(n.OpenStatement,n.Else))for(++J,++J,Ee(n.CloseStatement,"Expected closing statement token");Ze(n.OpenStatement,n.EndFor);)pn.push(Fe());return new G(ot,At,Ut,pn)}function nn(){return $n()}function $n(){const ot=Es();if(rt(n.If)){++J;const At=Es();if(rt(n.Else)){++J;const Ut=Es();return new S(At,[ot],[Ut])}else return new ge(ot,At)}return ot}function Es(){let ot=na();for(;rt(n.Or);){const At=W[J];++J;const Ut=na();ot=new oe(At,ot,Ut)}return ot}function na(){let ot=fn();for(;rt(n.And);){const At=W[J];++J;const Ut=fn();ot=new oe(At,ot,Ut)}return ot}function fn(){let ot;for(;rt(n.Not);){const At=W[J];++J;const Ut=fn();ot=new me(At,Ut)}return ot??fs()}function fs(){let ot=qt();for(;rt(n.ComparisonBinaryOperator)||rt(n.In)||rt(n.NotIn);){const At=W[J];++J;const Ut=qt();ot=new oe(At,ot,Ut)}return ot}function qt(){let ot=Ms();for(;rt(n.AdditiveBinaryOperator);){const At=W[J];++J;const Ut=Ms();ot=new oe(At,ot,Ut)}return ot}function sa(){const ot=ia();return rt(n.OpenParen)?Ts(ot):ot}function Ts(ot){let At=new F(ot,xs());return rt(n.OpenParen)&&(At=Ts(At)),At}function xs(){Ee(n.OpenParen,"Expected opening parenthesis for arguments list");const ot=aa();return Ee(n.CloseParen,"Expected closing parenthesis for arguments list"),ot}function aa(){const ot=[];for(;!rt(n.CloseParen);){let At=nn();if(rt(n.Equals)){if(++J,!(At instanceof I))throw new SyntaxError("Expected identifier for keyword argument");const Ut=nn();At=new $e(At,Ut)}ot.push(At),rt(n.Comma)&&++J}return ot}function Kn(){const ot=[];let At=!1;for(;!rt(n.CloseSquareBracket);)rt(n.Colon)?(ot.push(void 0),++J,At=!0):(ot.push(nn()),rt(n.Colon)&&(++J,At=!0));if(ot.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(At){if(ot.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new Le(...ot)}return ot[0]}function ia(){let ot=jn();for(;rt(n.Dot)||rt(n.OpenSquareBracket);){const At=W[J];++J;let Ut;const pn=At.type!==n.Dot;if(pn)Ut=Kn(),Ee(n.CloseSquareBracket,"Expected closing square bracket");else if(Ut=jn(),Ut.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");ot=new U(ot,Ut,pn)}return ot}function Ms(){let ot=Fs();for(;rt(n.MultiplicativeBinaryOperator);){const At=W[J];++J;const Ut=Fs();ot=new oe(At,ot,Ut)}return ot}function Fs(){let ot=Ns();for(;rt(n.Is);){++J;const At=rt(n.Not);At&&++J;let Ut=jn();if(Ut instanceof ce?Ut=new I(Ut.value.toString()):Ut instanceof ue&&(Ut=new I("none")),!(Ut instanceof I))throw new SyntaxError("Expected identifier for the test");ot=new ve(ot,At,Ut)}return ot}function Ns(){let ot=sa();for(;rt(n.Pipe);){++J;let At=jn();if(!(At instanceof I))throw new SyntaxError("Expected identifier for the filter");rt(n.OpenParen)&&(At=Ts(At)),ot=new re(ot,At)}return ot}function jn(){const ot=W[J];switch(ot.type){case n.NumericLiteral:return++J,new $(Number(ot.value));case n.StringLiteral:return++J,new j(ot.value);case n.BooleanLiteral:return++J,new ce(ot.value.toLowerCase()==="true");case n.NullLiteral:return++J,new ue(null);case n.Identifier:return++J,new I(ot.value);case n.OpenParen:{++J;const At=Rr();if(W[J].type!==n.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${W[J].type} instead`);return++J,At}case n.OpenSquareBracket:{++J;const At=[];for(;!rt(n.CloseSquareBracket);)At.push(nn()),rt(n.Comma)&&++J;return++J,new Pe(At)}case n.OpenCurlyBracket:{++J;const At=new Map;for(;!rt(n.CloseCurlyBracket);){const Ut=nn();Ee(n.Colon,"Expected colon between key and value in object literal");const pn=nn();At.set(Ut,pn),rt(n.Comma)&&++J}return++J,new ie(At)}default:throw new SyntaxError(`Unexpected token: ${ot.type}`)}}for(;J=0?(de=(de??(de=0))<0?Math.max(W.length+de,0):Math.min(de,W.length),J=(J??(J=W.length))<0?Math.max(W.length+J,0):Math.min(J,W.length)):(de=(de??(de=W.length-1))<0?Math.max(W.length+de,-1):Math.min(de,W.length-1),J=(J??(J=-1))<-1?Math.max(W.length+J,-1):Math.min(J,W.length-1));const Ze=[];for(let rt=de;Fe*rtde.toUpperCase())}var Re=class{constructor(W=void 0){we(this,"type","RuntimeValue");we(this,"value");we(this,"builtins",new Map);this.value=W}__bool__(){return new He(!!this.value)}},Xe=class extends Re{constructor(){super(...arguments);we(this,"type","NumericValue")}},ae=class extends Re{constructor(){super(...arguments);we(this,"type","StringValue");we(this,"builtins",new Map([["upper",new qe(()=>new ae(this.value.toUpperCase()))],["lower",new qe(()=>new ae(this.value.toLowerCase()))],["strip",new qe(()=>new ae(this.value.trim()))],["title",new qe(()=>new ae(ke(this.value)))],["length",new Xe(this.value.length)],["rstrip",new qe(()=>new ae(this.value.trimEnd()))],["lstrip",new qe(()=>new ae(this.value.trimStart()))]]))}},He=class extends Re{constructor(){super(...arguments);we(this,"type","BooleanValue")}},Ve=class extends Re{constructor(){super(...arguments);we(this,"type","ObjectValue");we(this,"builtins",new Map([["get",new qe(([de,J])=>{if(!(de instanceof ae))throw new Error(`Object key must be a string: got ${de.type}`);return this.value.get(de.value)??J??new Ge})],["items",new qe(()=>new Se(Array.from(this.value.entries()).map(([de,J])=>new Se([new ae(de),J]))))]]))}__bool__(){return new He(this.value.size>0)}},he=class extends Ve{constructor(){super(...arguments);we(this,"type","KeywordArgumentsValue")}},Se=class extends Re{constructor(){super(...arguments);we(this,"type","ArrayValue");we(this,"builtins",new Map([["length",new Xe(this.value.length)]]))}__bool__(){return new He(this.value.length>0)}},Ke=class extends Se{constructor(){super(...arguments);we(this,"type","TupleValue")}},qe=class extends Re{constructor(){super(...arguments);we(this,"type","FunctionValue")}},Ge=class extends Re{constructor(){super(...arguments);we(this,"type","NullValue")}},We=class extends Re{constructor(){super(...arguments);we(this,"type","UndefinedValue")}},st=class{constructor(W){we(this,"variables",new Map([["namespace",new qe(W=>{if(W.length===0)return new Ve(new Map);if(W.length!==1||!(W[0]instanceof Ve))throw new Error("`namespace` expects either zero arguments or a single object argument");return W[0]})]]));we(this,"tests",new Map([["boolean",W=>W.type==="BooleanValue"],["callable",W=>W instanceof qe],["odd",W=>{if(W.type!=="NumericValue")throw new Error(`Cannot apply test "odd" to type: ${W.type}`);return W.value%2!==0}],["even",W=>{if(W.type!=="NumericValue")throw new Error(`Cannot apply test "even" to type: ${W.type}`);return W.value%2===0}],["false",W=>W.type==="BooleanValue"&&!W.value],["true",W=>W.type==="BooleanValue"&&W.value],["none",W=>W.type==="NullValue"],["string",W=>W.type==="StringValue"],["number",W=>W.type==="NumericValue"],["integer",W=>W.type==="NumericValue"&&Number.isInteger(W.value)],["iterable",W=>W.type==="ArrayValue"||W.type==="StringValue"],["mapping",W=>W.type==="ObjectValue"],["lower",W=>{const de=W.value;return W.type==="StringValue"&&de===de.toLowerCase()}],["upper",W=>{const de=W.value;return W.type==="StringValue"&&de===de.toUpperCase()}],["none",W=>W.type==="NullValue"],["defined",W=>W.type!=="UndefinedValue"],["undefined",W=>W.type==="UndefinedValue"],["equalto",(W,de)=>W.value===de.value],["eq",(W,de)=>W.value===de.value]]));this.parent=W}set(W,de){return this.declareVariable(W,mt(de))}declareVariable(W,de){if(this.variables.has(W))throw new SyntaxError(`Variable already declared: ${W}`);return this.variables.set(W,de),de}setVariable(W,de){return this.variables.set(W,de),de}resolve(W){if(this.variables.has(W))return this;if(this.parent)return this.parent.resolve(W);throw new Error(`Unknown variable: ${W}`)}lookupVariable(W){try{return this.resolve(W).variables.get(W)??new We}catch{return new We}}},ht=class{constructor(W){we(this,"global");this.global=W??new st}run(W){return this.evaluate(W,this.global)}evaluateBinaryExpression(W,de){const J=this.evaluate(W.left,de);switch(W.operator.value){case"and":return J.__bool__().value?this.evaluate(W.right,de):J;case"or":return J.__bool__().value?J:this.evaluate(W.right,de)}const Ee=this.evaluate(W.right,de);switch(W.operator.value){case"==":return new He(J.value==Ee.value);case"!=":return new He(J.value!=Ee.value)}if(J instanceof We||Ee instanceof We)throw new Error("Cannot perform operation on undefined values");if(J instanceof Ge||Ee instanceof Ge)throw new Error("Cannot perform operation on null values");if(J instanceof Xe&&Ee instanceof Xe)switch(W.operator.value){case"+":return new Xe(J.value+Ee.value);case"-":return new Xe(J.value-Ee.value);case"*":return new Xe(J.value*Ee.value);case"/":return new Xe(J.value/Ee.value);case"%":return new Xe(J.value%Ee.value);case"<":return new He(J.value":return new He(J.value>Ee.value);case">=":return new He(J.value>=Ee.value);case"<=":return new He(J.value<=Ee.value)}else if(J instanceof Se&&Ee instanceof Se)switch(W.operator.value){case"+":return new Se(J.value.concat(Ee.value))}else if(Ee instanceof Se){const Fe=Ee.value.find(Ze=>Ze.value===J.value)!==void 0;switch(W.operator.value){case"in":return new He(Fe);case"not in":return new He(!Fe)}}if(J instanceof ae||Ee instanceof ae)switch(W.operator.value){case"+":return new ae(J.value.toString()+Ee.value.toString())}if(J instanceof ae&&Ee instanceof ae)switch(W.operator.value){case"in":return new He(Ee.value.includes(J.value));case"not in":return new He(!Ee.value.includes(J.value))}if(J instanceof ae&&Ee instanceof Ve)switch(W.operator.value){case"in":return new He(Ee.value.has(J.value));case"not in":return new He(!Ee.value.has(J.value))}throw new SyntaxError(`Unknown operator "${W.operator.value}" between ${J.type} and ${Ee.type}`)}evaluateArguments(W,de){const J=[],Ee=new Map;for(const Fe of W)if(Fe.type==="KeywordArgumentExpression"){const Ze=Fe;Ee.set(Ze.key.value,this.evaluate(Ze.value,de))}else{if(Ee.size>0)throw new Error("Positional arguments must come before keyword arguments");J.push(this.evaluate(Fe,de))}return[J,Ee]}evaluateFilterExpression(W,de){const J=this.evaluate(W.operand,de);if(W.filter.type==="Identifier"){const Ee=W.filter;if(Ee.value==="tojson")return new ae(ct(J));if(J instanceof Se)switch(Ee.value){case"list":return J;case"first":return J.value[0];case"last":return J.value[J.value.length-1];case"length":return new Xe(J.value.length);case"reverse":return new Se(J.value.reverse());case"sort":return new Se(J.value.sort((Fe,Ze)=>{if(Fe.type!==Ze.type)throw new Error(`Cannot compare different types: ${Fe.type} and ${Ze.type}`);switch(Fe.type){case"NumericValue":return Fe.value-Ze.value;case"StringValue":return Fe.value.localeCompare(Ze.value);default:throw new Error(`Cannot compare type: ${Fe.type}`)}}));default:throw new Error(`Unknown ArrayValue filter: ${Ee.value}`)}else if(J instanceof ae)switch(Ee.value){case"length":return new Xe(J.value.length);case"upper":return new ae(J.value.toUpperCase());case"lower":return new ae(J.value.toLowerCase());case"title":return new ae(ke(J.value));case"capitalize":return new ae(J.value.charAt(0).toUpperCase()+J.value.slice(1));case"trim":return new ae(J.value.trim());case"indent":return new ae(J.value.split(` `).map((Fe,Ze)=>Ze===0||Fe.length===0?Fe:" "+Fe).join(` `));case"string":return J;default:throw new Error(`Unknown StringValue filter: ${Ee.value}`)}else if(J instanceof Xe)switch(Ee.value){case"abs":return new Xe(Math.abs(J.value));default:throw new Error(`Unknown NumericValue filter: ${Ee.value}`)}else if(J instanceof Ve)switch(Ee.value){case"items":return new Se(Array.from(J.value.entries()).map(([Fe,Ze])=>new Se([new ae(Fe),Ze])));case"length":return new Xe(J.value.size);default:throw new Error(`Unknown ObjectValue filter: ${Ee.value}`)}throw new Error(`Cannot apply filter "${Ee.value}" to type: ${J.type}`)}else if(W.filter.type==="CallExpression"){const Ee=W.filter;if(Ee.callee.type!=="Identifier")throw new Error(`Unknown filter: ${Ee.callee.type}`);const Fe=Ee.callee.value;if(Fe==="tojson"){const[,Ze]=this.evaluateArguments(Ee.args,de),rt=Ze.get("indent")??new Ge;if(!(rt instanceof Xe||rt instanceof Ge))throw new Error("If set, indent must be a number");return new ae(ct(J,rt.value))}if(J instanceof Se){switch(Fe){case"selectattr":case"rejectattr":{const Ze=Fe==="selectattr";if(J.value.some(Nt=>!(Nt instanceof Ve)))throw new Error(`\`${Fe}\` can only be applied to array of objects`);if(Ee.args.some(Nt=>Nt.type!=="StringLiteral"))throw new Error(`arguments of \`${Fe}\` must be strings`);const[rt,dt,bt]=Ee.args.map(Nt=>this.evaluate(Nt,de));let Ct;if(dt){const Nt=de.tests.get(dt.value);if(!Nt)throw new Error(`Unknown test: ${dt.value}`);Ct=Nt}else Ct=(...Nt)=>Nt[0].__bool__().value;const Lt=J.value.filter(Nt=>{const br=Nt.value.get(rt.value),Rr=br?Ct(br,bt):!1;return Ze?Rr:!Rr});return new Se(Lt)}case"map":{const[,Ze]=this.evaluateArguments(Ee.args,de);if(Ze.has("attribute")){const rt=Ze.get("attribute");if(!(rt instanceof ae))throw new Error("attribute must be a string");const dt=Ze.get("default"),bt=J.value.map(Ct=>{if(!(Ct instanceof Ve))throw new Error("items in map must be an object");return Ct.value.get(rt.value)??dt??new We});return new Se(bt)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${Fe}`)}else if(J instanceof ae){switch(Fe){case"indent":{const[Ze,rt]=this.evaluateArguments(Ee.args,de),dt=Ze.at(0)??rt.get("width")??new Xe(4);if(!(dt instanceof Xe))throw new Error("width must be a number");const bt=Ze.at(1)??rt.get("first")??new He(!1),Ct=Ze.at(2)??rt.get("blank")??new He(!1),Lt=J.value.split(` `),Nt=" ".repeat(dt.value),br=Lt.map((Rr,Yr)=>!bt.value&&Yr===0||!Ct.value&&Rr.length===0?Rr:Nt+Rr);return new ae(br.join(` `))}}throw new Error(`Unknown StringValue filter: ${Fe}`)}else throw new Error(`Cannot apply filter "${Fe}" to type: ${J.type}`)}throw new Error(`Unknown filter: ${W.filter.type}`)}evaluateTestExpression(W,de){const J=this.evaluate(W.operand,de),Ee=de.tests.get(W.test.value);if(!Ee)throw new Error(`Unknown test: ${W.test.value}`);const Fe=Ee(J);return new He(W.negate?!Fe:Fe)}evaluateUnaryExpression(W,de){const J=this.evaluate(W.argument,de);switch(W.operator.value){case"not":return new He(!J.value);default:throw new SyntaxError(`Unknown operator: ${W.operator.value}`)}}evalProgram(W,de){return this.evaluateBlock(W.body,de)}evaluateBlock(W,de){let J="";for(const Ee of W){const Fe=this.evaluate(Ee,de);Fe.type!=="NullValue"&&Fe.type!=="UndefinedValue"&&(J+=Fe.value)}return new ae(J)}evaluateIdentifier(W,de){return de.lookupVariable(W.value)}evaluateCallExpression(W,de){const[J,Ee]=this.evaluateArguments(W.args,de);Ee.size>0&&J.push(new he(Ee));const Fe=this.evaluate(W.callee,de);if(Fe.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${Fe.type}`);return Fe.value(J,de)}evaluateSliceExpression(W,de,J){if(!(W instanceof Se||W instanceof ae))throw new Error("Slice object must be an array or string");const Ee=this.evaluate(de.start,J),Fe=this.evaluate(de.stop,J),Ze=this.evaluate(de.step,J);if(!(Ee instanceof Xe||Ee instanceof We))throw new Error("Slice start must be numeric or undefined");if(!(Fe instanceof Xe||Fe instanceof We))throw new Error("Slice stop must be numeric or undefined");if(!(Ze instanceof Xe||Ze instanceof We))throw new Error("Slice step must be numeric or undefined");return W instanceof Se?new Se(le(W.value,Ee.value,Fe.value,Ze.value)):new ae(le(Array.from(W.value),Ee.value,Fe.value,Ze.value).join(""))}evaluateMemberExpression(W,de){const J=this.evaluate(W.object,de);let Ee;if(W.computed){if(W.property.type==="SliceExpression")return this.evaluateSliceExpression(J,W.property,de);Ee=this.evaluate(W.property,de)}else Ee=new ae(W.property.value);let Fe;if(J instanceof Ve){if(!(Ee instanceof ae))throw new Error(`Cannot access property with non-string: got ${Ee.type}`);Fe=J.value.get(Ee.value)??J.builtins.get(Ee.value)}else if(J instanceof Se||J instanceof ae)if(Ee instanceof Xe)Fe=J.value.at(Ee.value),J instanceof ae&&(Fe=new ae(J.value.at(Ee.value)));else if(Ee instanceof ae)Fe=J.builtins.get(Ee.value);else throw new Error(`Cannot access property with non-string/non-number: got ${Ee.type}`);else{if(!(Ee instanceof ae))throw new Error(`Cannot access property with non-string: got ${Ee.type}`);Fe=J.builtins.get(Ee.value)}return Fe instanceof Re?Fe:new We}evaluateSet(W,de){const J=this.evaluate(W.value,de);if(W.assignee.type==="Identifier"){const Ee=W.assignee.value;de.setVariable(Ee,J)}else if(W.assignee.type==="MemberExpression"){const Ee=W.assignee,Fe=this.evaluate(Ee.object,de);if(!(Fe instanceof Ve))throw new Error("Cannot assign to member of non-object");if(Ee.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");Fe.value.set(Ee.property.value,J)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(W.assignee)}`);return new Ge}evaluateIf(W,de){const J=this.evaluate(W.test,de);return this.evaluateBlock(J.__bool__().value?W.body:W.alternate,de)}evaluateFor(W,de){const J=new st(de);let Ee,Fe;if(W.iterable.type==="SelectExpression"){const Ct=W.iterable;Fe=this.evaluate(Ct.iterable,J),Ee=Ct.test}else Fe=this.evaluate(W.iterable,J);if(!(Fe instanceof Se))throw new Error(`Expected iterable type in for loop: got ${Fe.type}`);const Ze=[],rt=[];for(let Ct=0;CtRr.setVariable(W.loopvar.value,Nt);else if(W.loopvar.type==="TupleLiteral"){const Rr=W.loopvar;if(Nt.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${Nt.type}`);const Yr=Nt;if(Rr.value.length!==Yr.value.length)throw new Error(`Too ${Rr.value.length>Yr.value.length?"few":"many"} items to unpack`);br=nn=>{for(let $n=0;$n0?Ze[Ct-1]:new We],["nextitem",Ct{var rt;const Fe=new st(Ee);J=J.slice();let Ze;((rt=J.at(-1))==null?void 0:rt.type)==="KeywordArgumentsValue"&&(Ze=J.pop());for(let dt=0;dtthis.evaluate(J,de)));case"TupleLiteral":return new Ke(W.value.map(J=>this.evaluate(J,de)));case"ObjectLiteral":{const J=new Map;for(const[Ee,Fe]of W.value){const Ze=this.evaluate(Ee,de);if(!(Ze instanceof ae))throw new Error(`Object keys must be strings: got ${Ze.type}`);J.set(Ze.value,this.evaluate(Fe,de))}return new Ve(J)}case"Identifier":return this.evaluateIdentifier(W,de);case"CallExpression":return this.evaluateCallExpression(W,de);case"MemberExpression":return this.evaluateMemberExpression(W,de);case"UnaryExpression":return this.evaluateUnaryExpression(W,de);case"BinaryExpression":return this.evaluateBinaryExpression(W,de);case"FilterExpression":return this.evaluateFilterExpression(W,de);case"TestExpression":return this.evaluateTestExpression(W,de);default:throw new SyntaxError(`Unknown node type: ${W.type}`)}}};function mt(W){switch(typeof W){case"number":return new Xe(W);case"string":return new ae(W);case"boolean":return new He(W);case"undefined":return new We;case"object":return W===null?new Ge:Array.isArray(W)?new Se(W.map(mt)):new Ve(new Map(Object.entries(W).map(([de,J])=>[de,mt(J)])));case"function":return new qe((de,J)=>{const Ee=W(...de.map(Fe=>Fe.value))??null;return mt(Ee)});default:throw new Error(`Cannot convert to runtime value: ${W}`)}}function ct(W,de,J){const Ee=J??0;switch(W.type){case"NullValue":case"UndefinedValue":return"null";case"NumericValue":case"StringValue":case"BooleanValue":return JSON.stringify(W.value);case"ArrayValue":case"ObjectValue":{const Fe=de?" ".repeat(de):"",Ze=` `+Fe.repeat(Ee),rt=Ze+Fe;if(W.type==="ArrayValue"){const dt=W.value.map(bt=>ct(bt,de,Ee+1));return de?`[${rt}${dt.join(`,${rt}`)}${Ze}]`:`[${dt.join(", ")}]`}else{const dt=Array.from(W.value.entries()).map(([bt,Ct])=>{const Lt=`"${bt}": ${ct(Ct,de,Ee+1)}`;return de?`${rt}${Lt}`:Lt});return de?`{${dt.join(",")}${Ze}}`:`{${dt.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${W.type}`)}}var gt=class{constructor(W){we(this,"parsed");const de=y(W,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=pe(de)}render(W){const de=new st;de.set("false",!1),de.set("true",!0),de.set("raise_exception",Fe=>{throw new Error(Fe)}),de.set("range",X);for(const[Fe,Ze]of Object.entries(W))de.set(Fe,Ze);return new ht(de).run(this.parsed).value}}},"./node_modules/onnxruntime-common/dist/esm/backend-impl.js":(r,e,t)=>{t.r(e),t.d(e,{registerBackend:()=>o,resolveBackendAndExecutionProviders:()=>d});const n=new Map,a=[],o=(c,h,_)=>{if(h&&typeof h.init=="function"&&typeof h.createInferenceSessionHandler=="function"){const y=n.get(c);if(y===void 0)n.set(c,{backend:h,priority:_});else{if(y.priority>_)return;if(y.priority===_&&y.backend!==h)throw new Error(`cannot register backend "${c}" using priority ${_}`)}if(_>=0){const w=a.indexOf(c);w!==-1&&a.splice(w,1);for(let M=0;M{const h=n.get(c);if(!h)return"backend not found.";if(h.initialized)return h.backend;if(h.aborted)return h.error;{const _=!!h.initPromise;try{return _||(h.initPromise=h.backend.init(c)),await h.initPromise,h.initialized=!0,h.backend}catch(y){return _||(h.error=`${y}`,h.aborted=!0),h.error}finally{delete h.initPromise}}},d=async c=>{const h=c.executionProviders||[],_=h.map(H=>typeof H=="string"?H:H.name),y=_.length===0?a:_;let w;const M=[],S=new Set;for(const H of y){const B=await u(H);typeof B=="string"?M.push({name:H,err:B}):(w||(w=B),w===B&&S.add(H))}if(!w)throw new Error(`no available backend found. ERR: ${M.map(H=>`[${H.name}] ${H.err}`).join(", ")}`);for(const{name:H,err:B}of M)_.includes(H)&&console.warn(`removing requested execution provider "${H}" from session options because it is not available: ${B}`);const G=h.filter(H=>S.has(typeof H=="string"?H:H.name));return[w,new Proxy(c,{get:(H,B)=>B==="executionProviders"?G:Reflect.get(H,B)})]}},"./node_modules/onnxruntime-common/dist/esm/backend.js":(r,e,t)=>{t.r(e),t.d(e,{registerBackend:()=>n.registerBackend});var n=t("./node_modules/onnxruntime-common/dist/esm/backend-impl.js")},"./node_modules/onnxruntime-common/dist/esm/env-impl.js":(r,e,t)=>{t.r(e),t.d(e,{env:()=>o});var n=t("./node_modules/onnxruntime-common/dist/esm/version.js");let a="warning";const o={wasm:{},webgl:{},webgpu:{},versions:{common:n.version},set logLevel(u){if(u!==void 0){if(typeof u!="string"||["verbose","info","warning","error","fatal"].indexOf(u)===-1)throw new Error(`Unsupported logging level: ${u}`);a=u}},get logLevel(){return a}};Object.defineProperty(o,"logLevel",{enumerable:!0})},"./node_modules/onnxruntime-common/dist/esm/env.js":(r,e,t)=>{t.r(e),t.d(e,{env:()=>a});var n=t("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const a=n.env},"./node_modules/onnxruntime-common/dist/esm/index.js":(r,e,t)=>{t.r(e),t.d(e,{InferenceSession:()=>o.InferenceSession,TRACE:()=>d.TRACE,TRACE_FUNC_BEGIN:()=>d.TRACE_FUNC_BEGIN,TRACE_FUNC_END:()=>d.TRACE_FUNC_END,Tensor:()=>u.Tensor,TrainingSession:()=>c.TrainingSession,env:()=>a.env,registerBackend:()=>n.registerBackend});var n=t("./node_modules/onnxruntime-common/dist/esm/backend.js"),a=t("./node_modules/onnxruntime-common/dist/esm/env.js"),o=t("./node_modules/onnxruntime-common/dist/esm/inference-session.js"),u=t("./node_modules/onnxruntime-common/dist/esm/tensor.js");t("./node_modules/onnxruntime-common/dist/esm/tensor-conversion.js"),t("./node_modules/onnxruntime-common/dist/esm/tensor-factory.js");var d=t("./node_modules/onnxruntime-common/dist/esm/trace.js");t("./node_modules/onnxruntime-common/dist/esm/onnx-model.js"),t("./node_modules/onnxruntime-common/dist/esm/onnx-value.js");var c=t("./node_modules/onnxruntime-common/dist/esm/training-session.js")},"./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js":(r,e,t)=>{t.r(e),t.d(e,{InferenceSession:()=>u});var n=t("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),a=t("./node_modules/onnxruntime-common/dist/esm/tensor.js"),o=t("./node_modules/onnxruntime-common/dist/esm/trace.js");class u{constructor(c){this.handler=c}async run(c,h,_){(0,o.TRACE_FUNC_BEGIN)();const y={};let w={};if(typeof c!="object"||c===null||c instanceof a.Tensor||Array.isArray(c))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let M=!0;if(typeof h=="object"){if(h===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(h instanceof a.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(h)){if(h.length===0)throw new TypeError("'fetches' cannot be an empty array.");M=!1;for(const H of h){if(typeof H!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(H)===-1)throw new RangeError(`'fetches' contains invalid output name: ${H}.`);y[H]=null}if(typeof _=="object"&&_!==null)w=_;else if(typeof _<"u")throw new TypeError("'options' must be an object.")}else{let H=!1;const B=Object.getOwnPropertyNames(h);for(const z of this.outputNames)if(B.indexOf(z)!==-1){const U=h[z];(U===null||U instanceof a.Tensor)&&(H=!0,M=!1,y[z]=U)}if(H){if(typeof _=="object"&&_!==null)w=_;else if(typeof _<"u")throw new TypeError("'options' must be an object.")}else w=h}}else if(typeof h<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const H of this.inputNames)if(typeof c[H]>"u")throw new Error(`input '${H}' is missing in 'feeds'.`);if(M)for(const H of this.outputNames)y[H]=null;const S=await this.handler.run(c,y,w),G={};for(const H in S)if(Object.hasOwnProperty.call(S,H)){const B=S[H];B instanceof a.Tensor?G[H]=B:G[H]=new a.Tensor(B.type,B.data,B.dims)}return(0,o.TRACE_FUNC_END)(),G}async release(){return this.handler.dispose()}static async create(c,h,_,y){(0,o.TRACE_FUNC_BEGIN)();let w,M={};if(typeof c=="string"){if(w=c,typeof h=="object"&&h!==null)M=h;else if(typeof h<"u")throw new TypeError("'options' must be an object.")}else if(c instanceof Uint8Array){if(w=c,typeof h=="object"&&h!==null)M=h;else if(typeof h<"u")throw new TypeError("'options' must be an object.")}else if(c instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&c instanceof SharedArrayBuffer){const B=c;let z=0,U=c.byteLength;if(typeof h=="object"&&h!==null)M=h;else if(typeof h=="number"){if(z=h,!Number.isSafeInteger(z))throw new RangeError("'byteOffset' must be an integer.");if(z<0||z>=B.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${B.byteLength}).`);if(U=c.byteLength-z,typeof _=="number"){if(U=_,!Number.isSafeInteger(U))throw new RangeError("'byteLength' must be an integer.");if(U<=0||z+U>B.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${B.byteLength-z}].`);if(typeof y=="object"&&y!==null)M=y;else if(typeof y<"u")throw new TypeError("'options' must be an object.")}else if(typeof _<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof h<"u")throw new TypeError("'options' must be an object.");w=new Uint8Array(B,z,U)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const[S,G]=await(0,n.resolveBackendAndExecutionProviders)(M),H=await S.createInferenceSessionHandler(w,G);return(0,o.TRACE_FUNC_END)(),new u(H)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}},"./node_modules/onnxruntime-common/dist/esm/inference-session.js":(r,e,t)=>{t.r(e),t.d(e,{InferenceSession:()=>a});var n=t("./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js");const a=n.InferenceSession},"./node_modules/onnxruntime-common/dist/esm/onnx-model.js":(r,e,t)=>{t.r(e)},"./node_modules/onnxruntime-common/dist/esm/onnx-value.js":(r,e,t)=>{t.r(e)},"./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js":(r,e,t)=>{t.r(e),t.d(e,{tensorToDataURL:()=>n,tensorToImageData:()=>a});const n=(o,u)=>{const d=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);d.width=o.dims[3],d.height=o.dims[2];const c=d.getContext("2d");if(c!=null){let h,_;(u==null?void 0:u.tensorLayout)!==void 0&&u.tensorLayout==="NHWC"?(h=o.dims[2],_=o.dims[3]):(h=o.dims[3],_=o.dims[2]);const y=(u==null?void 0:u.format)!==void 0?u.format:"RGB",w=u==null?void 0:u.norm;let M,S;w===void 0||w.mean===void 0?M=[255,255,255,255]:typeof w.mean=="number"?M=[w.mean,w.mean,w.mean,w.mean]:(M=[w.mean[0],w.mean[1],w.mean[2],0],w.mean[3]!==void 0&&(M[3]=w.mean[3])),w===void 0||w.bias===void 0?S=[0,0,0,0]:typeof w.bias=="number"?S=[w.bias,w.bias,w.bias,w.bias]:(S=[w.bias[0],w.bias[1],w.bias[2],0],w.bias[3]!==void 0&&(S[3]=w.bias[3]));const G=_*h;let H=0,B=G,z=G*2,U=-1;y==="RGBA"?(H=0,B=G,z=G*2,U=G*3):y==="RGB"?(H=0,B=G,z=G*2):y==="RBG"&&(H=0,z=G,B=G*2);for(let F=0;F<_;F++)for(let I=0;I{const d=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let c;if(d!=null){let h,_,y;(u==null?void 0:u.tensorLayout)!==void 0&&u.tensorLayout==="NHWC"?(h=o.dims[2],_=o.dims[1],y=o.dims[3]):(h=o.dims[3],_=o.dims[2],y=o.dims[1]);const w=u!==void 0&&u.format!==void 0?u.format:"RGB",M=u==null?void 0:u.norm;let S,G;M===void 0||M.mean===void 0?S=[255,255,255,255]:typeof M.mean=="number"?S=[M.mean,M.mean,M.mean,M.mean]:(S=[M.mean[0],M.mean[1],M.mean[2],255],M.mean[3]!==void 0&&(S[3]=M.mean[3])),M===void 0||M.bias===void 0?G=[0,0,0,0]:typeof M.bias=="number"?G=[M.bias,M.bias,M.bias,M.bias]:(G=[M.bias[0],M.bias[1],M.bias[2],0],M.bias[3]!==void 0&&(G[3]=M.bias[3]));const H=_*h;if(u!==void 0&&(u.format!==void 0&&y===4&&u.format!=="RGBA"||y===3&&u.format!=="RGB"&&u.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const B=4;let z=0,U=1,F=2,I=3,k=0,$=H,j=H*2,ce=-1;w==="RGBA"?(k=0,$=H,j=H*2,ce=H*3):w==="RGB"?(k=0,$=H,j=H*2):w==="RBG"&&(k=0,j=H,$=H*2),c=d.createImageData(h,_);for(let ue=0;ue<_*h;z+=B,U+=B,F+=B,I+=B,ue++)c.data[z]=(o.data[k++]-G[0])*S[0],c.data[U]=(o.data[$++]-G[1])*S[1],c.data[F]=(o.data[j++]-G[2])*S[2],c.data[I]=ce===-1?255:(o.data[ce++]-G[3])*S[3]}else throw new Error("Can not access image data");return c}},"./node_modules/onnxruntime-common/dist/esm/tensor-conversion.js":(r,e,t)=>{t.r(e)},"./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js":(r,e,t)=>{t.r(e),t.d(e,{bufferToTensor:()=>a,tensorFromGpuBuffer:()=>d,tensorFromImage:()=>o,tensorFromMLTensor:()=>c,tensorFromPinnedBuffer:()=>h,tensorFromTexture:()=>u});var n=t("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const a=(_,y)=>{if(_===void 0)throw new Error("Image buffer must be defined");if(y.height===void 0||y.width===void 0)throw new Error("Image height and width must be defined");if(y.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");const{height:w,width:M}=y,S=y.norm??{mean:255,bias:0};let G,H;typeof S.mean=="number"?G=[S.mean,S.mean,S.mean,S.mean]:G=[S.mean[0],S.mean[1],S.mean[2],S.mean[3]??255],typeof S.bias=="number"?H=[S.bias,S.bias,S.bias,S.bias]:H=[S.bias[0],S.bias[1],S.bias[2],S.bias[3]??0];const B=y.format!==void 0?y.format:"RGBA",z=y.tensorFormat!==void 0&&y.tensorFormat!==void 0?y.tensorFormat:"RGB",U=w*M,F=z==="RGBA"?new Float32Array(U*4):new Float32Array(U*3);let I=4,k=0,$=1,j=2,ce=3,ue=0,Pe=U,Te=U*2,ie=-1;B==="RGB"&&(I=3,k=0,$=1,j=2,ce=-1),z==="RGBA"?ie=U*3:z==="RBG"?(ue=0,Te=U,Pe=U*2):z==="BGR"&&(Te=0,Pe=U,ue=U*2);for(let re=0;re{const w=typeof HTMLImageElement<"u"&&_ instanceof HTMLImageElement,M=typeof ImageData<"u"&&_ instanceof ImageData,S=typeof ImageBitmap<"u"&&_ instanceof ImageBitmap,G=typeof _=="string";let H,B=y??{};const z=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},U=F=>typeof HTMLCanvasElement<"u"&&F instanceof HTMLCanvasElement||F instanceof OffscreenCanvas?F.getContext("2d"):null;if(w){const F=z();F.width=_.width,F.height=_.height;const I=U(F);if(I!=null){let k=_.height,$=_.width;if(y!==void 0&&y.resizedHeight!==void 0&&y.resizedWidth!==void 0&&(k=y.resizedHeight,$=y.resizedWidth),y!==void 0){if(B=y,y.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");B.tensorFormat="RGBA",B.height=k,B.width=$}else B.tensorFormat="RGBA",B.height=k,B.width=$;I.drawImage(_,0,0),H=I.getImageData(0,0,$,k).data}else throw new Error("Can not access image data")}else if(M){let F,I;if(y!==void 0&&y.resizedWidth!==void 0&&y.resizedHeight!==void 0?(F=y.resizedHeight,I=y.resizedWidth):(F=_.height,I=_.width),y!==void 0&&(B=y),B.format="RGBA",B.height=F,B.width=I,y!==void 0){const k=z();k.width=I,k.height=F;const $=U(k);if($!=null)$.putImageData(_,0,0),H=$.getImageData(0,0,I,F).data;else throw new Error("Can not access image data")}else H=_.data}else if(S){if(y===void 0)throw new Error("Please provide image config with format for Imagebitmap");const F=z();F.width=_.width,F.height=_.height;const I=U(F);if(I!=null){const k=_.height,$=_.width;return I.drawImage(_,0,0,$,k),H=I.getImageData(0,0,$,k).data,B.height=k,B.width=$,a(H,B)}else throw new Error("Can not access image data")}else{if(G)return new Promise((F,I)=>{const k=z(),$=U(k);if(!_||!$)return I();const j=new Image;j.crossOrigin="Anonymous",j.src=_,j.onload=()=>{k.width=j.width,k.height=j.height,$.drawImage(j,0,0,k.width,k.height);const ce=$.getImageData(0,0,k.width,k.height);B.height=k.height,B.width=k.width,F(a(ce.data,B))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(H!==void 0)return a(H,B);throw new Error("Input data provided is not supported - aborted tensor creation")},u=(_,y)=>{const{width:w,height:M,download:S,dispose:G}=y,H=[1,M,w,4];return new n.Tensor({location:"texture",type:"float32",texture:_,dims:H,download:S,dispose:G})},d=(_,y)=>{const{dataType:w,dims:M,download:S,dispose:G}=y;return new n.Tensor({location:"gpu-buffer",type:w??"float32",gpuBuffer:_,dims:M,download:S,dispose:G})},c=(_,y)=>{const{dataType:w,dims:M,download:S,dispose:G}=y;return new n.Tensor({location:"ml-tensor",type:w??"float32",mlTensor:_,dims:M,download:S,dispose:G})},h=(_,y,w)=>new n.Tensor({location:"cpu-pinned",type:_,data:y,dims:w??[y.length]})},"./node_modules/onnxruntime-common/dist/esm/tensor-factory.js":(r,e,t)=>{t.r(e)},"./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js":(r,e,t)=>{t.r(e),t.d(e,{NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP:()=>a,NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP:()=>n,checkTypedArray:()=>u});const n=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),a=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let o=!1;const u=()=>{if(!o){o=!0;const d=typeof BigInt64Array<"u"&&BigInt64Array.from,c=typeof BigUint64Array<"u"&&BigUint64Array.from,h=typeof Float16Array<"u"&&Float16Array.from;d&&(n.set("int64",BigInt64Array),a.set(BigInt64Array,"int64")),c&&(n.set("uint64",BigUint64Array),a.set(BigUint64Array,"uint64")),h?(n.set("float16",Float16Array),a.set(Float16Array,"float16")):n.set("float16",Uint16Array)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-impl.js":(r,e,t)=>{t.r(e),t.d(e,{Tensor:()=>d});var n=t("./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js"),a=t("./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js"),o=t("./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js"),u=t("./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js");class d{constructor(h,_,y){(0,o.checkTypedArray)();let w,M;if(typeof h=="object"&&"location"in h)switch(this.dataLocation=h.location,w=h.type,M=h.dims,h.location){case"cpu-pinned":{const G=o.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(w);if(!G)throw new TypeError(`unsupported type "${w}" to create tensor from pinned buffer`);if(!(h.data instanceof G))throw new TypeError(`buffer should be of type ${G.name}`);this.cpuData=h.data;break}case"texture":{if(w!=="float32")throw new TypeError(`unsupported type "${w}" to create tensor from texture`);this.gpuTextureData=h.texture,this.downloader=h.download,this.disposer=h.dispose;break}case"gpu-buffer":{if(w!=="float32"&&w!=="float16"&&w!=="int32"&&w!=="int64"&&w!=="uint32"&&w!=="uint8"&&w!=="bool"&&w!=="uint4"&&w!=="int4")throw new TypeError(`unsupported type "${w}" to create tensor from gpu buffer`);this.gpuBufferData=h.gpuBuffer,this.downloader=h.download,this.disposer=h.dispose;break}case"ml-tensor":{if(w!=="float32"&&w!=="float16"&&w!=="int32"&&w!=="int64"&&w!=="uint32"&&w!=="uint64"&&w!=="int8"&&w!=="uint8"&&w!=="bool")throw new TypeError(`unsupported type "${w}" to create tensor from MLTensor`);this.mlTensorData=h.mlTensor,this.downloader=h.download,this.disposer=h.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let G,H;if(typeof h=="string")if(w=h,H=y,h==="string"){if(!Array.isArray(_))throw new TypeError("A string tensor's data must be a string array.");G=_}else{const B=o.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(h);if(B===void 0)throw new TypeError(`Unsupported tensor type: ${h}.`);if(Array.isArray(_)){if(h==="float16"&&B===Uint16Array||h==="uint4"||h==="int4")throw new TypeError(`Creating a ${h} tensor from number array is not supported. Please use ${B.name} as data.`);h==="uint64"||h==="int64"?G=B.from(_,BigInt):G=B.from(_)}else if(_ instanceof B)G=_;else if(_ instanceof Uint8ClampedArray)if(h==="uint8")G=Uint8Array.from(_);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else throw new TypeError(`A ${w} tensor's data must be type of ${B}`)}else if(H=_,Array.isArray(h)){if(h.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const B=typeof h[0];if(B==="string")w="string",G=h;else if(B==="boolean")w="bool",G=Uint8Array.from(h);else throw new TypeError(`Invalid element type of data array: ${B}.`)}else if(h instanceof Uint8ClampedArray)w="uint8",G=Uint8Array.from(h);else{const B=o.NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(h.constructor);if(B===void 0)throw new TypeError(`Unsupported type for tensor data: ${h.constructor}.`);w=B,G=h}if(H===void 0)H=[G.length];else if(!Array.isArray(H))throw new TypeError("A tensor's dims must be a number array");M=H,this.cpuData=G,this.dataLocation="cpu"}const S=(0,u.calculateSize)(M);if(this.cpuData&&S!==this.cpuData.length&&!((w==="uint4"||w==="int4")&&Math.ceil(S/2)===this.cpuData.length))throw new Error(`Tensor's size(${S}) does not match data length(${this.cpuData.length}).`);this.type=w,this.dims=M,this.size=S}static async fromImage(h,_){return(0,a.tensorFromImage)(h,_)}static fromTexture(h,_){return(0,a.tensorFromTexture)(h,_)}static fromGpuBuffer(h,_){return(0,a.tensorFromGpuBuffer)(h,_)}static fromMLTensor(h,_){return(0,a.tensorFromMLTensor)(h,_)}static fromPinnedBuffer(h,_,y){return(0,a.tensorFromPinnedBuffer)(h,_,y)}toDataURL(h){return(0,n.tensorToDataURL)(this,h)}toImageData(h){return(0,n.tensorToImageData)(this,h)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(h){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;const _=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=_,h&&this.disposer&&(this.disposer(),this.disposer=void 0),_}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(h){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return(0,u.tensorReshape)(this,h)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js":(r,e,t)=>{t.r(e),t.d(e,{calculateSize:()=>a,tensorReshape:()=>o});var n=t("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const a=u=>{let d=1;for(let c=0;c{switch(u.location){case"cpu":return new n.Tensor(u.type,u.data,d);case"cpu-pinned":return new n.Tensor({location:"cpu-pinned",data:u.data,type:u.type,dims:d});case"texture":return new n.Tensor({location:"texture",texture:u.texture,type:u.type,dims:d});case"gpu-buffer":return new n.Tensor({location:"gpu-buffer",gpuBuffer:u.gpuBuffer,type:u.type,dims:d});case"ml-tensor":return new n.Tensor({location:"ml-tensor",mlTensor:u.mlTensor,type:u.type,dims:d});default:throw new Error(`tensorReshape: tensor location ${u.location} is not supported`)}}},"./node_modules/onnxruntime-common/dist/esm/tensor.js":(r,e,t)=>{t.r(e),t.d(e,{Tensor:()=>a});var n=t("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const a=n.Tensor},"./node_modules/onnxruntime-common/dist/esm/trace.js":(r,e,t)=>{t.r(e),t.d(e,{TRACE:()=>a,TRACE_FUNC_BEGIN:()=>u,TRACE_FUNC_END:()=>d});var n=t("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const a=(c,h)=>{(typeof n.env.trace>"u"?!n.env.wasm.trace:!n.env.trace)||console.timeStamp(`${c}::ORT::${h}`)},o=(c,h)=>{var w;const _=((w=new Error().stack)==null?void 0:w.split(/\r\n|\r|\n/g))||[];let y=!1;for(let M=0;M<_.length;M++){if(y&&!_[M].includes("TRACE_FUNC")){let S=`FUNC_${c}::${_[M].trim().split(" ")[1]}`;h&&(S+=`::${h}`),a("CPU",S);return}_[M].includes("TRACE_FUNC")&&(y=!0)}},u=c=>{(typeof n.env.trace>"u"?!n.env.wasm.trace:!n.env.trace)||o("BEGIN",c)},d=c=>{(typeof n.env.trace>"u"?!n.env.wasm.trace:!n.env.trace)||o("END",c)}},"./node_modules/onnxruntime-common/dist/esm/training-session-impl.js":(r,e,t)=>{t.r(e),t.d(e,{TrainingSession:()=>u});var n=t("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),a=t("./node_modules/onnxruntime-common/dist/esm/tensor.js");const o="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.";class u{constructor(c,h,_){this.handler=c,this.hasOptimizerModel=h,this.hasEvalModel=_}get trainingInputNames(){return this.handler.inputNames}get trainingOutputNames(){return this.handler.outputNames}get evalInputNames(){if(this.hasEvalModel)return this.handler.evalInputNames;throw new Error("This training session has no evalModel loaded.")}get evalOutputNames(){if(this.hasEvalModel)return this.handler.evalOutputNames;throw new Error("This training session has no evalModel loaded.")}static async create(c,h){const _=c.evalModel||"",y=c.optimizerModel||"",w=h||{},[M,S]=await(0,n.resolveBackendAndExecutionProviders)(w);if(M.createTrainingSessionHandler){const G=await M.createTrainingSessionHandler(c.checkpointState,c.trainModel,_,y,S);return new u(G,!!c.optimizerModel,!!c.evalModel)}else throw new Error(o)}typeNarrowingForRunStep(c,h,_,y,w){const M={};let S={};if(typeof _!="object"||_===null||_ instanceof a.Tensor||Array.isArray(_))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let G=!0;if(typeof y=="object"){if(y===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(y instanceof a.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(y)){if(y.length===0)throw new TypeError("'fetches' cannot be an empty array.");G=!1;for(const H of y){if(typeof H!="string")throw new TypeError("'fetches' must be a string array or an object.");if(h.indexOf(H)===-1)throw new RangeError(`'fetches' contains invalid output name: ${H}.`);M[H]=null}if(typeof w=="object"&&w!==null)S=w;else if(typeof w<"u")throw new TypeError("'options' must be an object.")}else{let H=!1;const B=Object.getOwnPropertyNames(y);for(const z of h)if(B.indexOf(z)!==-1){const U=y[z];(U===null||U instanceof a.Tensor)&&(H=!0,G=!1,M[z]=U)}if(H){if(typeof w=="object"&&w!==null)S=w;else if(typeof w<"u")throw new TypeError("'options' must be an object.")}else S=y}}else if(typeof y<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const H of c)if(typeof _[H]>"u")throw new Error(`input '${H}' is missing in 'feeds'.`);if(G)for(const H of h)M[H]=null;return[M,S]}convertHandlerReturnTypeToMapOfTensors(c){const h={};for(const _ in c)if(Object.hasOwnProperty.call(c,_)){const y=c[_];y instanceof a.Tensor?h[_]=y:h[_]=new a.Tensor(y.type,y.data,y.dims)}return h}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(c,h,_){const[y,w]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,c,h,_),M=await this.handler.runTrainStep(c,y,w);return this.convertHandlerReturnTypeToMapOfTensors(M)}async runOptimizerStep(c){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(c||{});else throw new Error("This TrainingSession has no OptimizerModel loaded.")}async runEvalStep(c,h,_){if(this.hasEvalModel){const[y,w]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,c,h,_),M=await this.handler.runEvalStep(c,y,w);return this.convertHandlerReturnTypeToMapOfTensors(M)}else throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(c=!0){return this.handler.getParametersSize(c)}async loadParametersBuffer(c,h=!0){const _=await this.getParametersSize(h);if(c.length!==4*_)throw new Error("Size of the buffer passed into loadParametersBuffer must match the number of parameters in the model. Please use getParametersSize method to check.");return this.handler.loadParametersBuffer(c,h)}async getContiguousParameters(c=!0){return this.handler.getContiguousParameters(c)}async release(){return this.handler.dispose()}}},"./node_modules/onnxruntime-common/dist/esm/training-session.js":(r,e,t)=>{t.r(e),t.d(e,{TrainingSession:()=>a});var n=t("./node_modules/onnxruntime-common/dist/esm/training-session-impl.js");const a=n.TrainingSession},"./node_modules/onnxruntime-common/dist/esm/version.js":(r,e,t)=>{t.r(e),t.d(e,{version:()=>n});const n="1.20.1"},"./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs?3a96":(r,e,t)=>{t.r(e),t.d(e,{InferenceSession:()=>ct,TRACE:()=>Ke,TRACE_FUNC_BEGIN:()=>Ge,TRACE_FUNC_END:()=>We,Tensor:()=>he,default:()=>Vv,env:()=>j,registerBackend:()=>S});/*! * ONNX Runtime Web v1.21.0-dev.20250114-228dd16893 * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */var n=Object.defineProperty,a=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,u=Object.prototype.hasOwnProperty,d=(s=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(s,{get:(i,l)=>(typeof require<"u"?require:i)[l]}):s)(function(s){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')}),c=(s,i)=>()=>(s&&(i=s(s=0)),i),h=(s,i)=>{for(var l in i)n(s,l,{get:i[l],enumerable:!0})},_=(s,i,l,f)=>{if(i&&typeof i=="object"||typeof i=="function")for(let p of o(i))!u.call(s,p)&&p!==l&&n(s,p,{get:()=>i[p],enumerable:!(f=a(i,p))||f.enumerable});return s},y=s=>_(n({},"__esModule",{value:!0}),s),w,M,S,G,H,B=c(()=>{w=new Map,M=[],S=(s,i,l)=>{if(i&&typeof i.init=="function"&&typeof i.createInferenceSessionHandler=="function"){let f=w.get(s);if(f===void 0)w.set(s,{backend:i,priority:l});else{if(f.priority>l)return;if(f.priority===l&&f.backend!==i)throw new Error(`cannot register backend "${s}" using priority ${l}`)}if(l>=0){let p=M.indexOf(s);p!==-1&&M.splice(p,1);for(let g=0;g{let i=w.get(s);if(!i)return"backend not found.";if(i.initialized)return i.backend;if(i.aborted)return i.error;{let l=!!i.initPromise;try{return l||(i.initPromise=i.backend.init(s)),await i.initPromise,i.initialized=!0,i.backend}catch(f){return l||(i.error=`${f}`,i.aborted=!0),i.error}finally{delete i.initPromise}}},H=async s=>{let i=s.executionProviders||[],l=i.map(x=>typeof x=="string"?x:x.name),f=l.length===0?M:l,p,g=[],m=new Set;for(let x of f){let P=await G(x);typeof P=="string"?g.push({name:x,err:P}):(p||(p=P),p===P&&m.add(x))}if(!p)throw new Error(`no available backend found. ERR: ${g.map(x=>`[${x.name}] ${x.err}`).join(", ")}`);for(let{name:x,err:P}of g)l.includes(x)&&console.warn(`removing requested execution provider "${x}" from session options because it is not available: ${P}`);let v=i.filter(x=>m.has(typeof x=="string"?x:x.name));return[p,new Proxy(s,{get:(x,P)=>P==="executionProviders"?v:Reflect.get(x,P)})]}}),z=c(()=>{B()}),U,F=c(()=>{U="1.21.0-dev.20241212-1f88284f96"}),I,k,$=c(()=>{F(),I="warning",k={wasm:{},webgl:{},webgpu:{},versions:{common:U},set logLevel(s){if(s!==void 0){if(typeof s!="string"||["verbose","info","warning","error","fatal"].indexOf(s)===-1)throw new Error(`Unsupported logging level: ${s}`);I=s}},get logLevel(){return I}},Object.defineProperty(k,"logLevel",{enumerable:!0})}),j,ce=c(()=>{$(),j=k}),ue,Pe,Te=c(()=>{ue=(s,i)=>{let l=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);l.width=s.dims[3],l.height=s.dims[2];let f=l.getContext("2d");if(f!=null){let p,g;(i==null?void 0:i.tensorLayout)!==void 0&&i.tensorLayout==="NHWC"?(p=s.dims[2],g=s.dims[3]):(p=s.dims[3],g=s.dims[2]);let m=(i==null?void 0:i.format)!==void 0?i.format:"RGB",v=i==null?void 0:i.norm,x,P;v===void 0||v.mean===void 0?x=[255,255,255,255]:typeof v.mean=="number"?x=[v.mean,v.mean,v.mean,v.mean]:(x=[v.mean[0],v.mean[1],v.mean[2],0],v.mean[3]!==void 0&&(x[3]=v.mean[3])),v===void 0||v.bias===void 0?P=[0,0,0,0]:typeof v.bias=="number"?P=[v.bias,v.bias,v.bias,v.bias]:(P=[v.bias[0],v.bias[1],v.bias[2],0],v.bias[3]!==void 0&&(P[3]=v.bias[3]));let D=g*p,R=0,E=D,K=D*2,q=-1;m==="RGBA"?(R=0,E=D,K=D*2,q=D*3):m==="RGB"?(R=0,E=D,K=D*2):m==="RBG"&&(R=0,K=D,E=D*2);for(let Y=0;Y{let l=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),f;if(l!=null){let p,g,m;(i==null?void 0:i.tensorLayout)!==void 0&&i.tensorLayout==="NHWC"?(p=s.dims[2],g=s.dims[1],m=s.dims[3]):(p=s.dims[3],g=s.dims[2],m=s.dims[1]);let v=i!==void 0&&i.format!==void 0?i.format:"RGB",x=i==null?void 0:i.norm,P,D;x===void 0||x.mean===void 0?P=[255,255,255,255]:typeof x.mean=="number"?P=[x.mean,x.mean,x.mean,x.mean]:(P=[x.mean[0],x.mean[1],x.mean[2],255],x.mean[3]!==void 0&&(P[3]=x.mean[3])),x===void 0||x.bias===void 0?D=[0,0,0,0]:typeof x.bias=="number"?D=[x.bias,x.bias,x.bias,x.bias]:(D=[x.bias[0],x.bias[1],x.bias[2],0],x.bias[3]!==void 0&&(D[3]=x.bias[3]));let R=g*p;if(i!==void 0&&(i.format!==void 0&&m===4&&i.format!=="RGBA"||m===3&&i.format!=="RGB"&&i.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let E=4,K=0,q=1,Y=2,ne=3,se=0,te=R,ye=R*2,be=-1;v==="RGBA"?(se=0,te=R,ye=R*2,be=R*3):v==="RGB"?(se=0,te=R,ye=R*2):v==="RBG"&&(se=0,ye=R,te=R*2),f=l.createImageData(p,g);for(let Ce=0;Ce{Ve(),ie=(s,i)=>{if(s===void 0)throw new Error("Image buffer must be defined");if(i.height===void 0||i.width===void 0)throw new Error("Image height and width must be defined");if(i.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:l,width:f}=i,p=i.norm??{mean:255,bias:0},g,m;typeof p.mean=="number"?g=[p.mean,p.mean,p.mean,p.mean]:g=[p.mean[0],p.mean[1],p.mean[2],p.mean[3]??255],typeof p.bias=="number"?m=[p.bias,p.bias,p.bias,p.bias]:m=[p.bias[0],p.bias[1],p.bias[2],p.bias[3]??0];let v=i.format!==void 0?i.format:"RGBA",x=i.tensorFormat!==void 0&&i.tensorFormat!==void 0?i.tensorFormat:"RGB",P=l*f,D=x==="RGBA"?new Float32Array(P*4):new Float32Array(P*3),R=4,E=0,K=1,q=2,Y=3,ne=0,se=P,te=P*2,ye=-1;v==="RGB"&&(R=3,E=0,K=1,q=2,Y=-1),x==="RGBA"?ye=P*3:x==="RBG"?(ne=0,te=P,se=P*2):x==="BGR"&&(te=0,se=P,ne=P*2);for(let be=0;be{let l=typeof HTMLImageElement<"u"&&s instanceof HTMLImageElement,f=typeof ImageData<"u"&&s instanceof ImageData,p=typeof ImageBitmap<"u"&&s instanceof ImageBitmap,g=typeof s=="string",m,v=i??{},x=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},P=D=>typeof HTMLCanvasElement<"u"&&D instanceof HTMLCanvasElement||D instanceof OffscreenCanvas?D.getContext("2d"):null;if(l){let D=x();D.width=s.width,D.height=s.height;let R=P(D);if(R!=null){let E=s.height,K=s.width;if(i!==void 0&&i.resizedHeight!==void 0&&i.resizedWidth!==void 0&&(E=i.resizedHeight,K=i.resizedWidth),i!==void 0){if(v=i,i.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");v.tensorFormat="RGBA",v.height=E,v.width=K}else v.tensorFormat="RGBA",v.height=E,v.width=K;R.drawImage(s,0,0),m=R.getImageData(0,0,K,E).data}else throw new Error("Can not access image data")}else if(f){let D,R;if(i!==void 0&&i.resizedWidth!==void 0&&i.resizedHeight!==void 0?(D=i.resizedHeight,R=i.resizedWidth):(D=s.height,R=s.width),i!==void 0&&(v=i),v.format="RGBA",v.height=D,v.width=R,i!==void 0){let E=x();E.width=R,E.height=D;let K=P(E);if(K!=null)K.putImageData(s,0,0),m=K.getImageData(0,0,R,D).data;else throw new Error("Can not access image data")}else m=s.data}else if(p){if(i===void 0)throw new Error("Please provide image config with format for Imagebitmap");let D=x();D.width=s.width,D.height=s.height;let R=P(D);if(R!=null){let E=s.height,K=s.width;return R.drawImage(s,0,0,K,E),m=R.getImageData(0,0,K,E).data,v.height=E,v.width=K,ie(m,v)}else throw new Error("Can not access image data")}else{if(g)return new Promise((D,R)=>{let E=x(),K=P(E);if(!s||!K)return R();let q=new Image;q.crossOrigin="Anonymous",q.src=s,q.onload=()=>{E.width=q.width,E.height=q.height,K.drawImage(q,0,0,E.width,E.height);let Y=K.getImageData(0,0,E.width,E.height);v.height=E.height,v.width=E.width,D(ie(Y.data,v))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(m!==void 0)return ie(m,v);throw new Error("Input data provided is not supported - aborted tensor creation")},re=(s,i)=>{let{width:l,height:f,download:p,dispose:g}=i,m=[1,f,l,4];return new He({location:"texture",type:"float32",texture:s,dims:m,download:p,dispose:g})},ge=(s,i)=>{let{dataType:l,dims:f,download:p,dispose:g}=i;return new He({location:"gpu-buffer",type:l??"float32",gpuBuffer:s,dims:f,download:p,dispose:g})},ve=(s,i)=>{let{dataType:l,dims:f,download:p,dispose:g}=i;return new He({location:"ml-tensor",type:l??"float32",mlTensor:s,dims:f,download:p,dispose:g})},me=(s,i,l)=>new He({location:"cpu-pinned",type:s,data:i,dims:l??[i.length]})}),$e,pe,X,le,ke=c(()=>{$e=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),pe=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),X=!1,le=()=>{if(!X){X=!0;let s=typeof BigInt64Array<"u"&&BigInt64Array.from,i=typeof BigUint64Array<"u"&&BigUint64Array.from,l=typeof Float16Array<"u"&&Float16Array.from;s&&($e.set("int64",BigInt64Array),pe.set(BigInt64Array,"int64")),i&&($e.set("uint64",BigUint64Array),pe.set(BigUint64Array,"uint64")),l?($e.set("float16",Float16Array),pe.set(Float16Array,"float16")):$e.set("float16",Uint16Array)}}}),Re,Xe,ae=c(()=>{Ve(),Re=s=>{let i=1;for(let l=0;l{switch(s.location){case"cpu":return new He(s.type,s.data,i);case"cpu-pinned":return new He({location:"cpu-pinned",data:s.data,type:s.type,dims:i});case"texture":return new He({location:"texture",texture:s.texture,type:s.type,dims:i});case"gpu-buffer":return new He({location:"gpu-buffer",gpuBuffer:s.gpuBuffer,type:s.type,dims:i});case"ml-tensor":return new He({location:"ml-tensor",mlTensor:s.mlTensor,type:s.type,dims:i});default:throw new Error(`tensorReshape: tensor location ${s.location} is not supported`)}}}),He,Ve=c(()=>{Te(),Le(),ke(),ae(),He=class{constructor(s,i,l){le();let f,p;if(typeof s=="object"&&"location"in s)switch(this.dataLocation=s.location,f=s.type,p=s.dims,s.location){case"cpu-pinned":{let m=$e.get(f);if(!m)throw new TypeError(`unsupported type "${f}" to create tensor from pinned buffer`);if(!(s.data instanceof m))throw new TypeError(`buffer should be of type ${m.name}`);this.cpuData=s.data;break}case"texture":{if(f!=="float32")throw new TypeError(`unsupported type "${f}" to create tensor from texture`);this.gpuTextureData=s.texture,this.downloader=s.download,this.disposer=s.dispose;break}case"gpu-buffer":{if(f!=="float32"&&f!=="float16"&&f!=="int32"&&f!=="int64"&&f!=="uint32"&&f!=="uint8"&&f!=="bool"&&f!=="uint4"&&f!=="int4")throw new TypeError(`unsupported type "${f}" to create tensor from gpu buffer`);this.gpuBufferData=s.gpuBuffer,this.downloader=s.download,this.disposer=s.dispose;break}case"ml-tensor":{if(f!=="float32"&&f!=="float16"&&f!=="int32"&&f!=="int64"&&f!=="uint32"&&f!=="uint64"&&f!=="int8"&&f!=="uint8"&&f!=="bool"&&f!=="uint4"&&f!=="int4")throw new TypeError(`unsupported type "${f}" to create tensor from MLTensor`);this.mlTensorData=s.mlTensor,this.downloader=s.download,this.disposer=s.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let m,v;if(typeof s=="string")if(f=s,v=l,s==="string"){if(!Array.isArray(i))throw new TypeError("A string tensor's data must be a string array.");m=i}else{let x=$e.get(s);if(x===void 0)throw new TypeError(`Unsupported tensor type: ${s}.`);if(Array.isArray(i)){if(s==="float16"&&x===Uint16Array||s==="uint4"||s==="int4")throw new TypeError(`Creating a ${s} tensor from number array is not supported. Please use ${x.name} as data.`);s==="uint64"||s==="int64"?m=x.from(i,BigInt):m=x.from(i)}else if(i instanceof x)m=i;else if(i instanceof Uint8ClampedArray)if(s==="uint8")m=Uint8Array.from(i);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else throw new TypeError(`A ${f} tensor's data must be type of ${x}`)}else if(v=i,Array.isArray(s)){if(s.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let x=typeof s[0];if(x==="string")f="string",m=s;else if(x==="boolean")f="bool",m=Uint8Array.from(s);else throw new TypeError(`Invalid element type of data array: ${x}.`)}else if(s instanceof Uint8ClampedArray)f="uint8",m=Uint8Array.from(s);else{let x=pe.get(s.constructor);if(x===void 0)throw new TypeError(`Unsupported type for tensor data: ${s.constructor}.`);f=x,m=s}if(v===void 0)v=[m.length];else if(!Array.isArray(v))throw new TypeError("A tensor's dims must be a number array");p=v,this.cpuData=m,this.dataLocation="cpu"}let g=Re(p);if(this.cpuData&&g!==this.cpuData.length&&!((f==="uint4"||f==="int4")&&Math.ceil(g/2)===this.cpuData.length))throw new Error(`Tensor's size(${g}) does not match data length(${this.cpuData.length}).`);this.type=f,this.dims=p,this.size=g}static async fromImage(s,i){return oe(s,i)}static fromTexture(s,i){return re(s,i)}static fromGpuBuffer(s,i){return ge(s,i)}static fromMLTensor(s,i){return ve(s,i)}static fromPinnedBuffer(s,i,l){return me(s,i,l)}toDataURL(s){return ue(this,s)}toImageData(s){return Pe(this,s)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(s){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let i=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=i,s&&this.disposer&&(this.disposer(),this.disposer=void 0),i}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(s){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return Xe(this,s)}}}),he,Se=c(()=>{Ve(),he=He}),Ke,qe,Ge,We,st=c(()=>{$(),Ke=(s,i)=>{(typeof k.trace>"u"?!k.wasm.trace:!k.trace)||console.timeStamp(`${s}::ORT::${i}`)},qe=(s,i)=>{var p;let l=((p=new Error().stack)==null?void 0:p.split(/\r\n|\r|\n/g))||[],f=!1;for(let g=0;g{(typeof k.trace>"u"?!k.wasm.trace:!k.trace)||qe("BEGIN",s)},We=s=>{(typeof k.trace>"u"?!k.wasm.trace:!k.trace)||qe("END",s)}}),ht,mt=c(()=>{B(),Se(),st(),ht=class rw{constructor(i){this.handler=i}async run(i,l,f){Ge();let p={},g={};if(typeof i!="object"||i===null||i instanceof he||Array.isArray(i))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let m=!0;if(typeof l=="object"){if(l===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(l instanceof he)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(l)){if(l.length===0)throw new TypeError("'fetches' cannot be an empty array.");m=!1;for(let P of l){if(typeof P!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(P)===-1)throw new RangeError(`'fetches' contains invalid output name: ${P}.`);p[P]=null}if(typeof f=="object"&&f!==null)g=f;else if(typeof f<"u")throw new TypeError("'options' must be an object.")}else{let P=!1,D=Object.getOwnPropertyNames(l);for(let R of this.outputNames)if(D.indexOf(R)!==-1){let E=l[R];(E===null||E instanceof he)&&(P=!0,m=!1,p[R]=E)}if(P){if(typeof f=="object"&&f!==null)g=f;else if(typeof f<"u")throw new TypeError("'options' must be an object.")}else g=l}}else if(typeof l<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let P of this.inputNames)if(typeof i[P]>"u")throw new Error(`input '${P}' is missing in 'feeds'.`);if(m)for(let P of this.outputNames)p[P]=null;let v=await this.handler.run(i,p,g),x={};for(let P in v)if(Object.hasOwnProperty.call(v,P)){let D=v[P];D instanceof he?x[P]=D:x[P]=new he(D.type,D.data,D.dims)}return We(),x}async release(){return this.handler.dispose()}static async create(i,l,f,p){Ge();let g,m={};if(typeof i=="string"){if(g=i,typeof l=="object"&&l!==null)m=l;else if(typeof l<"u")throw new TypeError("'options' must be an object.")}else if(i instanceof Uint8Array){if(g=i,typeof l=="object"&&l!==null)m=l;else if(typeof l<"u")throw new TypeError("'options' must be an object.")}else if(i instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&i instanceof SharedArrayBuffer){let D=i,R=0,E=i.byteLength;if(typeof l=="object"&&l!==null)m=l;else if(typeof l=="number"){if(R=l,!Number.isSafeInteger(R))throw new RangeError("'byteOffset' must be an integer.");if(R<0||R>=D.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${D.byteLength}).`);if(E=i.byteLength-R,typeof f=="number"){if(E=f,!Number.isSafeInteger(E))throw new RangeError("'byteLength' must be an integer.");if(E<=0||R+E>D.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${D.byteLength-R}].`);if(typeof p=="object"&&p!==null)m=p;else if(typeof p<"u")throw new TypeError("'options' must be an object.")}else if(typeof f<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof l<"u")throw new TypeError("'options' must be an object.");g=new Uint8Array(D,R,E)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[v,x]=await H(m),P=await v.createInferenceSessionHandler(g,x);return We(),new rw(P)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}}),ct,gt=c(()=>{mt(),ct=ht}),W=c(()=>{}),de=c(()=>{}),J=c(()=>{}),Ee=c(()=>{}),Fe={};h(Fe,{InferenceSession:()=>ct,TRACE:()=>Ke,TRACE_FUNC_BEGIN:()=>Ge,TRACE_FUNC_END:()=>We,Tensor:()=>he,env:()=>j,registerBackend:()=>S});var Ze=c(()=>{z(),ce(),gt(),Se(),W(),de(),st(),J(),Ee()}),rt=c(()=>{}),dt={};h(dt,{default:()=>Lt});var bt,Ct,Lt,Nt=c(()=>{var s;ab(),zn(),Ns(),bt="ort-wasm-proxy-worker",Ct=((s=globalThis.self)==null?void 0:s.name)===bt,Ct&&(self.onmessage=i=>{let{type:l,in:f}=i.data;try{switch(l){case"init-wasm":Ps(f.wasm).then(()=>{Vf(f).then(()=>{postMessage({type:l})},p=>{postMessage({type:l,err:p})})},p=>{postMessage({type:l,err:p})});break;case"init-ep":{let{epName:p,env:g}=f;Wf(g,p).then(()=>{postMessage({type:l})},m=>{postMessage({type:l,err:m})});break}case"copy-from":{let{buffer:p}=f,g=Wn(p);postMessage({type:l,out:g});break}case"create":{let{model:p,options:g}=f;H_(p,g).then(m=>{postMessage({type:l,out:m})},m=>{postMessage({type:l,err:m})});break}case"release":K_(f),postMessage({type:l});break;case"run":{let{sessionId:p,inputIndices:g,inputs:m,outputIndices:v,options:x}=f;Z_(p,g,m,v,new Array(v.length).fill(null),x).then(P=>{P.some(D=>D[3]!=="cpu")?postMessage({type:l,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:l,out:P},X_([...m,...P]))},P=>{postMessage({type:l,err:P})});break}case"end-profiling":Y_(f),postMessage({type:l});break;default:}}catch(p){postMessage({type:l,err:p})}}),Lt=Ct?null:i=>new Worker(i??fn,{type:"module",name:bt})}),br={};h(br,{default:()=>nn});var Rr,Yr,nn,$n=c(()=>{var s;Yr=(Rr=import.meta.url,async function(i={}){function l(){return zt.buffer!=Kt.buffer&&Wr(),Kt}function f(){return zt.buffer!=Kt.buffer&&Wr(),Or}function p(){return zt.buffer!=Kt.buffer&&Wr(),ut}function g(){return zt.buffer!=Kt.buffer&&Wr(),It}function m(){return zt.buffer!=Kt.buffer&&Wr(),Sr}function v(){return zt.buffer!=Kt.buffer&&Wr(),ln}function x(){return zt.buffer!=Kt.buffer&&Wr(),ls}function P(){return zt.buffer!=Kt.buffer&&Wr(),lo}var D,R,E=Object.assign({},i),K=new Promise((b,C)=>{D=b,R=C}),q=typeof window=="object",Y=typeof importScripts=="function",ne=Y&&self.name=="em-pthread";E.mountExternalData=(b,C)=>{b.startsWith("./")&&(b=b.substring(2)),(E.Fb||(E.Fb=new Map)).set(b,C)},E.unmountExternalData=()=>{delete E.Fb};var se=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let te=()=>{let b=(L,V,Q)=>(...Me)=>{let et=ya,it=V==null?void 0:V();Me=L(...Me);let Tt=V==null?void 0:V();return it!==Tt&&(L=Tt,Q(it),V=Q=null),ya!=et?new Promise((Ot,Jt)=>{gg={resolve:Ot,reject:Jt}}):Me},C=L=>async(...V)=>{var Q;try{if(E.Gb)throw Error("Session already started");let Me=E.Gb={hc:V[0],errors:[]},et=await L(...V);if(E.Gb!==Me)throw Error("Session mismatch");(Q=E.Hb)==null||Q.flush();let it=Me.errors;if(0Ot),0E._OrtCreateSession,L=>E._OrtCreateSession=L),E._OrtRun=C(b(E._OrtRun,()=>E._OrtRun,L=>E._OrtRun=L)),E._OrtRunWithBinding=C(b(E._OrtRunWithBinding,()=>E._OrtRunWithBinding,L=>E._OrtRunWithBinding=L)),E._OrtBindInput=b(E._OrtBindInput,()=>E._OrtBindInput,L=>E._OrtBindInput=L),te=void 0};E.jsepInit=(b,C)=>{if(te==null||te(),b==="webgpu"){[E.Hb,E.Vb,E.Zb,E.Ob,E.Yb,E.kb,E.$b,E.cc,E.Wb,E.Xb,E.ac]=C;let L=E.Hb;E.jsepRegisterBuffer=(V,Q,Me,et)=>L.registerBuffer(V,Q,Me,et),E.jsepGetBuffer=V=>L.getBuffer(V),E.jsepCreateDownloader=(V,Q,Me)=>L.createDownloader(V,Q,Me),E.jsepOnCreateSession=V=>{L.onCreateSession(V)},E.jsepOnReleaseSession=V=>{L.onReleaseSession(V)},E.jsepOnRunStart=V=>L.onRunStart(V),E.dc=(V,Q)=>{L.upload(V,Q)}}else if(b==="webnn"){[E.Hb,E.bc,E.Pb,E.jsepEnsureTensor,E.ec,E.jsepDownloadTensor]=C,E.jsepReleaseTensorId=E.Pb;let L=E.Hb;E.jsepOnRunStart=V=>L.onRunStart(V),E.jsepRegisterMLContext=(V,Q)=>{L.registerMLContext(V,Q)},E.jsepOnReleaseSession=V=>{L.onReleaseSession(V)},E.jsepCreateMLTensorDownloader=(V,Q)=>L.createMLTensorDownloader(V,Q),E.jsepRegisterMLTensor=(V,Q,Me)=>L.registerMLTensor(V,Q,Me),E.jsepCreateMLContext=V=>L.createMLContext(V),E.jsepRegisterMLConstant=(V,Q,Me,et,it)=>L.registerMLConstant(V,Q,Me,et,it,E.Fb)}};var ye,be,Ce=Object.assign({},E),Be="./this.program",je=(b,C)=>{throw C},tt="";(q||Y)&&(Y?tt=self.location.href:typeof document<"u"&&document.currentScript&&(tt=document.currentScript.src),Rr&&(tt=Rr),tt=tt.startsWith("blob:")?"":tt.substr(0,tt.replace(/[?#].*/,"").lastIndexOf("/")+1),Y&&(be=b=>{var C=new XMLHttpRequest;return C.open("GET",b,!1),C.responseType="arraybuffer",C.send(null),new Uint8Array(C.response)}),ye=(b,C,L)=>{var V=new XMLHttpRequest;V.open("GET",b,!0),V.responseType="arraybuffer",V.onload=()=>{V.status==200||V.status==0&&V.response?C(V.response):L()},V.onerror=L,V.send(null)});var lt,kt=console.log.bind(console),ir=console.error.bind(console),cr=kt,Pt=ir;if(Object.assign(E,Ce),Ce=null,ne){let b=function(C){try{var L=C.data,V=L.cmd;if(V==="load"){let Q=[];self.onmessage=Me=>Q.push(Me),self.startWorker=()=>{postMessage({cmd:"loaded"});for(let Me of Q)b(Me);self.onmessage=b};for(let Me of L.handlers)E[Me]&&!E[Me].proxy||(E[Me]=(...et)=>{postMessage({Nb:"callHandler",pc:Me,args:et})},Me=="print"&&(cr=E[Me]),Me=="printErr"&&(Pt=E[Me]));zt=L.wasmMemory,Wr(),pr(L.wasmModule)}else if(V==="run"){vg(L.pthread_ptr,0,0,1,0,0),mg(L.pthread_ptr),Hv(),Ab(),Rt||(Py(),Rt=!0);try{Kv(L.start_routine,L.arg)}catch(Q){if(Q!="unwind")throw Q}}else V==="cancel"?vl()&&Nm(-1):L.target!=="setimmediate"&&(V==="checkMailbox"?Rt&&Cm():V&&(Pt(`worker: received unknown command ${V}`),Pt(L)))}catch(Q){throw Cy(),Q}};var pr,Rt=!1;Pt=function(...C){C=C.join(" "),console.error(C)},self.alert=function(...C){postMessage({Nb:"alert",text:C.join(" "),rc:vl()})},E.instantiateWasm=(C,L)=>new Promise(V=>{pr=Q=>{Q=new WebAssembly.Instance(Q,xb()),L(Q),V()}}),self.onunhandledrejection=C=>{throw C.reason||C},self.onmessage=b}E.wasmBinary&&(lt=E.wasmBinary);var zt,Br,rr,Kt,Or,ut,It,Sr,ln,ls,Pn,_a,lo,on=!1;function Wr(){var b=zt.buffer;E.HEAP8=Kt=new Int8Array(b),E.HEAP16=ut=new Int16Array(b),E.HEAPU8=Or=new Uint8Array(b),E.HEAPU16=It=new Uint16Array(b),E.HEAP32=Sr=new Int32Array(b),E.HEAPU32=ln=new Uint32Array(b),E.HEAPF32=ls=new Float32Array(b),E.HEAPF64=lo=new Float64Array(b),E.HEAP64=Pn=new BigInt64Array(b),E.HEAPU64=_a=new BigUint64Array(b)}if(!ne){if(!((zt=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0})).buffer instanceof se))throw Pt("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),Error("bad memory");Wr()}var di=[],Kf=[],rg=[],qf=0,Zf=null;function yb(){if(--qf==0&&Zf){var b=Zf;Zf=null,b()}}function hi(b){throw Pt(b="Aborted("+b+")"),on=!0,rr=1,b=new WebAssembly.RuntimeError(b+". Build with -sASSERTIONS for more info."),R(b),b}var ng,wb=b=>b.startsWith("data:application/octet-stream;base64,"),vb=b=>b.startsWith("file://");function Eb(b){if(b==ng&<)return new Uint8Array(lt);if(be)return be(b);throw"both async and sync fetching of the wasm failed"}function Tb(b,C,L){return function(V){if(!lt&&(q||Y)){if(typeof fetch=="function"&&!vb(V))return fetch(V,{credentials:"same-origin"}).then(Q=>{if(!Q.ok)throw`failed to load wasm binary file at '${V}'`;return Q.arrayBuffer()}).catch(()=>Eb(V));if(ye)return new Promise((Q,Me)=>{ye(V,et=>Q(new Uint8Array(et)),Me)})}return Promise.resolve().then(()=>Eb(V))}(b).then(V=>WebAssembly.instantiate(V,C)).then(L,V=>{Pt(`failed to asynchronously prepare wasm: ${V}`),hi(V)})}function xb(){return{a:{O:Gv,Aa:Wv,b:Zv,aa:Ob,B:Fb,qa:Nb,Y:Bb,_:jb,ra:zb,oa:Ub,ha:Vb,na:Wb,L:Gb,Z:Hb,W:Kb,pa:qb,X:Zb,va:Yv,F:Xv,Q:Qv,P:eE,E:rE,u:nE,q:sE,G:aE,A:hE,R:fE,ua:pE,ka:mE,U:_E,ba:gE,H:bE,ja:mg,ta:yE,t:wE,Ba:vE,x:xE,n:ME,l:CE,c:fg,o:SE,j:IE,w:$E,p:OE,f:LE,s:RE,m:FE,e:NE,k:DE,i:BE,h:jE,d:zE,ea:UE,fa:VE,ga:WE,ca:ly,da:cy,T:GE,g:HE,D:KE,I:qE,M:ZE,y:YE,sa:XE,V:QE,v:hy,z:JE,N:e2,S:t2,za:r2,ya:n2,la:my,ma:_y,$:ug,C:gy,K:by,ia:yy,J:wy,a:zt,xa:og,wa:Ty,r:i2}}}var sg={913700:(b,C,L,V,Q)=>{if(E===void 0||!E.Fb)return 1;if((b=bn(Number(b>>>0))).startsWith("./")&&(b=b.substring(2)),!(b=E.Fb.get(b)))return 2;if(C=Number(C>>>0),L=Number(L>>>0),V=Number(V>>>0),C+L>b.byteLength)return 3;try{let Me=b.subarray(C,C+L);switch(Q){case 0:f().set(Me,V>>>0);break;case 1:E.dc(V,Me);break;default:return 4}return 0}catch{return 4}},914415:(b,C,L)=>{E.ec(b,f().subarray(C>>>0,C+L>>>0))},914478:()=>E.bc(),914519:b=>{E.Pb(b)},914555:()=>{E.Wb()},914586:()=>{E.Xb()},914615:()=>{E.ac()},914640:b=>E.Vb(b),914673:b=>E.Zb(b),914705:(b,C,L)=>{E.Ob(Number(b),Number(C),Number(L),!0)},914768:(b,C,L)=>{E.Ob(Number(b),Number(C),Number(L))},914825:()=>typeof wasmOffsetConverter<"u",914882:b=>{E.kb("Abs",b,void 0)},914933:b=>{E.kb("Neg",b,void 0)},914984:b=>{E.kb("Floor",b,void 0)},915037:b=>{E.kb("Ceil",b,void 0)},915089:b=>{E.kb("Reciprocal",b,void 0)},915147:b=>{E.kb("Sqrt",b,void 0)},915199:b=>{E.kb("Exp",b,void 0)},915250:b=>{E.kb("Erf",b,void 0)},915301:b=>{E.kb("Sigmoid",b,void 0)},915356:(b,C,L)=>{E.kb("HardSigmoid",b,{alpha:C,beta:L})},915435:b=>{E.kb("Log",b,void 0)},915486:b=>{E.kb("Sin",b,void 0)},915537:b=>{E.kb("Cos",b,void 0)},915588:b=>{E.kb("Tan",b,void 0)},915639:b=>{E.kb("Asin",b,void 0)},915691:b=>{E.kb("Acos",b,void 0)},915743:b=>{E.kb("Atan",b,void 0)},915795:b=>{E.kb("Sinh",b,void 0)},915847:b=>{E.kb("Cosh",b,void 0)},915899:b=>{E.kb("Asinh",b,void 0)},915952:b=>{E.kb("Acosh",b,void 0)},916005:b=>{E.kb("Atanh",b,void 0)},916058:b=>{E.kb("Tanh",b,void 0)},916110:b=>{E.kb("Not",b,void 0)},916161:(b,C,L)=>{E.kb("Clip",b,{min:C,max:L})},916230:b=>{E.kb("Clip",b,void 0)},916282:(b,C)=>{E.kb("Elu",b,{alpha:C})},916340:b=>{E.kb("Gelu",b,void 0)},916392:b=>{E.kb("Relu",b,void 0)},916444:(b,C)=>{E.kb("LeakyRelu",b,{alpha:C})},916508:(b,C)=>{E.kb("ThresholdedRelu",b,{alpha:C})},916578:(b,C)=>{E.kb("Cast",b,{to:C})},916636:b=>{E.kb("Add",b,void 0)},916687:b=>{E.kb("Sub",b,void 0)},916738:b=>{E.kb("Mul",b,void 0)},916789:b=>{E.kb("Div",b,void 0)},916840:b=>{E.kb("Pow",b,void 0)},916891:b=>{E.kb("Equal",b,void 0)},916944:b=>{E.kb("Greater",b,void 0)},916999:b=>{E.kb("GreaterOrEqual",b,void 0)},917061:b=>{E.kb("Less",b,void 0)},917113:b=>{E.kb("LessOrEqual",b,void 0)},917172:(b,C,L,V,Q)=>{E.kb("ReduceMean",b,{keepDims:!!C,noopWithEmptyAxes:!!L,axes:V?Array.from(m().subarray(Number(V)>>>0,Number(Q)>>>0)):[]})},917347:(b,C,L,V,Q)=>{E.kb("ReduceMax",b,{keepDims:!!C,noopWithEmptyAxes:!!L,axes:V?Array.from(m().subarray(Number(V)>>>0,Number(Q)>>>0)):[]})},917521:(b,C,L,V,Q)=>{E.kb("ReduceMin",b,{keepDims:!!C,noopWithEmptyAxes:!!L,axes:V?Array.from(m().subarray(Number(V)>>>0,Number(Q)>>>0)):[]})},917695:(b,C,L,V,Q)=>{E.kb("ReduceProd",b,{keepDims:!!C,noopWithEmptyAxes:!!L,axes:V?Array.from(m().subarray(Number(V)>>>0,Number(Q)>>>0)):[]})},917870:(b,C,L,V,Q)=>{E.kb("ReduceSum",b,{keepDims:!!C,noopWithEmptyAxes:!!L,axes:V?Array.from(m().subarray(Number(V)>>>0,Number(Q)>>>0)):[]})},918044:(b,C,L,V,Q)=>{E.kb("ReduceL1",b,{keepDims:!!C,noopWithEmptyAxes:!!L,axes:V?Array.from(m().subarray(Number(V)>>>0,Number(Q)>>>0)):[]})},918217:(b,C,L,V,Q)=>{E.kb("ReduceL2",b,{keepDims:!!C,noopWithEmptyAxes:!!L,axes:V?Array.from(m().subarray(Number(V)>>>0,Number(Q)>>>0)):[]})},918390:(b,C,L,V,Q)=>{E.kb("ReduceLogSum",b,{keepDims:!!C,noopWithEmptyAxes:!!L,axes:V?Array.from(m().subarray(Number(V)>>>0,Number(Q)>>>0)):[]})},918567:(b,C,L,V,Q)=>{E.kb("ReduceSumSquare",b,{keepDims:!!C,noopWithEmptyAxes:!!L,axes:V?Array.from(m().subarray(Number(V)>>>0,Number(Q)>>>0)):[]})},918747:(b,C,L,V,Q)=>{E.kb("ReduceLogSumExp",b,{keepDims:!!C,noopWithEmptyAxes:!!L,axes:V?Array.from(m().subarray(Number(V)>>>0,Number(Q)>>>0)):[]})},918927:b=>{E.kb("Where",b,void 0)},918980:(b,C,L)=>{E.kb("Transpose",b,{perm:C?Array.from(m().subarray(Number(C)>>>0,Number(L)>>>0)):[]})},919104:(b,C,L,V)=>{E.kb("DepthToSpace",b,{blocksize:C,mode:bn(L),format:V?"NHWC":"NCHW"})},919237:(b,C,L,V)=>{E.kb("DepthToSpace",b,{blocksize:C,mode:bn(L),format:V?"NHWC":"NCHW"})},919370:(b,C,L,V,Q,Me,et,it,Tt,Ot,Jt,Ar,jr,Ye,xr)=>{E.kb("ConvTranspose",b,{format:Tt?"NHWC":"NCHW",autoPad:C,dilations:[L],group:V,kernelShape:[Q],pads:[Me,et],strides:[it],wIsConst:()=>!!l()[Ot>>>0],outputPadding:Jt?Array.from(m().subarray(Number(Jt)>>>0,Number(Ar)>>>0)):[],outputShape:jr?Array.from(m().subarray(Number(jr)>>>0,Number(Ye)>>>0)):[],activation:bn(xr)})},919803:(b,C,L,V,Q,Me,et,it,Tt,Ot,Jt,Ar,jr,Ye)=>{E.kb("ConvTranspose",b,{format:it?"NHWC":"NCHW",autoPad:C,dilations:Array.from(m().subarray(Number(L)>>>0,2+(Number(L)>>>0)>>>0)),group:V,kernelShape:Array.from(m().subarray(Number(Q)>>>0,2+(Number(Q)>>>0)>>>0)),pads:Array.from(m().subarray(Number(Me)>>>0,4+(Number(Me)>>>0)>>>0)),strides:Array.from(m().subarray(Number(et)>>>0,2+(Number(et)>>>0)>>>0)),wIsConst:()=>!!l()[Tt>>>0],outputPadding:Ot?Array.from(m().subarray(Number(Ot)>>>0,Number(Jt)>>>0)):[],outputShape:Ar?Array.from(m().subarray(Number(Ar)>>>0,Number(jr)>>>0)):[],activation:bn(Ye)})},920464:(b,C,L,V,Q,Me,et,it,Tt,Ot,Jt,Ar,jr,Ye,xr)=>{E.kb("ConvTranspose",b,{format:Tt?"NHWC":"NCHW",autoPad:C,dilations:[L],group:V,kernelShape:[Q],pads:[Me,et],strides:[it],wIsConst:()=>!!l()[Ot>>>0],outputPadding:Jt?Array.from(m().subarray(Number(Jt)>>>0,Number(Ar)>>>0)):[],outputShape:jr?Array.from(m().subarray(Number(jr)>>>0,Number(Ye)>>>0)):[],activation:bn(xr)})},920897:(b,C,L,V,Q,Me,et,it,Tt,Ot,Jt,Ar,jr,Ye)=>{E.kb("ConvTranspose",b,{format:it?"NHWC":"NCHW",autoPad:C,dilations:Array.from(m().subarray(Number(L)>>>0,2+(Number(L)>>>0)>>>0)),group:V,kernelShape:Array.from(m().subarray(Number(Q)>>>0,2+(Number(Q)>>>0)>>>0)),pads:Array.from(m().subarray(Number(Me)>>>0,4+(Number(Me)>>>0)>>>0)),strides:Array.from(m().subarray(Number(et)>>>0,2+(Number(et)>>>0)>>>0)),wIsConst:()=>!!l()[Tt>>>0],outputPadding:Ot?Array.from(m().subarray(Number(Ot)>>>0,Number(Jt)>>>0)):[],outputShape:Ar?Array.from(m().subarray(Number(Ar)>>>0,Number(jr)>>>0)):[],activation:bn(Ye)})},921558:(b,C)=>{E.kb("GlobalAveragePool",b,{format:C?"NHWC":"NCHW"})},921649:(b,C,L,V,Q,Me,et,it,Tt,Ot,Jt,Ar,jr,Ye)=>{E.kb("AveragePool",b,{format:Ye?"NHWC":"NCHW",auto_pad:C,ceil_mode:L,count_include_pad:V,storage_order:Q,dilations:Me?Array.from(m().subarray(Number(Me)>>>0,Number(et)>>>0)):[],kernel_shape:it?Array.from(m().subarray(Number(it)>>>0,Number(Tt)>>>0)):[],pads:Ot?Array.from(m().subarray(Number(Ot)>>>0,Number(Jt)>>>0)):[],strides:Ar?Array.from(m().subarray(Number(Ar)>>>0,Number(jr)>>>0)):[]})},922128:(b,C)=>{E.kb("GlobalAveragePool",b,{format:C?"NHWC":"NCHW"})},922219:(b,C,L,V,Q,Me,et,it,Tt,Ot,Jt,Ar,jr,Ye)=>{E.kb("AveragePool",b,{format:Ye?"NHWC":"NCHW",auto_pad:C,ceil_mode:L,count_include_pad:V,storage_order:Q,dilations:Me?Array.from(m().subarray(Number(Me)>>>0,Number(et)>>>0)):[],kernel_shape:it?Array.from(m().subarray(Number(it)>>>0,Number(Tt)>>>0)):[],pads:Ot?Array.from(m().subarray(Number(Ot)>>>0,Number(Jt)>>>0)):[],strides:Ar?Array.from(m().subarray(Number(Ar)>>>0,Number(jr)>>>0)):[]})},922698:(b,C)=>{E.kb("GlobalMaxPool",b,{format:C?"NHWC":"NCHW"})},922785:(b,C,L,V,Q,Me,et,it,Tt,Ot,Jt,Ar,jr,Ye)=>{E.kb("MaxPool",b,{format:Ye?"NHWC":"NCHW",auto_pad:C,ceil_mode:L,count_include_pad:V,storage_order:Q,dilations:Me?Array.from(m().subarray(Number(Me)>>>0,Number(et)>>>0)):[],kernel_shape:it?Array.from(m().subarray(Number(it)>>>0,Number(Tt)>>>0)):[],pads:Ot?Array.from(m().subarray(Number(Ot)>>>0,Number(Jt)>>>0)):[],strides:Ar?Array.from(m().subarray(Number(Ar)>>>0,Number(jr)>>>0)):[]})},923260:(b,C)=>{E.kb("GlobalMaxPool",b,{format:C?"NHWC":"NCHW"})},923347:(b,C,L,V,Q,Me,et,it,Tt,Ot,Jt,Ar,jr,Ye)=>{E.kb("MaxPool",b,{format:Ye?"NHWC":"NCHW",auto_pad:C,ceil_mode:L,count_include_pad:V,storage_order:Q,dilations:Me?Array.from(m().subarray(Number(Me)>>>0,Number(et)>>>0)):[],kernel_shape:it?Array.from(m().subarray(Number(it)>>>0,Number(Tt)>>>0)):[],pads:Ot?Array.from(m().subarray(Number(Ot)>>>0,Number(Jt)>>>0)):[],strides:Ar?Array.from(m().subarray(Number(Ar)>>>0,Number(jr)>>>0)):[]})},923822:(b,C,L,V,Q)=>{E.kb("Gemm",b,{alpha:C,beta:L,transA:V,transB:Q})},923926:b=>{E.kb("MatMul",b,void 0)},923980:(b,C,L,V)=>{E.kb("ArgMax",b,{keepDims:!!C,selectLastIndex:!!L,axis:V})},924088:(b,C,L,V)=>{E.kb("ArgMin",b,{keepDims:!!C,selectLastIndex:!!L,axis:V})},924196:(b,C)=>{E.kb("Softmax",b,{axis:C})},924259:(b,C)=>{E.kb("Concat",b,{axis:C})},924319:(b,C,L,V,Q)=>{E.kb("Split",b,{axis:C,numOutputs:L,splitSizes:V?Array.from(m().subarray(Number(V)>>>0,Number(Q)>>>0)):[]})},924475:b=>{E.kb("Expand",b,void 0)},924529:(b,C)=>{E.kb("Gather",b,{axis:Number(C)})},924600:(b,C)=>{E.kb("GatherElements",b,{axis:Number(C)})},924679:(b,C)=>{E.kb("GatherND",b,{batch_dims:Number(C)})},924758:(b,C,L,V,Q,Me,et,it,Tt,Ot,Jt)=>{E.kb("Resize",b,{antialias:C,axes:L?Array.from(m().subarray(Number(L)>>>0,Number(V)>>>0)):[],coordinateTransformMode:bn(Q),cubicCoeffA:Me,excludeOutside:et,extrapolationValue:it,keepAspectRatioPolicy:bn(Tt),mode:bn(Ot),nearestMode:bn(Jt)})},925120:(b,C,L,V,Q,Me,et)=>{E.kb("Slice",b,{starts:C?Array.from(m().subarray(Number(C)>>>0,Number(L)>>>0)):[],ends:V?Array.from(m().subarray(Number(V)>>>0,Number(Q)>>>0)):[],axes:Me?Array.from(m().subarray(Number(Me)>>>0,Number(et)>>>0)):[]})},925384:b=>{E.kb("Tile",b,void 0)},925436:(b,C,L)=>{E.kb("InstanceNormalization",b,{epsilon:C,format:L?"NHWC":"NCHW"})},925550:(b,C,L)=>{E.kb("InstanceNormalization",b,{epsilon:C,format:L?"NHWC":"NCHW"})},925664:b=>{E.kb("Range",b,void 0)},925717:(b,C)=>{E.kb("Einsum",b,{equation:bn(C)})},925798:(b,C,L,V,Q)=>{E.kb("Pad",b,{mode:C,value:L,pads:V?Array.from(m().subarray(Number(V)>>>0,Number(Q)>>>0)):[]})},925941:(b,C,L,V,Q,Me)=>{E.kb("BatchNormalization",b,{epsilon:C,momentum:L,spatial:!!Q,trainingMode:!!V,format:Me?"NHWC":"NCHW"})},926110:(b,C,L,V,Q,Me)=>{E.kb("BatchNormalization",b,{epsilon:C,momentum:L,spatial:!!Q,trainingMode:!!V,format:Me?"NHWC":"NCHW"})},926279:(b,C,L)=>{E.kb("CumSum",b,{exclusive:Number(C),reverse:Number(L)})},926376:(b,C,L)=>{E.kb("DequantizeLinear",b,{axis:C,blockSize:L})},926466:(b,C,L,V,Q)=>{E.kb("GridSample",b,{align_corners:C,mode:bn(L),padding_mode:bn(V),format:Q?"NHWC":"NCHW"})},926636:(b,C,L,V,Q)=>{E.kb("GridSample",b,{align_corners:C,mode:bn(L),padding_mode:bn(V),format:Q?"NHWC":"NCHW"})},926806:(b,C,L,V,Q,Me,et,it,Tt)=>{E.kb("Attention",b,{numHeads:C,isUnidirectional:L,maskFilterValue:V,scale:Q,doRotary:Me,qkvHiddenSizes:et?Array.from(m().subarray(Number(it)>>>0,Number(it)+et>>>0)):[],pastPresentShareBuffer:!!Tt})},927078:b=>{E.kb("BiasAdd",b,void 0)},927133:b=>{E.kb("BiasSplitGelu",b,void 0)},927194:b=>{E.kb("FastGelu",b,void 0)},927250:(b,C,L,V,Q,Me,et,it,Tt,Ot,Jt,Ar,jr,Ye,xr,cn)=>{E.kb("Conv",b,{format:Ar?"NHWC":"NCHW",auto_pad:C,dilations:L?Array.from(m().subarray(Number(L)>>>0,Number(V)>>>0)):[],group:Q,kernel_shape:Me?Array.from(m().subarray(Number(Me)>>>0,Number(et)>>>0)):[],pads:it?Array.from(m().subarray(Number(it)>>>0,Number(Tt)>>>0)):[],strides:Ot?Array.from(m().subarray(Number(Ot)>>>0,Number(Jt)>>>0)):[],w_is_const:()=>!!l()[Number(jr)>>>0],activation:bn(Ye),activation_params:xr?Array.from(x().subarray(Number(xr)>>>0,Number(cn)>>>0)):[]})},927834:b=>{E.kb("Gelu",b,void 0)},927886:(b,C,L,V,Q,Me,et,it,Tt)=>{E.kb("GroupQueryAttention",b,{numHeads:C,kvNumHeads:L,scale:V,softcap:Q,doRotary:Me,rotaryInterleaved:et,smoothSoftmax:it,localWindowSize:Tt})},928103:(b,C,L,V)=>{E.kb("LayerNormalization",b,{axis:C,epsilon:L,simplified:!!V})},928214:(b,C,L,V)=>{E.kb("LayerNormalization",b,{axis:C,epsilon:L,simplified:!!V})},928325:(b,C,L,V,Q,Me)=>{E.kb("MatMulNBits",b,{k:C,n:L,accuracyLevel:V,bits:Q,blockSize:Me})},928452:(b,C,L,V,Q,Me)=>{E.kb("MultiHeadAttention",b,{numHeads:C,isUnidirectional:L,maskFilterValue:V,scale:Q,doRotary:Me})},928611:(b,C)=>{E.kb("QuickGelu",b,{alpha:C})},928675:(b,C,L,V,Q)=>{E.kb("RotaryEmbedding",b,{interleaved:!!C,numHeads:L,rotaryEmbeddingDim:V,scale:Q})},928814:(b,C,L)=>{E.kb("SkipLayerNormalization",b,{epsilon:C,simplified:!!L})},928916:(b,C,L)=>{E.kb("SkipLayerNormalization",b,{epsilon:C,simplified:!!L})},929018:(b,C,L,V)=>{E.kb("GatherBlockQuantized",b,{gatherAxis:C,quantizeAxis:L,blockSize:V})},929139:b=>{E.$b(b)},929173:(b,C)=>E.cc(Number(b),Number(C),E.Gb.hc,E.Gb.errors)};function Wv(b,C,L){return sy(async()=>{await E.Yb(Number(b),Number(C),Number(L))})}function Gv(){return typeof wasmOffsetConverter<"u"}function ag(b){this.name="ExitStatus",this.message=`Program terminated with exit(${b})`,this.status=b}var ig=b=>{b.terminate(),b.onmessage=()=>{}},Mb=b=>{fi.length==0&&(Ib(),kb(fi[0]));var C=fi.pop();if(!C)return 6;ho.push(C),ga[b.Bb]=C,C.Bb=b.Bb;var L={cmd:"run",start_routine:b.ic,arg:b.Rb,pthread_ptr:b.Bb};return C.postMessage(L,b.nc),0},co=0,un=(b,C,...L)=>{for(var V=2*L.length,Q=xg(),Me=Tg(8*V),et=Me>>>3,it=0;it>>0]=Tt)}return b=Sy(b,0,V,Me,C),Dm(Q),b};function og(b){if(ne)return un(0,1,b);if(rr=b,!(0{if(rr=b,ne)throw Pb(b),"unwind";og(b)},fi=[],ho=[],Cb=[],ga={},Sb=b=>{var C=b.Bb;delete ga[C],fi.push(b),ho.splice(ho.indexOf(b),1),b.Bb=0,Eg(C)};function Ab(){Cb.forEach(b=>b())}var kb=b=>new Promise(C=>{b.onmessage=Q=>{var Me=(Q=Q.data).cmd;if(Q.targetThread&&Q.targetThread!=vl()){var et=ga[Q.targetThread];et?et.postMessage(Q,Q.transferList):Pt(`Internal error! Worker sent a message "${Me}" to target pthread ${Q.targetThread}, but that thread no longer exists!`)}else Me==="checkMailbox"?Cm():Me==="spawnThread"?Mb(Q):Me==="cleanupThread"?Sb(ga[Q.thread]):Me==="killThread"?(Q=Q.thread,Me=ga[Q],delete ga[Q],ig(Me),Eg(Q),ho.splice(ho.indexOf(Me),1),Me.Bb=0):Me==="cancelThread"?ga[Q.thread].postMessage({cmd:"cancel"}):Me==="loaded"?(b.loaded=!0,C(b)):Me==="alert"?alert(`Thread ${Q.threadId}: ${Q.text}`):Q.target==="setimmediate"?b.postMessage(Q):Me==="callHandler"?E[Q.handler](...Q.args):Me&&Pt(`worker sent an unknown command ${Me}`)},b.onerror=Q=>{throw Pt(`worker sent an error! ${Q.filename}:${Q.lineno}: ${Q.message}`),Q};var L,V=[];for(L of[])E.hasOwnProperty(L)&&V.push(L);b.postMessage({cmd:"load",handlers:V,wasmMemory:zt,wasmModule:Br})});function Ib(){var b=new Worker(import.meta.url.startsWith("file:")?new URL(t("./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs?46eb"),t.b):new URL(import.meta.url),{type:"module",workerData:"em-pthread",name:"em-pthread"});fi.push(b)}var Pm=b=>{for(;0{var b=vl(),C=v()[b+52>>>2>>>0];b=v()[b+56>>>2>>>0],ky(C,C-b),Dm(C)},Kv=(b,C)=>{co=0,b=Iy(b,C),0>>=0);throw C>>>=0,L>>>=0,v()[V.Kb+16>>>2>>>0]=0,v()[V.Kb+4>>>2>>>0]=C,v()[V.Kb+8>>>2>>>0]=L,b}function $b(b,C,L,V){return ne?un(2,1,b,C,L,V):Ob(b,C,L,V)}function Ob(b,C,L,V){if(b>>>=0,C>>>=0,L>>>=0,V>>>=0,se===void 0)return Pt("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var Q=[];return ne&&Q.length===0?$b(b,C,L,V):(b={ic:L,Bb:b,Rb:V,nc:Q},ne?(b.Nb="spawnThread",postMessage(b,Q),0):Mb(b))}var Lb=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,Rb=(b,C,L)=>{var V=(C>>>=0)+L;for(L=C;b[L]&&!(L>=V);)++L;if(16(Q=(240&Q)==224?(15&Q)<<12|Me<<6|et:(7&Q)<<18|Me<<12|et<<6|63&b[C++])?V+=String.fromCharCode(Q):(Q-=65536,V+=String.fromCharCode(55296|Q>>10,56320|1023&Q))}}else V+=String.fromCharCode(Q)}return V},bn=(b,C)=>(b>>>=0)?Rb(f(),b,C):"";function Fb(b,C,L){return ne?un(3,1,b,C,L):0}function Nb(b,C){if(ne)return un(4,1,b,C)}var lg=b=>{for(var C=0,L=0;L=V?C++:2047>=V?C+=2:55296<=V&&57343>=V?(C+=4,++L):C+=3}return C},Db=(b,C,L,V)=>{if(!(0>>=0;V=L+V-1;for(var Me=0;Me=et&&(et=65536+((1023&et)<<10)|1023&b.charCodeAt(++Me)),127>=et){if(L>=V)break;C[L++>>>0]=et}else{if(2047>=et){if(L+1>=V)break;C[L++>>>0]=192|et>>6}else{if(65535>=et){if(L+2>=V)break;C[L++>>>0]=224|et>>12}else{if(L+3>=V)break;C[L++>>>0]=240|et>>18,C[L++>>>0]=128|et>>12&63}C[L++>>>0]=128|et>>6&63}C[L++>>>0]=128|63&et}}return C[L>>>0]=0,L-Q},yl=(b,C,L)=>Db(b,f(),C,L);function Bb(b,C){if(ne)return un(5,1,b,C)}function jb(b,C,L){if(ne)return un(6,1,b,C,L)}function zb(b,C,L){return ne?un(7,1,b,C,L):0}function Ub(b,C){if(ne)return un(8,1,b,C)}function Vb(b,C,L){if(ne)return un(9,1,b,C,L)}function Wb(b,C,L,V){if(ne)return un(10,1,b,C,L,V)}function Gb(b,C,L,V){if(ne)return un(11,1,b,C,L,V)}function Hb(b,C,L,V){if(ne)return un(12,1,b,C,L,V)}function Kb(b){if(ne)return un(13,1,b)}function qb(b,C){if(ne)return un(14,1,b,C)}function Zb(b,C,L){if(ne)return un(15,1,b,C,L)}var Yb,pi,Yv=()=>{hi("")},ba=b=>{for(var C="";f()[b>>>0];)C+=Yb[f()[b++>>>0]];return C},cg={},dg={};function Na(b,C,L={}){if(!("argPackAdvance"in C))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(V,Q,Me={}){var et=Q.name;if(!V)throw new pi(`type "${et}" must have a positive integer typeid pointer`);if(dg.hasOwnProperty(V)){if(Me.Tb)return;throw new pi(`Cannot register type '${et}' twice`)}dg[V]=Q,cg.hasOwnProperty(V)&&(Q=cg[V],delete cg[V],Q.forEach(it=>it()))}(b,C,L)}var Xb=(b,C,L)=>{switch(C){case 1:return L?V=>l()[V>>>0]:V=>f()[V>>>0];case 2:return L?V=>p()[V>>>1>>>0]:V=>g()[V>>>1>>>0];case 4:return L?V=>m()[V>>>2>>>0]:V=>v()[V>>>2>>>0];case 8:return L?V=>Pn[V>>>3]:V=>_a[V>>>3];default:throw new TypeError(`invalid integer width (${C}): ${b}`)}};function Xv(b,C,L){L>>>=0,Na(b>>>=0,{name:C=ba(C>>>0),fromWireType:V=>V,toWireType:function(V,Q){if(typeof Q!="bigint"&&typeof Q!="number")throw Q=Q===null?"null":(V=typeof Q)=="object"||V==="array"||V==="function"?Q.toString():""+Q,new TypeError(`Cannot convert "${Q}" to ${this.name}`);return typeof Q=="number"&&(Q=BigInt(Q)),Q},argPackAdvance:mi,readValueFromPointer:Xb(C,L,C.indexOf("u")==-1),Eb:null})}var mi=8;function Qv(b,C,L,V){Na(b>>>=0,{name:C=ba(C>>>0),fromWireType:function(Q){return!!Q},toWireType:function(Q,Me){return Me?L:V},argPackAdvance:mi,readValueFromPointer:function(Q){return this.fromWireType(f()[Q>>>0])},Eb:null})}var hg=[],Da=[];function fg(b){9<(b>>>=0)&&--Da[b+1]==0&&(Da[b]=void 0,hg.push(b))}var gs=b=>{if(!b)throw new pi("Cannot use deleted val. handle = "+b);return Da[b]},Is=b=>{switch(b){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let C=hg.pop()||Da.length;return Da[C]=b,Da[C+1]=1,C}};function pg(b){return this.fromWireType(v()[b>>>2>>>0])}var Jv={name:"emscripten::val",fromWireType:b=>{var C=gs(b);return fg(b),C},toWireType:(b,C)=>Is(C),argPackAdvance:mi,readValueFromPointer:pg,Eb:null};function eE(b){return Na(b>>>0,Jv)}var tE=(b,C)=>{switch(C){case 4:return function(L){return this.fromWireType(x()[L>>>2>>>0])};case 8:return function(L){return this.fromWireType(P()[L>>>3>>>0])};default:throw new TypeError(`invalid float width (${C}): ${b}`)}};function rE(b,C,L){L>>>=0,Na(b>>>=0,{name:C=ba(C>>>0),fromWireType:V=>V,toWireType:(V,Q)=>Q,argPackAdvance:mi,readValueFromPointer:tE(C,L),Eb:null})}function nE(b,C,L,V,Q){if(b>>>=0,L>>>=0,C=ba(C>>>0),Q===-1&&(Q=4294967295),Q=it=>it,V===0){var Me=32-8*L;Q=it=>it<>>Me}var et=C.includes("unsigned")?function(it,Tt){return Tt>>>0}:function(it,Tt){return Tt};Na(b,{name:C,fromWireType:Q,toWireType:et,argPackAdvance:mi,readValueFromPointer:Xb(C,L,V!==0),Eb:null})}function sE(b,C,L){function V(Me){var et=v()[Me>>>2>>>0];return Me=v()[Me+4>>>2>>>0],new Q(l().buffer,Me,et)}var Q=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][C];Na(b>>>=0,{name:L=ba(L>>>0),fromWireType:V,argPackAdvance:mi,readValueFromPointer:V},{Tb:!0})}function aE(b,C){b>>>=0;var L=(C=ba(C>>>0))==="std::string";Na(b,{name:C,fromWireType:function(V){var Q=v()[V>>>2>>>0],Me=V+4;if(L)for(var et=Me,it=0;it<=Q;++it){var Tt=Me+it;if(it==Q||f()[Tt>>>0]==0){if(et=bn(et,Tt-et),Ot===void 0)var Ot=et;else Ot+="\0",Ot+=et;et=Tt+1}}else{for(Ot=Array(Q),it=0;it>>0]);Ot=Ot.join("")}return wa(V),Ot},toWireType:function(V,Q){Q instanceof ArrayBuffer&&(Q=new Uint8Array(Q));var Me=typeof Q=="string";if(!(Me||Q instanceof Uint8Array||Q instanceof Uint8ClampedArray||Q instanceof Int8Array))throw new pi("Cannot pass non-string to std::string");var et=L&&Me?lg(Q):Q.length,it=Fm(4+et+1),Tt=it+4;if(v()[it>>>2>>>0]=et,L&&Me)yl(Q,Tt,et+1);else if(Me)for(Me=0;Me>>0]=Ot}else for(Me=0;Me>>0]=Q[Me];return V!==null&&V.push(wa,it),it},argPackAdvance:mi,readValueFromPointer:pg,Eb(V){wa(V)}})}var Qb=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,iE=(b,C)=>{for(var L=b>>1,V=L+C/2;!(L>=V)&&g()[L>>>0];)++L;if(32<(L<<=1)-b&&Qb)return Qb.decode(f().slice(b,L));for(L="",V=0;!(V>=C/2);++V){var Q=p()[b+2*V>>>1>>>0];if(Q==0)break;L+=String.fromCharCode(Q)}return L},oE=(b,C,L)=>{if(L??(L=2147483647),2>L)return 0;var V=C;L=(L-=2)<2*b.length?L/2:b.length;for(var Q=0;Q>>1>>>0]=Me,C+=2}return p()[C>>>1>>>0]=0,C-V},uE=b=>2*b.length,lE=(b,C)=>{for(var L=0,V="";!(L>=C/4);){var Q=m()[b+4*L>>>2>>>0];if(Q==0)break;++L,65536<=Q?(Q-=65536,V+=String.fromCharCode(55296|Q>>10,56320|1023&Q)):V+=String.fromCharCode(Q)}return V},cE=(b,C,L)=>{if(C>>>=0,L??(L=2147483647),4>L)return 0;var V=C;L=V+L-4;for(var Q=0;Q=Me&&(Me=65536+((1023&Me)<<10)|1023&b.charCodeAt(++Q)),m()[C>>>2>>>0]=Me,(C+=4)+4>L)break}return m()[C>>>2>>>0]=0,C-V},dE=b=>{for(var C=0,L=0;L=V&&++L,C+=4}return C};function hE(b,C,L){if(b>>>=0,C>>>=0,L=ba(L>>>=0),C===2)var V=iE,Q=oE,Me=uE,et=it=>g()[it>>>1>>>0];else C===4&&(V=lE,Q=cE,Me=dE,et=it=>v()[it>>>2>>>0]);Na(b,{name:L,fromWireType:it=>{for(var Tt,Ot=v()[it>>>2>>>0],Jt=it+4,Ar=0;Ar<=Ot;++Ar){var jr=it+4+Ar*C;Ar!=Ot&&et(jr)!=0||(Jt=V(Jt,jr-Jt),Tt===void 0?Tt=Jt:(Tt+="\0",Tt+=Jt),Jt=jr+C)}return wa(it),Tt},toWireType:(it,Tt)=>{if(typeof Tt!="string")throw new pi(`Cannot pass non-string to C++ string type ${L}`);var Ot=Me(Tt),Jt=Fm(4+Ot+C);return v()[Jt>>>2>>>0]=Ot/C,Q(Tt,Jt+4,Ot+C),it!==null&&it.push(wa,Jt),Jt},argPackAdvance:mi,readValueFromPointer:pg,Eb(it){wa(it)}})}function fE(b,C){Na(b>>>=0,{Ub:!0,name:C=ba(C>>>0),argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})}var pE=()=>1;function mE(b){vg(b>>>0,!Y,1,!q,131072,!1),Ab()}var Jb=b=>{if(!on)try{if(b(),!(0>>=0,typeof Atomics.oc=="function"&&(Atomics.oc(m(),b>>>2,b).value.then(Cm),b+=128,Atomics.store(m(),b>>>2,1))}var Cm=()=>{var b=vl();b&&(mg(b),Jb(Ay))};function _E(b,C){(b>>>=0)==C>>>0?setTimeout(Cm):ne?postMessage({targetThread:b,cmd:"checkMailbox"}):(b=ga[b])&&b.postMessage({cmd:"checkMailbox"})}var _g=[];function gE(b,C,L,V,Q){for(C>>>=0,V/=2,_g.length=V,L=Q>>>0>>>3,Q=0;Q>>0];return(C?sg[C]:o2[b])(..._g)}function bE(b){b>>>=0,ne?postMessage({cmd:"cleanupThread",thread:b}):Sb(ga[b])}function yE(b){}var Sm=(b,C)=>{var L=dg[b];if(L===void 0)throw b=My(b),L=ba(b),wa(b),new pi(`${C} has unknown type ${L}`);return L},ey=(b,C,L)=>{var V=[];return b=b.toWireType(V,L),V.length&&(v()[C>>>2>>>0]=Is(V)),b};function wE(b,C,L){return C>>>=0,L>>>=0,b=gs(b>>>0),C=Sm(C,"emval::as"),ey(C,L,b)}function vE(b,C){return C>>>=0,b=gs(b>>>0),(C=Sm(C,"emval::as")).toWireType(null,b)}var Am=b=>{try{b()}catch(C){hi(C)}},_i=0,ya=null,ty=0,km=[],ry={},ny={},EE=0,gg=null,TE=[];function sy(b){return function(C){if(!on){if(_i===0){var L=!1,V=!1;C((Q=0)=>{if(!on&&(ty=Q,L=!0,V)){_i=2,Am(()=>Ly(ya)),typeof Browser<"u"&&Browser.Lb.Sb&&Browser.Lb.resume(),Q=!1;try{var Me=function(){var Tt=m()[ya+8>>>2>>>0];return Tt=Yt[ny[Tt]],--co,Tt()}()}catch(Tt){Me=Tt,Q=!0}var et=!1;if(!ya){var it=gg;it&&(gg=null,(Q?it.reject:it.resolve)(Me),et=!0)}if(Q&&!et)throw Me}}),V=!0,L||(_i=1,ya=function(){var Q=Fm(65548),Me=Q+12;v()[Q>>>2>>>0]=Me,v()[Q+4>>>2>>>0]=Me+65536,Me=km[0];var et=ry[Me];return et===void 0&&(et=EE++,ry[Me]=et,ny[et]=Me),Me=et,m()[Q+8>>>2>>>0]=Me,Q}(),typeof Browser<"u"&&Browser.Lb.Sb&&Browser.Lb.pause(),Am(()=>$y(ya)))}else _i===2?(_i=0,Am(Ry),wa(ya),ya=null,TE.forEach(Jb)):hi(`invalid state: ${_i}`);return ty}}(C=>{b().then(C)})}function xE(b){return b>>>=0,sy(()=>(b=gs(b)).then(Is))}var Im=[];function ME(b,C,L,V){return L>>>=0,V>>>=0,(b=Im[b>>>0])(null,C=gs(C>>>0),L,V)}var PE={},$m=b=>{var C=PE[b];return C===void 0?ba(b):C};function CE(b,C,L,V,Q){return L>>>=0,V>>>=0,Q>>>=0,(b=Im[b>>>0])(C=gs(C>>>0),C[L=$m(L)],V,Q)}var ay=()=>typeof globalThis=="object"?globalThis:Function("return this")();function SE(b){return(b>>>=0)==0?Is(ay()):(b=$m(b),Is(ay()[b]))}var AE=b=>{var C=Im.length;return Im.push(b),C},kE=(b,C)=>{for(var L=Array(b),V=0;V>>2>>>0],"parameter "+V);return L},iy=(b,C)=>Object.defineProperty(C,"name",{value:b});function IE(b,C,L){var V=(C=kE(b,C>>>0)).shift();b--;var Q=`return function (obj, func, destructorsRef, args) { `,Me=0,et=[];L===0&&et.push("obj");for(var it=["retType"],Tt=[V],Ot=0;OtJt.name).join(", ")}) => ${V.name}>`,AE(iy(L,b))}function $E(b){return b=$m(b>>>0),Is(E[b])}function OE(b,C){return C>>>=0,b=gs(b>>>0),C=gs(C),Is(b[C])}function LE(b){9<(b>>>=0)&&(Da[b+1]+=1)}function RE(){return Is([])}function FE(b){b=gs(b>>>0);for(var C=Array(b.length),L=0;L>>0))}function DE(){return Is({})}function BE(b){for(var C=gs(b>>>=0);C.length;){var L=C.pop();C.pop()(L)}fg(b)}function jE(b,C,L){C>>>=0,L>>>=0,b=gs(b>>>0),C=gs(C),L=gs(L),b[C]=L}function zE(b,C){return C>>>=0,b=(b=Sm(b>>>0,"_emval_take_value")).readValueFromPointer(C),Is(b)}function UE(b,C){b=-9007199254740992>b||9007199254740992>>=0,b=new Date(1e3*b),m()[C>>>2>>>0]=b.getUTCSeconds(),m()[C+4>>>2>>>0]=b.getUTCMinutes(),m()[C+8>>>2>>>0]=b.getUTCHours(),m()[C+12>>>2>>>0]=b.getUTCDate(),m()[C+16>>>2>>>0]=b.getUTCMonth(),m()[C+20>>>2>>>0]=b.getUTCFullYear()-1900,m()[C+24>>>2>>>0]=b.getUTCDay(),b=(b.getTime()-Date.UTC(b.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,m()[C+28>>>2>>>0]=b}var wl=b=>b%4==0&&(b%100!=0||b%400==0),oy=[0,31,60,91,121,152,182,213,244,274,305,335],uy=[0,31,59,90,120,151,181,212,243,273,304,334];function VE(b,C){b=-9007199254740992>b||9007199254740992>>=0,b=new Date(1e3*b),m()[C>>>2>>>0]=b.getSeconds(),m()[C+4>>>2>>>0]=b.getMinutes(),m()[C+8>>>2>>>0]=b.getHours(),m()[C+12>>>2>>>0]=b.getDate(),m()[C+16>>>2>>>0]=b.getMonth(),m()[C+20>>>2>>>0]=b.getFullYear()-1900,m()[C+24>>>2>>>0]=b.getDay();var L=(wl(b.getFullYear())?oy:uy)[b.getMonth()]+b.getDate()-1|0;m()[C+28>>>2>>>0]=L,m()[C+36>>>2>>>0]=-60*b.getTimezoneOffset(),L=new Date(b.getFullYear(),6,1).getTimezoneOffset();var V=new Date(b.getFullYear(),0,1).getTimezoneOffset();b=0|(L!=V&&b.getTimezoneOffset()==Math.min(V,L)),m()[C+32>>>2>>>0]=b}function WE(b){b>>>=0;var C=new Date(m()[b+20>>>2>>>0]+1900,m()[b+16>>>2>>>0],m()[b+12>>>2>>>0],m()[b+8>>>2>>>0],m()[b+4>>>2>>>0],m()[b>>>2>>>0],0),L=m()[b+32>>>2>>>0],V=C.getTimezoneOffset(),Q=new Date(C.getFullYear(),6,1).getTimezoneOffset(),Me=new Date(C.getFullYear(),0,1).getTimezoneOffset(),et=Math.min(Me,Q);return 0>L?m()[b+32>>>2>>>0]=+(Q!=Me&&et==V):0>>2>>>0]=C.getDay(),L=(wl(C.getFullYear())?oy:uy)[C.getMonth()]+C.getDate()-1|0,m()[b+28>>>2>>>0]=L,m()[b>>>2>>>0]=C.getSeconds(),m()[b+4>>>2>>>0]=C.getMinutes(),m()[b+8>>>2>>>0]=C.getHours(),m()[b+12>>>2>>>0]=C.getDate(),m()[b+16>>>2>>>0]=C.getMonth(),m()[b+20>>>2>>>0]=C.getYear(),b=C.getTime(),BigInt(isNaN(b)?-1:b/1e3)}function ly(b,C,L,V,Q,Me,et){return ne?un(16,1,b,C,L,V,Q,Me,et):-52}function cy(b,C,L,V,Q,Me){if(ne)return un(17,1,b,C,L,V,Q,Me)}function GE(b,C,L,V){b>>>=0,C>>>=0,L>>>=0,V>>>=0;var Q=new Date().getFullYear(),Me=new Date(Q,0,1),et=new Date(Q,6,1);Q=Me.getTimezoneOffset();var it=et.getTimezoneOffset(),Tt=Math.max(Q,it);v()[b>>>2>>>0]=60*Tt,m()[C>>>2>>>0]=+(Q!=it),Me=(b=Ot=>Ot.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1])(Me),et=b(et),it{bg.length=0;for(var L;L=f()[b++>>>0];){var V=L!=105;C+=(V&=L!=112)&&C%8?4:0,bg.push(L==112?v()[C>>>2>>>0]:L==106?Pn[C>>>3]:L==105?m()[C>>>2>>>0]:P()[C>>>3>>>0]),C+=V?8:4}return bg};function HE(b,C,L){return b>>>=0,C=dy(C>>>0,L>>>0),sg[b](...C)}function KE(b,C,L){return b>>>=0,C=dy(C>>>0,L>>>0),sg[b](...C)}var qE=()=>{},ZE=()=>Date.now();function YE(b,C){return Pt(bn(b>>>0,C>>>0))}var hy,XE=()=>{throw co+=1,"unwind"};function QE(){return 4294901760}hy=()=>performance.timeOrigin+performance.now();var JE=()=>navigator.hardwareConcurrency;function e2(){return hi("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function t2(b){b>>>=0;var C=f().length;if(b<=C||4294901760=L;L*=2){var V=C*(1+.2/L);V=Math.min(V,b+100663296);var Q=Math;V=Math.max(b,V);e:{Q=(Q.min.call(Q,4294901760,V+(65536-V%65536)%65536)-zt.buffer.byteLength+65535)/65536;try{zt.grow(Q),Wr();var Me=1;break e}catch{}Me=void 0}if(Me)return!0}return!1}var Om=()=>(hi("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),Yf={},fy=b=>{b.forEach(C=>{Om()})};function r2(){var b=Error().stack.toString().split(` `);return b[0]=="Error"&&b.shift(),fy(b),Yf.Qb=Om(),Yf.fc=b,Yf.Qb}function n2(b,C,L){if(b>>>=0,C>>>=0,Yf.Qb==b)var V=Yf.fc;else(V=Error().stack.toString().split(` `))[0]=="Error"&&V.shift(),fy(V);for(var Q=3;V[Q]&&Om()!=b;)++Q;for(b=0;b>>2>>>0]=Om();return b}var yg,wg={},py=()=>{if(!yg){var b,C={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:Be};for(b in wg)wg[b]===void 0?delete C[b]:C[b]=wg[b];var L=[];for(b in C)L.push(`${b}=${C[b]}`);yg=L}return yg};function my(b,C){if(ne)return un(18,1,b,C);b>>>=0,C>>>=0;var L=0;return py().forEach((V,Q)=>{var Me=C+L;for(Q=v()[b+4*Q>>>2>>>0]=Me,Me=0;Me>>0]=V.charCodeAt(Me);l()[Q>>>0]=0,L+=V.length+1}),0}function _y(b,C){if(ne)return un(19,1,b,C);b>>>=0,C>>>=0;var L=py();v()[b>>>2>>>0]=L.length;var V=0;return L.forEach(Q=>V+=Q.length+1),v()[C>>>2>>>0]=V,0}function gy(b){return ne?un(20,1,b):52}function by(b,C,L,V){return ne?un(21,1,b,C,L,V):52}function yy(b,C,L,V){return ne?un(22,1,b,C,L,V):70}var s2=[null,[],[]];function wy(b,C,L,V){if(ne)return un(23,1,b,C,L,V);C>>>=0,L>>>=0,V>>>=0;for(var Q=0,Me=0;Me>>2>>>0],it=v()[C+4>>>2>>>0];C+=8;for(var Tt=0;Tt>>0],Jt=s2[b];Ot===0||Ot===10?((b===1?cr:Pt)(Rb(Jt,0)),Jt.length=0):Jt.push(Ot)}Q+=it}return v()[V>>>2>>>0]=Q,0}var vy=[31,29,31,30,31,30,31,31,30,31,30,31],Ey=[31,28,31,30,31,30,31,31,30,31,30,31],a2=(b,C)=>{l().set(b,C>>>0)};function Ty(b,C,L,V){function Q(Ye,xr,cn){for(Ye=typeof Ye=="number"?Ye.toString():Ye||"";Ye.lengthNy?-1:0fo-Ye.getDate())){Ye.setDate(Ye.getDate()+xr);break}xr-=fo-Ye.getDate()+1,Ye.setDate(1),11>cn?Ye.setMonth(cn+1):(Ye.setMonth(0),Ye.setFullYear(Ye.getFullYear()+1))}return cn=new Date(Ye.getFullYear()+1,0,4),xr=it(new Date(Ye.getFullYear(),0,4)),cn=it(cn),0>=et(xr,Ye)?0>=et(cn,Ye)?Ye.getFullYear()+1:Ye.getFullYear():Ye.getFullYear()-1}b>>>=0,C>>>=0,L>>>=0,V>>>=0;var Ot=v()[V+40>>>2>>>0];for(var Jt in V={lc:m()[V>>>2>>>0],kc:m()[V+4>>>2>>>0],Ib:m()[V+8>>>2>>>0],Mb:m()[V+12>>>2>>>0],Jb:m()[V+16>>>2>>>0],Db:m()[V+20>>>2>>>0],vb:m()[V+24>>>2>>>0],Cb:m()[V+28>>>2>>>0],sc:m()[V+32>>>2>>>0],jc:m()[V+36>>>2>>>0],mc:Ot?bn(Ot):""},L=bn(L),Ot={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})L=L.replace(new RegExp(Jt,"g"),Ot[Jt]);var Ar="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),jr="January February March April May June July August September October November December".split(" ");for(Jt in Ot={"%a":Ye=>Ar[Ye.vb].substring(0,3),"%A":Ye=>Ar[Ye.vb],"%b":Ye=>jr[Ye.Jb].substring(0,3),"%B":Ye=>jr[Ye.Jb],"%C":Ye=>Me((Ye.Db+1900)/100|0,2),"%d":Ye=>Me(Ye.Mb,2),"%e":Ye=>Q(Ye.Mb,2," "),"%g":Ye=>Tt(Ye).toString().substring(2),"%G":Tt,"%H":Ye=>Me(Ye.Ib,2),"%I":Ye=>((Ye=Ye.Ib)==0?Ye=12:12{for(var xr=0,cn=0;cn<=Ye.Jb-1;xr+=(wl(Ye.Db+1900)?vy:Ey)[cn++]);return Me(Ye.Mb+xr,3)},"%m":Ye=>Me(Ye.Jb+1,2),"%M":Ye=>Me(Ye.kc,2),"%n":()=>` `,"%p":Ye=>0<=Ye.Ib&&12>Ye.Ib?"AM":"PM","%S":Ye=>Me(Ye.lc,2),"%t":()=>" ","%u":Ye=>Ye.vb||7,"%U":Ye=>Me(Math.floor((Ye.Cb+7-Ye.vb)/7),2),"%V":Ye=>{var xr=Math.floor((Ye.Cb+7-(Ye.vb+6)%7)/7);if(2>=(Ye.vb+371-Ye.Cb-2)%7&&xr++,xr)xr==53&&((cn=(Ye.vb+371-Ye.Cb)%7)==4||cn==3&&wl(Ye.Db)||(xr=1));else{xr=52;var cn=(Ye.vb+7-Ye.Cb-1)%7;(cn==4||cn==5&&wl(Ye.Db%400-1))&&xr++}return Me(xr,2)},"%w":Ye=>Ye.vb,"%W":Ye=>Me(Math.floor((Ye.Cb+7-(Ye.vb+6)%7)/7),2),"%y":Ye=>(Ye.Db+1900).toString().substring(2),"%Y":Ye=>Ye.Db+1900,"%z":Ye=>{var xr=0<=(Ye=Ye.jc);return Ye=Math.abs(Ye)/60,(xr?"+":"-")+("0000"+(Ye/60*100+Ye%60)).slice(-4)},"%Z":Ye=>Ye.mc,"%%":()=>"%"},L=L.replace(/%%/g,"\0\0"),Ot)L.includes(Jt)&&(L=L.replace(new RegExp(Jt,"g"),Ot[Jt](V)));return Jt=function(Ye){var xr=Array(lg(Ye)+1);return Db(Ye,xr,0,xr.length),xr}(L=L.replace(/\0\0/g,"%")),Jt.length>C?0:(a2(Jt,b),Jt.length-1)}function i2(b,C,L,V){return Ty(b>>>0,C>>>0,L>>>0,V>>>0)}ne||function(){for(var b=E.numThreads-1;b--;)Ib();di.unshift(()=>{qf++,function(C){ne?C():Promise.all(fi.map(kb)).then(C)}(()=>yb())})}();for(var xy=Array(256),Lm=0;256>Lm;++Lm)xy[Lm]=String.fromCharCode(Lm);Yb=xy,pi=E.BindingError=class extends Error{constructor(b){super(b),this.name="BindingError"}},E.InternalError=class extends Error{constructor(b){super(b),this.name="InternalError"}},Da.push(0,1,void 0,1,null,1,!0,1,!1,1),E.count_emval_handles=()=>Da.length/2-5-hg.length;var o2=[og,Pb,$b,Fb,Nb,Bb,jb,zb,Ub,Vb,Wb,Gb,Hb,Kb,qb,Zb,ly,cy,my,_y,gy,by,yy,wy],Yt=function(){function b(L,V){return Yt=L.exports,Yt=function(){var Q=Yt,Me={};for(let[et,it]of Object.entries(Q))Me[et]=typeof it=="function"?(...Tt)=>{km.push(et);try{return it(...Tt)}finally{on||(km.pop(),ya&&_i===1&&km.length===0&&(_i=0,co+=1,Am(Oy),typeof Fibers<"u"&&Fibers.tc()))}}:it;return Me}(),Yt=function(){var Q=Yt,Me=it=>Tt=>it(Tt)>>>0,et=it=>()=>it()>>>0;return(Q=Object.assign({},Q)).Da=Me(Q.Da),Q.gb=et(Q.gb),Q.ib=Me(Q.ib),Q.emscripten_main_runtime_thread_id=et(Q.emscripten_main_runtime_thread_id),Q.tb=Me(Q.tb),Q.ub=et(Q.ub),Q}(),Cb.push(Yt.jb),Kf.unshift(Yt.Ca),Br=V,yb(),Yt}var C=xb();if(qf++,E.instantiateWasm)try{return E.instantiateWasm(C,b)}catch(L){Pt(`Module.instantiateWasm callback failed with error: ${L}`),R(L)}return ng||(ng=E.locateFile?wb("ort-wasm-simd-threaded.jsep.wasm")?"ort-wasm-simd-threaded.jsep.wasm":E.locateFile?E.locateFile("ort-wasm-simd-threaded.jsep.wasm",tt):tt+"ort-wasm-simd-threaded.jsep.wasm":new URL(t("./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm"),t.b).href),function(L,V){var Q=ng;return lt||typeof WebAssembly.instantiateStreaming!="function"||wb(Q)||vb(Q)||typeof fetch!="function"?Tb(Q,L,V):fetch(Q,{credentials:"same-origin"}).then(Me=>WebAssembly.instantiateStreaming(Me,L).then(V,function(et){return Pt(`wasm streaming compile failed: ${et}`),Pt("falling back to ArrayBuffer instantiation"),Tb(Q,L,V)}))}(C,function(L){b(L.instance,L.module)}).catch(R),{}}(),My=b=>(My=Yt.Da)(b),Py=()=>(Py=Yt.Ea)();E._OrtInit=(b,C)=>(E._OrtInit=Yt.Fa)(b,C),E._OrtGetLastError=(b,C)=>(E._OrtGetLastError=Yt.Ga)(b,C),E._OrtCreateSessionOptions=(b,C,L,V,Q,Me,et,it,Tt,Ot)=>(E._OrtCreateSessionOptions=Yt.Ha)(b,C,L,V,Q,Me,et,it,Tt,Ot),E._OrtAppendExecutionProvider=(b,C)=>(E._OrtAppendExecutionProvider=Yt.Ia)(b,C),E._OrtAddFreeDimensionOverride=(b,C,L)=>(E._OrtAddFreeDimensionOverride=Yt.Ja)(b,C,L),E._OrtAddSessionConfigEntry=(b,C,L)=>(E._OrtAddSessionConfigEntry=Yt.Ka)(b,C,L),E._OrtReleaseSessionOptions=b=>(E._OrtReleaseSessionOptions=Yt.La)(b),E._OrtCreateSession=(b,C,L)=>(E._OrtCreateSession=Yt.Ma)(b,C,L),E._OrtReleaseSession=b=>(E._OrtReleaseSession=Yt.Na)(b),E._OrtGetInputOutputCount=(b,C,L)=>(E._OrtGetInputOutputCount=Yt.Oa)(b,C,L),E._OrtGetInputName=(b,C)=>(E._OrtGetInputName=Yt.Pa)(b,C),E._OrtGetOutputName=(b,C)=>(E._OrtGetOutputName=Yt.Qa)(b,C),E._OrtFree=b=>(E._OrtFree=Yt.Ra)(b),E._OrtCreateTensor=(b,C,L,V,Q,Me)=>(E._OrtCreateTensor=Yt.Sa)(b,C,L,V,Q,Me),E._OrtGetTensorData=(b,C,L,V,Q)=>(E._OrtGetTensorData=Yt.Ta)(b,C,L,V,Q),E._OrtReleaseTensor=b=>(E._OrtReleaseTensor=Yt.Ua)(b),E._OrtCreateRunOptions=(b,C,L,V)=>(E._OrtCreateRunOptions=Yt.Va)(b,C,L,V),E._OrtAddRunConfigEntry=(b,C,L)=>(E._OrtAddRunConfigEntry=Yt.Wa)(b,C,L),E._OrtReleaseRunOptions=b=>(E._OrtReleaseRunOptions=Yt.Xa)(b),E._OrtCreateBinding=b=>(E._OrtCreateBinding=Yt.Ya)(b),E._OrtBindInput=(b,C,L)=>(E._OrtBindInput=Yt.Za)(b,C,L),E._OrtBindOutput=(b,C,L,V)=>(E._OrtBindOutput=Yt._a)(b,C,L,V),E._OrtClearBoundOutputs=b=>(E._OrtClearBoundOutputs=Yt.$a)(b),E._OrtReleaseBinding=b=>(E._OrtReleaseBinding=Yt.ab)(b),E._OrtRunWithBinding=(b,C,L,V,Q)=>(E._OrtRunWithBinding=Yt.bb)(b,C,L,V,Q),E._OrtRun=(b,C,L,V,Q,Me,et,it)=>(E._OrtRun=Yt.cb)(b,C,L,V,Q,Me,et,it),E._OrtEndProfiling=b=>(E._OrtEndProfiling=Yt.db)(b),E._JsepOutput=(b,C,L)=>(E._JsepOutput=Yt.eb)(b,C,L),E._JsepGetNodeName=b=>(E._JsepGetNodeName=Yt.fb)(b);var Rm,vl=()=>(vl=Yt.gb)(),wa=E._free=b=>(wa=E._free=Yt.hb)(b),Fm=E._malloc=b=>(Fm=E._malloc=Yt.ib)(b),vg=(b,C,L,V,Q,Me)=>(vg=Yt.lb)(b,C,L,V,Q,Me),Cy=()=>(Cy=Yt.mb)(),Sy=(b,C,L,V,Q)=>(Sy=Yt.nb)(b,C,L,V,Q),Eg=b=>(Eg=Yt.ob)(b),Nm=b=>(Nm=Yt.pb)(b),Ay=()=>(Ay=Yt.qb)(),ky=(b,C)=>(ky=Yt.rb)(b,C),Dm=b=>(Dm=Yt.sb)(b),Tg=b=>(Tg=Yt.tb)(b),xg=()=>(xg=Yt.ub)(),Iy=E.dynCall_ii=(b,C)=>(Iy=E.dynCall_ii=Yt.wb)(b,C),$y=b=>($y=Yt.xb)(b),Oy=()=>(Oy=Yt.yb)(),Ly=b=>(Ly=Yt.zb)(b),Ry=()=>(Ry=Yt.Ab)();function Fy(){0xg(),E.stackRestore=b=>Dm(b),E.stackAlloc=b=>Tg(b),E.setValue=function(b,C,L="i8"){switch(L.endsWith("*")&&(L="*"),L){case"i1":case"i8":l()[b>>>0]=C;break;case"i16":p()[b>>>1>>>0]=C;break;case"i32":m()[b>>>2>>>0]=C;break;case"i64":Pn[b>>>3]=BigInt(C);break;case"float":x()[b>>>2>>>0]=C;break;case"double":P()[b>>>3>>>0]=C;break;case"*":v()[b>>>2>>>0]=C;break;default:hi(`invalid type for setValue: ${L}`)}},E.getValue=function(b,C="i8"){switch(C.endsWith("*")&&(C="*"),C){case"i1":case"i8":return l()[b>>>0];case"i16":return p()[b>>>1>>>0];case"i32":return m()[b>>>2>>>0];case"i64":return Pn[b>>>3];case"float":return x()[b>>>2>>>0];case"double":return P()[b>>>3>>>0];case"*":return v()[b>>>2>>>0];default:hi(`invalid type for getValue: ${C}`)}},E.UTF8ToString=bn,E.stringToUTF8=yl,E.lengthBytesUTF8=lg,Zf=function b(){Rm||Fy(),Rm||(Zf=b)},Fy(),E.PTR_SIZE=4,K}),nn=Yr,((s=globalThis.self)==null?void 0:s.name)==="em-pthread"&&Yr()}),Es,na,fn,fs,qt,sa,Ts,xs,aa,Kn,ia,Ms,Fs,Ns=c(()=>{rt(),Es=typeof location>"u"?void 0:location.origin,na=()=>{var s;return(s=import.meta.url)!=null&&s.startsWith("file:")?new URL(new URL(t("./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs?46eb"),t.b).href,Es).href:import.meta.url},fn=na(),fs=()=>{if(fn&&!fn.startsWith("blob:"))return fn.substring(0,fn.lastIndexOf("/")+1)},qt=(s,i)=>{try{let l=i??fn;return(l?new URL(s,l):new URL(s)).origin===Es}catch{return!1}},sa=(s,i)=>{let l=i??fn;try{return(l?new URL(s,l):new URL(s)).href}catch{return}},Ts=(s,i)=>`${i??"./"}${s}`,xs=async s=>{let i=await(await fetch(s,{credentials:"same-origin"})).blob();return URL.createObjectURL(i)},aa=async s=>(await import(s)).default,Kn=(Nt(),y(dt)).default,ia=async()=>{if(!fn)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(qt(fn))return[void 0,Kn()];let s=await xs(fn);return[s,Kn(s)]},Ms=($n(),y(br)).default,Fs=async(s,i,l)=>{if(!s&&!i&&Ms&&fn&&qt(fn))return[void 0,Ms];{let f="ort-wasm-simd-threaded.jsep.mjs",p=s??sa(f,i),g=l&&p&&!qt(p,i),m=g?await xs(p):p??Ts(f,i);return[g?m:void 0,await aa(m)]}}}),jn,ot,At,Ut,pn,Ds,Ps,Dr,zn=c(()=>{Ns(),ot=!1,At=!1,Ut=!1,pn=()=>{if(typeof SharedArrayBuffer>"u")return!1;try{return typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},Ds=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},Ps=async s=>{if(ot)return Promise.resolve();if(At)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Ut)throw new Error("previous call to 'initializeWebAssembly()' failed.");At=!0;let i=s.initTimeout,l=s.numThreads;if(!Ds())throw new Error("WebAssembly SIMD is not supported in the current environment.");let f=pn();l>1&&!f&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+l+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),s.numThreads=l=1);let p=s.wasmPaths,g=typeof p=="string"?p:void 0,m=p==null?void 0:p.mjs,v=(m==null?void 0:m.href)??m,x=p==null?void 0:p.wasm,P=(x==null?void 0:x.href)??x,D=s.wasmBinary,[R,E]=await Fs(v,g,l>1),K=!1,q=[];if(i>0&&q.push(new Promise(Y=>{setTimeout(()=>{K=!0,Y()},i)})),q.push(new Promise((Y,ne)=>{let se={numThreads:l};if(D)se.wasmBinary=D;else if(P||g)se.locateFile=te=>P??g+te;else if(v&&v.indexOf("blob:")!==0)se.locateFile=te=>new URL(te,v).href;else if(R){let te=fs();te&&(se.locateFile=ye=>te+ye)}E(se).then(te=>{At=!1,ot=!0,jn=te,Y(),R&&URL.revokeObjectURL(R)},te=>{At=!1,Ut=!0,ne(te)})})),await Promise.race(q),K)throw new Error(`WebAssembly backend initializing failed due to timeout: ${i}ms`)},Dr=()=>{if(ot&&jn)return jn;throw new Error("WebAssembly is not initialized yet.")}}),en,ps,fr,Ma=c(()=>{zn(),en=(s,i)=>{let l=Dr(),f=l.lengthBytesUTF8(s)+1,p=l._malloc(f);return l.stringToUTF8(s,p,f),i.push(p),p},ps=(s,i,l,f)=>{if(typeof s=="object"&&s!==null){if(l.has(s))throw new Error("Circular reference in options");l.add(s)}Object.entries(s).forEach(([p,g])=>{let m=i?i+p:p;if(typeof g=="object")ps(g,m+".",l,f);else if(typeof g=="string"||typeof g=="number")f(m,g.toString());else if(typeof g=="boolean")f(m,g?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof g}`)})},fr=s=>{let i=Dr(),l=i.stackSave();try{let f=i.PTR_SIZE,p=i.stackAlloc(2*f);i._OrtGetLastError(p,p+f);let g=Number(i.getValue(p,f===4?"i32":"i64")),m=i.getValue(p+f,"*"),v=m?i.UTF8ToString(m):"";throw new Error(`${s} ERROR_CODE: ${g}, ERROR_MESSAGE: ${v}`)}finally{i.stackRestore(l)}}}),Bs,$i=c(()=>{zn(),Ma(),Bs=s=>{let i=Dr(),l=0,f=[],p=s||{};try{if((s==null?void 0:s.logSeverityLevel)===void 0)p.logSeverityLevel=2;else if(typeof s.logSeverityLevel!="number"||!Number.isInteger(s.logSeverityLevel)||s.logSeverityLevel<0||s.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${s.logSeverityLevel}`);if((s==null?void 0:s.logVerbosityLevel)===void 0)p.logVerbosityLevel=0;else if(typeof s.logVerbosityLevel!="number"||!Number.isInteger(s.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${s.logVerbosityLevel}`);(s==null?void 0:s.terminate)===void 0&&(p.terminate=!1);let g=0;return(s==null?void 0:s.tag)!==void 0&&(g=en(s.tag,f)),l=i._OrtCreateRunOptions(p.logSeverityLevel,p.logVerbosityLevel,!!p.terminate,g),l===0&&fr("Can't create run options."),(s==null?void 0:s.extra)!==void 0&&ps(s.extra,"",new WeakSet,(m,v)=>{let x=en(m,f),P=en(v,f);i._OrtAddRunConfigEntry(l,x,P)!==0&&fr(`Can't set a run config entry: ${m} - ${v}.`)}),[l,f]}catch(g){throw l!==0&&i._OrtReleaseRunOptions(l),f.forEach(m=>i._free(m)),g}}}),Ha,Ka,qa,js,Za,Oi=c(()=>{zn(),Ma(),Ha=s=>{switch(s){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${s}`)}},Ka=s=>{switch(s){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${s}`)}},qa=s=>{s.extra||(s.extra={}),s.extra.session||(s.extra.session={});let i=s.extra.session;i.use_ort_model_bytes_directly||(i.use_ort_model_bytes_directly="1"),s.executionProviders&&s.executionProviders.some(l=>(typeof l=="string"?l:l.name)==="webgpu")&&(s.enableMemPattern=!1)},js=(s,i,l)=>{for(let f of i){let p=typeof f=="string"?f:f.name;switch(p){case"webnn":if(p="WEBNN",typeof f!="string"){let m=f==null?void 0:f.deviceType;if(m){let v=en("deviceType",l),x=en(m,l);Dr()._OrtAddSessionConfigEntry(s,v,x)!==0&&fr(`Can't set a session config entry: 'deviceType' - ${m}.`)}}break;case"webgpu":if(p="JS",typeof f!="string"){let m=f;if(m!=null&&m.preferredLayout){if(m.preferredLayout!=="NCHW"&&m.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${m.preferredLayout}`);let v=en("preferredLayout",l),x=en(m.preferredLayout,l);Dr()._OrtAddSessionConfigEntry(s,v,x)!==0&&fr(`Can't set a session config entry: 'preferredLayout' - ${m.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${p}`)}let g=en(p,l);Dr()._OrtAppendExecutionProvider(s,g)!==0&&fr(`Can't append execution provider: ${p}.`)}},Za=s=>{let i=Dr(),l=0,f=[],p=s||{};qa(p);try{let g=Ha(p.graphOptimizationLevel??"all"),m=Ka(p.executionMode??"sequential"),v=typeof p.logId=="string"?en(p.logId,f):0,x=p.logSeverityLevel??2;if(!Number.isInteger(x)||x<0||x>4)throw new Error(`log serverity level is not valid: ${x}`);let P=p.logVerbosityLevel??0;if(!Number.isInteger(P)||P<0||P>4)throw new Error(`log verbosity level is not valid: ${P}`);let D=typeof p.optimizedModelFilePath=="string"?en(p.optimizedModelFilePath,f):0;if(l=i._OrtCreateSessionOptions(g,!!p.enableCpuMemArena,!!p.enableMemPattern,m,!!p.enableProfiling,0,v,x,P,D),l===0&&fr("Can't create session options."),p.executionProviders&&js(l,p.executionProviders,f),p.enableGraphCapture!==void 0){if(typeof p.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${p.enableGraphCapture}`);let R=en("enableGraphCapture",f),E=en(p.enableGraphCapture.toString(),f);i._OrtAddSessionConfigEntry(l,R,E)!==0&&fr(`Can't set a session config entry: 'enableGraphCapture' - ${p.enableGraphCapture}.`)}if(p.freeDimensionOverrides)for(let[R,E]of Object.entries(p.freeDimensionOverrides)){if(typeof R!="string")throw new Error(`free dimension override name must be a string: ${R}`);if(typeof E!="number"||!Number.isInteger(E)||E<0)throw new Error(`free dimension override value must be a non-negative integer: ${E}`);let K=en(R,f);i._OrtAddFreeDimensionOverride(l,K,E)!==0&&fr(`Can't set a free dimension override: ${R} - ${E}.`)}return p.extra!==void 0&&ps(p.extra,"",new WeakSet,(R,E)=>{let K=en(R,f),q=en(E,f);i._OrtAddSessionConfigEntry(l,K,q)!==0&&fr(`Can't set a session config entry: ${R} - ${E}.`)}),[l,f]}catch(g){throw l!==0&&i._OrtReleaseSessionOptions(l)!==0&&fr("Can't release session options."),f.forEach(m=>i._free(m)),g}}}),zs,rs,Un,Pa,oa,Ca,Sa,Aa,Wt=c(()=>{zs=s=>{switch(s){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${s}`)}},rs=s=>{switch(s){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${s}`)}},Un=(s,i)=>{let l=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][s],f=typeof i=="number"?i:i.reduce((p,g)=>p*g,1);return l>0?Math.ceil(f*l):void 0},Pa=s=>{switch(s){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${s}`)}},oa=s=>{switch(s){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${s}`)}},Ca=s=>s==="float32"||s==="float16"||s==="int32"||s==="int64"||s==="uint32"||s==="uint8"||s==="bool"||s==="uint4"||s==="int4",Sa=s=>s==="float32"||s==="float16"||s==="int32"||s==="int64"||s==="uint32"||s==="uint64"||s==="int8"||s==="uint8"||s==="bool"||s==="uint4"||s==="int4",Aa=s=>{switch(s){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${s}`)}}}),ka,Ya=c(()=>{rt(),ka=async s=>{if(typeof s=="string"){let i=await fetch(s);if(!i.ok)throw new Error(`failed to load external data file: ${s}`);let l=i.headers.get("Content-Length"),f=l?parseInt(l,10):0;if(f<1073741824)return new Uint8Array(await i.arrayBuffer());{if(!i.body)throw new Error(`failed to load external data file: ${s}, no response body.`);let p=i.body.getReader(),g;try{g=new ArrayBuffer(f)}catch(v){if(v instanceof RangeError){let x=Math.ceil(f/65536);g=new WebAssembly.Memory({initial:x,maximum:x}).buffer}else throw v}let m=0;for(;;){let{done:v,value:x}=await p.read();if(v)break;let P=x.byteLength;new Uint8Array(g,m,P).set(x),m+=P}return new Uint8Array(g,0,f)}}else return s instanceof Blob?new Uint8Array(await s.arrayBuffer()):s instanceof Uint8Array?s:new Uint8Array(s)}}),Xa,Qa,Us,Ja,Ia,ei,Tr,Ie=c(()=>{Wt(),Xa=["V","I","W","E","F"],Qa=(s,i)=>{console.log(`[${Xa[s]},${new Date().toISOString()}]${i}`)},Ia=(s,i)=>{Us=s,Ja=i},ei=(s,i)=>{let l=oa(s),f=oa(Us);l>=f&&Qa(l,typeof i=="function"?i():i)},Tr=(...s)=>{Ja&&ei(...s)}}),N,ee=c(()=>{Wt(),N=(s,i)=>new(Pa(i))(s)}),fe=c(()=>{}),Ae,Oe,Je,_t,Et,yt,St,tr,kr,Pr=c(()=>{Ie(),fe(),Ae=new Map([[64,250],[128,200],[256,200],[512,200],[2048,230],[4096,200],[8192,50],[16384,50],[32768,50],[65536,50],[131072,50],[262144,50],[524288,50],[1048576,50],[2097152,30],[4194304,20],[8388608,10],[12582912,10],[16777216,10],[26214400,15],[33554432,22],[44236800,2],[58982400,6],[67108864,6],[134217728,6],[167772160,6]]),Oe=[],Je=s=>Math.ceil(Number(s)/16)*16,_t=s=>{for(let i=0;iEt++,St=async(s,i,l,f)=>{let p=Je(l),g=s.device.createBuffer({size:p,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let m=s.getCommandEncoder();s.endComputePass(),m.copyBufferToBuffer(i,0,g,0,p),s.flush(),await g.mapAsync(GPUMapMode.READ);let v=g.getMappedRange();if(f){let x=f();return x.set(new Uint8Array(v,0,l)),x}else return new Uint8Array(v.slice(0,l))}finally{g.destroy()}},tr=class{constructor(s){this.backend=s,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersPending=[],this.capturedPendingBuffers=new Map;for(let[i]of Ae)Oe.push(i),this.freeBuffers.set(i,[]),this.freeUniformBuffers.set(i,[]);this.sessionCount=0}upload(s,i){let l=i.buffer,f=i.byteOffset,p=i.byteLength,g=Je(p),m=this.storageCache.get(s);if(!m)throw new Error("gpu data for uploading does not exist");if(Number(m.originalSize)!==p)throw new Error(`inconsistent data size. gpu data size=${m.originalSize}, data size=${p}`);let v=this.backend.device.createBuffer({mappedAtCreation:!0,size:g,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),x=v.getMappedRange();new Uint8Array(x).set(new Uint8Array(l,f,p)),v.unmap();let P=this.backend.device.createCommandEncoder();P.copyBufferToBuffer(v,0,m.gpuData.buffer,0,g),this.backend.device.queue.submit([P.finish()]),v.destroy(),Tr("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${s})`)}memcpy(s,i){let l=this.storageCache.get(s);if(!l)throw new Error("source gpu data for memcpy does not exist");let f=this.storageCache.get(i);if(!f)throw new Error("destination gpu data for memcpy does not exist");if(l.originalSize!==f.originalSize)throw new Error("inconsistent source and destination gpu data size");let p=Je(l.originalSize),g=this.backend.getCommandEncoder();this.backend.endComputePass(),g.copyBufferToBuffer(l.gpuData.buffer,0,f.gpuData.buffer,0,p)}registerExternalBuffer(s,i,l){let f;if(l){if(f=l[0],s===l[1])return Tr("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${i}) => id=${f}, buffer is the same, skip.`),f;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error(`Registering a different external buffer under graph capture mode is not supported yet. Please use the previous external buffer!`)}else f=yt();return this.storageCache.set(f,{gpuData:{id:f,type:0,buffer:s},originalSize:i}),Tr("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${i}) => id=${f}, registered.`),f}unregisterExternalBuffer(s){s!==void 0&&(this.storageCache.delete(s),Tr("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${s}`))}create(s,i=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let l=_t(s),f,p=(i&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,g=(i&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(p||g){let v=(p?this.freeBuffers:this.freeUniformBuffers).get(l);v?v.length>0?f=v.pop():f=this.backend.device.createBuffer({size:l,usage:i}):f=this.backend.device.createBuffer({size:l,usage:i})}else f=this.backend.device.createBuffer({size:l,usage:i});let m={id:yt(),type:0,buffer:f};return this.storageCache.set(m.id,{gpuData:m,originalSize:Number(s)}),Tr("verbose",()=>`[WebGPU] GpuDataManager.create(size=${s}) => id=${m.id}`),m}get(s){var i;return(i=this.storageCache.get(s))==null?void 0:i.gpuData}release(s){let i=typeof s=="bigint"?Number(s):s,l=this.storageCache.get(i);if(!l){if(this.storageCache.size===0)return 0;throw new Error("releasing data does not exist")}return Tr("verbose",()=>`[WebGPU] GpuDataManager.release(id=${i}), gpuDataId=${l.gpuData.id}`),this.storageCache.delete(i),this.buffersPending.push(l.gpuData.buffer),l.originalSize}async download(s,i){let l=this.storageCache.get(Number(s));if(!l)throw new Error("data does not exist");await St(this.backend,l.gpuData.buffer,l.originalSize,i)}refreshPendingBuffers(){if(this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let s of this.buffersPending){let i=Ae.get(s.size);if((s.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let l=this.freeBuffers.get(s.size)||[];i===void 0||l.length>=i?s.destroy():l.push(s)}else if((s.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let l=this.freeUniformBuffers.get(s.size)||[];i===void 0||l.length>=i?s.destroy():l.push(s)}else s.destroy()}this.buffersPending=[]}else{let s=this.capturedPendingBuffers.get(this.backend.currentSessionId);s||(s=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,s));for(let i of this.buffersPending)s.push(i);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(s=>{s.forEach(i=>{i.destroy()})}),this.freeUniformBuffers.forEach(s=>{s.forEach(i=>{i.destroy()})}),this.storageCache.forEach(s=>{s.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(s=>{s.forEach(i=>{i.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onCreateSession(){this.sessionCount+=1}onReleaseSession(s){let i=this.capturedPendingBuffers.get(s);i&&(i.forEach(l=>{l.destroy()}),this.capturedPendingBuffers.delete(s)),this.sessionCount-=1,this.sessionCount===0&&(Tr("warning",()=>"[WebGPU] Clearing webgpu buffer cache"),this.storageCache.forEach(l=>{l.gpuData.buffer.destroy()}),this.storageCache=new Map)}},kr=(...s)=>new tr(...s)}),rn,Gt,mr=c(()=>{rn=class{constructor(s){Object.assign(this,s)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map(s=>`${this[s]}`).join(";")),this.key}},Gt=s=>new rn(s)}),On,mn,ze,xn,Cs,Xr,yn,jt=c(()=>{On=class{static calcMatMulShape(s,i){return s[1]!==i[0]?void 0:[s[0],i[1]]}},mn=class{static calcShape(s,i,l=!1){let f=s.length,p=i.length;if(f===0)return i;if(p===0)return s;let g=Math.max(s.length,i.length),m=new Array(g);if(l){if(f<2||p<2)return;let v=On.calcMatMulShape([s[f-2],s[f-1]],[i[p-2],i[p-1]]);if(v===void 0)return;[m[g-2],m[g-1]]=v}for(let v=l?3:1;v<=g;v++){let x=f-v<0?1:s[f-v],P=p-v<0?1:i[p-v];if(x!==P&&x>1&&P>1)return;let D=Math.max(x,P);if(x&&P)m[g-v]=Math.max(x,P);else{if(D>1)return;m[g-v]=0}}return m}static isValidBroadcast(s,i){let l=s.length,f=i.length;if(l>f)return!1;for(let p=1;p<=l;p++)if(s[l-p]!==1&&s[l-p]!==i[f-p])return!1;return!0}},ze=class qm{static size(i){return qm.getSizeFromDimensionRange(i,0,i.length)}static convertShape(i,l=4){let f=i.length;if(f===0)return[];let p=new Array(f),g=f-1;for(;g>=0;){if(i[g]%l===0){p[g]=i[g]/l;break}if(l%i[g]!==0)throw new Error("cannot convert shape");p[g]=1,l/=i[g],g--}for(g--;g>=0;g--)p[g]=i[g];return p}static sizeFromDimension(i,l){if(l<0||l>i.length)throw new Error(`invalid dimension of ${l} for sizeFromDimension as Tensor has ${i.length} dimensions.`);return qm.getSizeFromDimensionRange(i,l,i.length)}static sizeToDimension(i,l){if(l<0||l>i.length)throw new Error(`invalid dimension of ${l} for sizeToDimension as Tensor has ${i.length} dimensions.`);return qm.getSizeFromDimensionRange(i,0,l)}static getSizeFromDimensionRange(i,l,f){let p=1;for(let g=l;g=0;--p)f[p]=f[p+1]*i[p+1];return f}static normalizeAxis(i,l){if(i<-l&&i>=l)throw new Error("unsupported axis for this operation.");return i<0?i+l:i}static normalizeAxes(i,l){return i.map(f=>this.normalizeAxis(f,l??i.length))}static sortBasedOnPerm(i,l){return l?l.map(f=>i[f]):i.slice().reverse()}static padShape(i,l){let f=i.length;return i.map((p,g)=>p+l[g]+l[g+f])}static areEqual(i,l){return i.length!==l.length?!1:i.every((f,p)=>f===l[p])}},xn=class ep{static adjustPoolAttributes(i,l,f,p,g,m){if(!i&&f.length!==l.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(i)for(let v=0;v=f.length?f.push(l[v+2]):f[v]=l[v+2];for(let v=0;v=f[v]||m[v+f.length]>=f[v])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(i,l,f,p,g,m,v){if(v){if(g.length!==2*(i.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(l.length!==i.length-2)throw new Error("length of strides should be the length of data dimensions");if(p.length!==i.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let x=0;x{Wt(),jt(),Nn=64,ns=(s,i)=>{if(i===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(Number(s)){case 10:return i>1?`vec${i}`:"f16";case 1:return i>1?`vec${i}`:"f32";case 6:return i>1?`vec${i}`:"i32";case 12:return i>1?`vec${i}`:"u32";case 7:if(i>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","i32"];case 13:if(i>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","u32"];case 9:if(i!==4)throw new Error("bool must be vec4");return["u32","vec4"];case 22:return"i32";case 21:return"u32";default:throw new Error(`Unknown data type: ${s}`)}},Ir=(s,i=1)=>{let l=ns(s,i);return typeof l=="string"?l:l[0]},Qr=(s,i=1)=>{let l=ns(s,i);return typeof l=="string"?l:l[1]},xt=(...s)=>{let i=[];return s.forEach(l=>{l.length!==0&&i.push({type:12,data:l},{type:12,data:ze.computeStrides(l)})}),i},sr=s=>s%4===0?4:s%2===0?2:1,sn=(s="f32",i,l="0")=>!i||i===1?`${s}(${l})`:`vec${i}<${s}>(${l})`,Jr=(s,i,l)=>s==="f32"?l:i===1?`f32(${l})`:`vec${i}(${l})`,_n=(s,i)=>i===4?`(${s}.x + ${s}.y + ${s}.z + ${s}.w)`:i===2?`(${s}.x + ${s}.y)`:i===3?`(${s}.x + ${s}.y + ${s}.z)`:s,Ft=(s,i,l,f)=>s.startsWith("uniforms.")&&l>4?typeof i=="string"?f==="f16"?`${s}[(${i}) / 8][(${i}) % 8 / 4][(${i}) % 8 % 4]`:`${s}[(${i}) / 4][(${i}) % 4]`:f==="f16"?`${s}[${Math.floor(i/8)}][${Math.floor(i%8/4)}][${i%8%4}]`:`${s}[${Math.floor(i/4)}][${i%4}]`:l>1?`${s}[${i}]`:s,ua=(s,i,l,f,p)=>{let g=typeof l=="number",m=g?l:l.length,v=[...new Array(m).keys()],x=m<2?"u32":m<=4?`vec${m}`:`array`,P=ns(i,p),D=typeof P=="string"?P:P[1],R=typeof P=="string"?P:P[0],E={indices:x,value:D,storage:R,tensor:i},K=ut=>typeof ut=="string"?ut:`${ut}u`,q={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},Y=g?"uniforms.":"",ne=`${Y}${s}_shape`,se=`${Y}${s}_strides`,te="";for(let ut=0;ut ${E.indices} { var indices: ${E.indices}; var current = offset; ${te} return indices; }`,be=ut=>(q.offsetToIndices=!0,m<2?ut:`o2i_${s}(${ut})`),Ce=[];if(m>=2)for(let ut=m-1;ut>=0;ut--)Ce.push(`${Ft(se,ut,m)} * (indices[${ut}])`);let Be=m<2?"":` fn i2o_${s}(indices: ${E.indices}) -> u32 { return ${Ce.join("+")}; }`,je=ut=>(q.indicesToOffset=!0,m<2?ut:`i2o_${s}(${ut})`),tt=(...ut)=>m===0?"0u":`${E.indices}(${ut.map(K).join(",")})`,lt=(ut,It)=>m<2?`${ut}`:`${Ft(ut,It,m)}`,kt=(ut,It,Sr)=>m<2?`${ut}=${Sr};`:`${Ft(ut,It,m)}=${Sr};`,ir={},cr=(ut,It)=>{q.broadcastedIndicesToOffset=!0;let Sr=`${It.name}broadcastedIndicesTo${s}Offset`;if(Sr in ir)return`${Sr}(${ut})`;let ln=[];for(let ls=m-1;ls>=0;ls--){let Pn=It.indicesGet("outputIndices",ls+It.rank-m);ln.push(`${lt(se,ls)} * (${Pn} % ${lt(ne,ls)})`)}return ir[Sr]=`fn ${Sr}(outputIndices: ${It.type.indices}) -> u32 { return ${ln.length>0?ln.join("+"):"0u"}; }`,`${Sr}(${ut})`},Pt=(ut,It)=>(()=>{if(E.storage===E.value)return`${s}[${ut}]=${It};`;if(E.storage==="vec2"&&E.value==="i32")return`${s}[${ut}]=vec2(u32(${It}), select(0u, 0xFFFFFFFFu, ${It} < 0));`;if(E.storage==="vec2"&&E.value==="u32")return`${s}[${ut}]=vec2(u32(${It}), 0u);`;if(E.storage==="u32"&&E.value==="vec4")return`${s}[${ut}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${It}));`;throw new Error(`not supported combination of storage type ${E.storage} and value type ${E.value} yet`)})(),pr=ut=>(()=>{if(E.storage===E.value)return`${s}[${ut}]`;if(E.storage==="vec2"&&E.value==="i32")return`i32(${s}[${ut}].x)`;if(E.storage==="vec2"&&E.value==="u32")return`u32(${s}[${ut}].x)`;if(E.storage==="u32"&&E.value==="vec4")return`vec4(bool(${s}[${ut}] & 0xFFu), bool(${s}[${ut}] & 0xFF00u), bool(${s}[${ut}] & 0xFF0000u), bool(${s}[${ut}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${E.storage} and value type ${E.value} yet`)})(),Rt=m<2?"":` fn get_${s}ByIndices(indices: ${E.indices}) -> ${D} { return ${pr(`i2o_${s}(indices)`)}; }`,zt=m<2?"":(()=>{let ut=v.map(Sr=>`d${Sr}: u32`).join(", "),It=v.map(Sr=>`d${Sr}`).join(", ");return` fn get_${s}(${ut}) -> ${D} { return get_${s}ByIndices(${tt(It)}); }`})(),Br=(...ut)=>{if(ut.length!==m)throw new Error(`indices length must be ${m}`);let It=ut.map(K).join(",");return m===0?pr("0u"):m===1?pr(It[0]):(q.get=!0,q.getByIndices=!0,q.indicesToOffset=!0,`get_${s}(${It})`)},rr=ut=>m<2?pr(ut):(q.getByIndices=!0,q.indicesToOffset=!0,`get_${s}ByIndices(${ut})`),Kt=m<2?"":` fn set_${s}ByIndices(indices: ${E.indices}, value: ${D}) { ${Pt(`i2o_${s}(indices)`,"value")} }`,Or=m<2?"":(()=>{let ut=v.map(Sr=>`d${Sr}: u32`).join(", "),It=v.map(Sr=>`d${Sr}`).join(", ");return` fn set_${s}(${ut}, value: ${D}) { set_${s}ByIndices(${tt(It)}, value); }`})();return{impl:()=>{let ut=[],It=!1;return q.offsetToIndices&&(ut.push(ye),It=!0),q.indicesToOffset&&(ut.push(Be),It=!0),q.broadcastedIndicesToOffset&&(Object.values(ir).forEach(Sr=>ut.push(Sr)),It=!0),q.set&&(ut.push(Or),It=!0),q.setByIndices&&(ut.push(Kt),It=!0),q.get&&(ut.push(zt),It=!0),q.getByIndices&&(ut.push(Rt),It=!0),!g&&It&&ut.unshift(`const ${ne} = ${E.indices}(${l.join(",")});`,`const ${se} = ${E.indices}(${ze.computeStrides(l).join(",")});`),ut.join(` `)},type:E,offsetToIndices:be,indicesToOffset:je,broadcastedIndicesToOffset:cr,indices:tt,indicesGet:lt,indicesSet:kt,set:(...ut)=>{if(ut.length!==m+1)throw new Error(`indices length must be ${m}`);let It=ut[m];if(typeof It!="string")throw new Error("value must be string");let Sr=ut.slice(0,m).map(K).join(",");return m===0?Pt("0u",It):m===1?Pt(Sr[0],It):(q.set=!0,q.setByIndices=!0,q.indicesToOffset=!0,`set_${s}(${Sr}, ${It})`)},setByOffset:Pt,setByIndices:(ut,It)=>m<2?Pt(ut,It):(q.setByIndices=!0,q.indicesToOffset=!0,`set_${s}ByIndices(${ut}, ${It});`),get:Br,getByOffset:pr,getByIndices:rr,usage:f,name:s,strides:se,shape:ne,rank:m}},Qe=(s,i,l,f=1)=>ua(s,i,l,"input",f),Dt=(s,i,l,f=1)=>ua(s,i,l,"output",f),Hl=(s,i,l)=>ua(s,i,l,"atomicOutput",1),Co=(s,i,l,f=1)=>ua(s,i,l,"internal",f),Kl=class{constructor(s,i){this.normalizedDispatchGroup=s,this.limits=i,this.internalVariables=[],this.variables=[],this.uniforms=[],this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(s){return`if (global_idx >= ${typeof s=="number"?`${s}u`:s}) { return; }`}mainStart(s=Nn){let i=typeof s=="number"?s:s[0],l=typeof s=="number"?1:s[1],f=typeof s=="number"?1:s[2];if(i>this.limits.maxComputeWorkgroupSizeX||l>this.limits.maxComputeWorkgroupSizeY||f>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${i}, ${l}, ${f}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(i*l*f>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${i}, ${l}, ${f}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let p=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,g=p?`@builtin(global_invocation_id) global_id : vec3, @builtin(workgroup_id) workgroup_id : vec3, @builtin(local_invocation_index) local_idx : u32, @builtin(local_invocation_id) local_id : vec3`:`@builtin(global_invocation_id) global_id : vec3, @builtin(local_invocation_id) local_id : vec3, @builtin(local_invocation_index) local_idx : u32, @builtin(workgroup_id) workgroup_id : vec3, @builtin(num_workgroups) num_workgroups : vec3`,m=p?`let global_idx = global_id.x; let workgroup_index = workgroup_id.x;`:`let workgroup_index = workgroup_id.z * num_workgroups[0] * num_workgroups[1] + workgroup_id.y * num_workgroups[0] + workgroup_id.x; let global_idx = workgroup_index * ${i*l*f}u + local_idx;`;return`@compute @workgroup_size(${i}, ${l}, ${f}) fn main(${g}) { ${m} `}appendVariableUniforms(s){s.rank!==0&&(s.shape.startsWith("uniforms.")&&this.uniforms.push({name:s.shape.replace("uniforms.",""),type:"u32",length:s.rank}),s.strides.startsWith("uniforms.")&&this.uniforms.push({name:s.strides.replace("uniforms.",""),type:"u32",length:s.rank}))}declareVariable(s,i){if(s.usage==="internal")throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(s),this.appendVariableUniforms(s);let l=s.usage==="input"?"read":"read_write",f=s.usage==="atomicOutput"?"atomic":s.type.storage;return`@group(0) @binding(${i}) var ${s.name}: array<${f}>;`}declareVariables(...s){return s.map(i=>this.declareVariable(i,this.variableIndex++)).join(` `)}registerInternalVariable(s){if(s.usage!=="internal")throw new Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.");this.internalVariables.push(s),this.appendVariableUniforms(s)}registerInternalVariables(...s){return s.forEach(i=>this.registerInternalVariable(i)),this}registerUniform(s,i,l=1){return this.uniforms.push({name:s,type:i,length:l}),this}registerUniforms(s){return this.uniforms=this.uniforms.concat(s),this}uniformDeclaration(){if(this.uniforms.length===0)return"";let s=[];for(let{name:i,type:l,length:f}of this.uniforms)if(f&&f>4)l==="f16"?s.push(`@align(16) ${i}:array, ${Math.ceil(f/8)}>`):s.push(`${i}:array, ${Math.ceil(f/4)}>`);else{let p=f==null||f===1?l:`vec${f}<${l}>`;s.push(`${i}:${p}`)}return` struct Uniforms { ${s.join(", ")} }; @group(0) @binding(${this.variableIndex}) var uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(s=>s.impl()).join(` `)+this.internalVariables.map(s=>s.impl()).join(` `)}get variablesInfo(){if(this.uniforms.length===0)return;let s=i=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(i)];return this.uniforms.map(i=>[s(i.type),i.length??1])}},ql=(s,i)=>new Kl(s,i)}),Zl,So,Ao,Yl,Xl,ko,qn,Ql,Io,Vs=c(()=>{Wt(),jt(),mr(),or(),Zl=(s,i)=>{if(!s||s.length!==1)throw new Error("Transpose requires 1 input.");if(i.length!==0&&i.length!==s[0].dims.length)throw new Error(`perm size ${i.length} does not match input rank ${s[0].dims.length}`)},So=(s,i)=>i.length!==0?i:[...new Array(s).keys()].reverse(),Ao=(s,i)=>ze.sortBasedOnPerm(s,So(s.length,i)),Yl=(s,i,l,f)=>{let p=`fn perm(i: ${f.type.indices}) -> ${l.type.indices} { var a: ${l.type.indices};`;for(let g=0;g{let l=[],f=[];for(let p=0;p{let l=0;for(let f=0;f{let l=s.dataType,f=s.dims.length,p=So(f,i),g=Ao(s.dims,p),m=s.dims,v=g,x=f<2||ko(p,s.dims),P;if(x)return P=q=>{let Y=Qe("input",l,m,4),ne=Dt("output",l,v,4);return` ${q.registerUniform("output_size","u32").declareVariables(Y,ne)} ${q.mainStart()} ${q.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} output[global_idx] = input[global_idx]; }`},{name:"TransposeCopy",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let q=ze.size(g);return{outputs:[{dims:g,dataType:s.dataType}],dispatchGroup:{x:Math.ceil(q/64/4)},programUniforms:[{type:12,data:Math.ceil(q/4)}]}},getShaderSource:P};let{newShape:D,newPerm:R}=Xl(s.dims,p),E=ze.areEqual(R,[2,3,1]),K=ze.areEqual(R,[3,1,2]);if(D.length===2||E||K){m=E?[D[0],D[1]*D[2]]:K?[D[0]*D[1],D[2]]:D,v=[m[1],m[0]];let q=16;return P=Y=>{let ne=Qe("a",l,m.length),se=Dt("output",l,v.length);return` ${Y.registerUniform("output_size","u32").declareVariables(ne,se)} var tile : array, ${q}>; ${Y.mainStart([q,q,1])} let stride = (uniforms.output_shape[1] - 1) / ${q} + 1; let workgroup_id_x = workgroup_index % stride; let workgroup_id_y = workgroup_index / stride; let input_col = workgroup_id_y * ${q}u + local_id.x; let input_row = workgroup_id_x * ${q}u + local_id.y; if (input_row < uniforms.a_shape[0] && input_col < uniforms.a_shape[1]) { tile[local_id.y][local_id.x] = ${ne.getByIndices(`${ne.type.indices}(input_row, input_col)`)}; } workgroupBarrier(); let output_col = workgroup_id_x * ${q}u + local_id.x; let output_row = workgroup_id_y * ${q}u + local_id.y; if (output_row < uniforms.output_shape[0] && output_col < uniforms.output_shape[1]) { ${se.setByIndices(`${se.type.indices}(output_row, output_col)`,"tile[local_id.x][local_id.y]")} } }`},{name:"TransposeShared",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let Y=ze.size(g);return{outputs:[{dims:g,dataType:s.dataType}],dispatchGroup:{x:Math.ceil(v[1]/q),y:Math.ceil(v[0]/q)},programUniforms:[{type:12,data:Y},...xt(m,v)]}},getShaderSource:P}}return P=q=>{let Y=Qe("a",l,m.length),ne=Dt("output",l,v.length);return` ${q.registerUniform("output_size","u32").declareVariables(Y,ne)} ${Yl(p,f,Y,ne)} ${q.mainStart()} ${q.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${ne.offsetToIndices("global_idx")}; let aIndices = perm(indices); ${ne.setByOffset("global_idx",Y.getByIndices("aIndices"))} }`},{name:"Transpose",shaderCache:{hint:`${i}`,inputDependencies:["rank"]},getRunData:()=>{let q=ze.size(g);return{outputs:[{dims:g,dataType:s.dataType}],dispatchGroup:{x:Math.ceil(q/64)},programUniforms:[{type:12,data:q},...xt(m,v)]}},getShaderSource:P}},Ql=(s,i)=>{Zl(s.inputs,i.perm),s.compute(qn(s.inputs[0],i.perm))},Io=s=>Gt({perm:s.perm})}),Li,Jl,ec,tc,rc,nc,sc,ac,$o,ic,Zn,la,oc,Bp,uc,jp,lc,Oo,cc,dc,hc,zp=c(()=>{Wt(),jt(),or(),Ni(),Vs(),Li={max:"select(bestValue, candidate, candidate > bestValue)",min:"select(bestValue, candidate, candidate < bestValue)",mean:"bestValue + candidate",sum:"bestValue + candidate",prod:"bestValue * candidate",sumSquare:"bestValue + candidate * candidate",logSumExp:"bestValue + exp(candidate)",l1:"bestValue + abs(candidate)",l2:"bestValue + candidate * candidate",logSum:"bestValue + candidate"},Jl={max:"select(bestValue, candidate, candidate > bestValue)",min:"select(bestValue, candidate, candidate < bestValue)",mean:"bestValue + candidate",sum:"bestValue + candidate",prod:"bestValue * candidate",sumSquare:"bestValue + candidate",logSumExp:"bestValue + candidate",l1:"bestValue + candidate",l2:"bestValue + candidate",logSum:"bestValue + candidate"},ec={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},tc={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},rc=(s,i)=>{let l=[];for(let f=i-s;f{let l=[],f=s.length;for(let g=0;gs[g]);return[l,p]},sc=(s,i)=>{let l=s.length+i.length,f=[],p=0;for(let g=0;g{for(let l=0;l{let l=[];if(!ac(s,i)){for(let f=0;fl.push(f))}return l},ic=(s,i,l,f,p,g,m)=>{let v=l[0].dims,x=ze.size(g),P=ze.size(m),D=Qe("_A",l[0].dataType,v),R=Dt("output",p,g),E=64;x===1&&(E=256);let K=` var aBestValues : array; `,q=Y=>` ${Y.registerUniform("reduceSize","u32").declareVariables(D,R)} ${K} fn DIV_CEIL(a : u32, b : u32) -> u32 { return ((a - 1u) / b + 1u); } ${Y.mainStart(E)} let outputIndex = global_idx / ${E}; let offset = outputIndex * uniforms.reduceSize; var bestValue = f32(${ec[f]}); let Length = uniforms.reduceSize; for (var k = local_idx; k < Length; k = k + ${E}) { let candidate = f32(${D.getByOffset("offset + k")}); bestValue = ${Li[f]}; } aBestValues[local_idx] = bestValue; workgroupBarrier(); var reduceSize = min(Length, ${E}u); for (var currentSize = reduceSize / 2u; reduceSize > 1u; currentSize = reduceSize / 2u) { let interval = DIV_CEIL(reduceSize, 2u); if (local_idx < currentSize) { let candidate = aBestValues[local_idx + interval]; bestValue = ${Jl[f]}; aBestValues[local_idx] = bestValue; } reduceSize = interval; workgroupBarrier(); } if (local_idx == 0u) { ${R.setByOffset("outputIndex",`${f==="mean"?`${R.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${R.type.storage}(${tc[f]})`}`)}; } }`;return{name:s,shaderCache:{hint:`${i};${E}`,inputDependencies:["type"]},getShaderSource:q,getRunData:()=>({outputs:[{dims:g,dataType:p}],dispatchGroup:{x},programUniforms:[{type:12,data:P}]})}},Zn=(s,i,l,f)=>{let p=s.inputs.length===1?l:Lo(s.inputs,l),g=p.axes;g.length===0&&!p.noopWithEmptyAxes&&(g=s.inputs[0].dims.map((K,q)=>q));let m=ze.normalizeAxes(g,s.inputs[0].dims.length),v=m,x=s.inputs[0],P=$o(v,s.inputs[0].dims.length);P.length>0&&(x=s.compute(qn(s.inputs[0],P),{inputs:[0],outputs:[-1]})[0],v=rc(v.length,x.dims.length));let[D,R]=nc(x.dims,v),E=D;p.keepDims&&(E=sc(D,m)),s.compute(ic(i,p.cacheKey,[x],f,s.inputs[0].dataType,E,R),{inputs:[x]})},la=(s,i)=>{Zn(s,"ReduceMeanShared",i,"mean")},oc=(s,i)=>{Zn(s,"ReduceL1Shared",i,"l1")},Bp=(s,i)=>{Zn(s,"ReduceL2Shared",i,"l2")},uc=(s,i)=>{Zn(s,"ReduceLogSumExpShared",i,"logSumExp")},jp=(s,i)=>{Zn(s,"ReduceMaxShared",i,"max")},lc=(s,i)=>{Zn(s,"ReduceMinShared",i,"min")},Oo=(s,i)=>{Zn(s,"ReduceProdShared",i,"prod")},cc=(s,i)=>{Zn(s,"ReduceSumShared",i,"sum")},dc=(s,i)=>{Zn(s,"ReduceSumSquareShared",i,"sumSquare")},hc=(s,i)=>{Zn(s,"ReduceLogSumShared",i,"logSum")}}),ss,Ri,Fi,Lo,as,Ro,fc,pc,Fo,mc,_c,No,gc,bc,Do,is,yc,Bo,wc,vc,jo,Ec,Tc,zo,xc,Mc,Ni=c(()=>{Wt(),jt(),mr(),or(),zp(),ss=s=>{if(!s||s.length===0||s.length>2)throw new Error("Reduce op requires 1 or 2 inputs.");if(s.length===2&&s[1].dims.length!==1)throw new Error("Invalid axes input dims.")},Ri=s=>["","",`var value = ${s.getByIndices("input_indices")};`,""],Fi=(s,i,l,f,p,g,m=!1,v=!1)=>{let x=[],P=l[0].dims,D=P.length,R=ze.normalizeAxes(p,D),E=!v&&R.length===0;P.forEach((Y,ne)=>{E||R.indexOf(ne)>=0?m&&x.push(1):x.push(Y)});let K=x.length,q=ze.size(x);return{name:s,shaderCache:i,getShaderSource:Y=>{let ne=[],se=Qe("_A",l[0].dataType,D),te=Dt("output",g,K),ye=f(se,te,R),be=ye[2];for(let Ce=0,Be=0;Ce=0?(m&&Be++,be=`for(var j${Ce}: u32 = 0; j${Ce} < ${P[Ce]}; j${Ce}++) { ${ye[2].includes("last_index")?`let last_index = j${Ce};`:""} ${se.indicesSet("input_indices",Ce,`j${Ce}`)} ${be} }`):(ne.push(`${se.indicesSet("input_indices",Ce,te.indicesGet("output_indices",Be))};`),Be++);return` ${Y.registerUniform("output_size","u32").declareVariables(se,te)} ${Y.mainStart()} ${Y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} var input_indices: ${se.type.indices}; let output_indices = ${te.offsetToIndices("global_idx")}; ${ne.join(` `)} ${ye[0]} // init ops for reduce max/min ${ye[1]} ${be} ${ye[3]} ${ye.length===4?te.setByOffset("global_idx","value"):ye.slice(4).join(` `)} }`},getRunData:()=>({outputs:[{dims:x,dataType:g}],dispatchGroup:{x:Math.ceil(q/64)},programUniforms:[{type:12,data:q},...xt(P,x)]})}},Lo=(s,i)=>{let l=[];return s[1].dims[0]>0&&s[1].getBigInt64Array().forEach(f=>l.push(Number(f))),Gt({axes:l,keepDims:i.keepDims,noopWithEmptyAxes:i.noopWithEmptyAxes})},as=(s,i,l,f)=>{let p=s.inputs,g=p.length===1?l:Lo(p,l);s.compute(Fi(i,{hint:g.cacheKey,inputDependencies:["rank"]},[p[0]],g.noopWithEmptyAxes&&g.axes.length===0?Ri:f,g.axes,p[0].dataType,g.keepDims,g.noopWithEmptyAxes),{inputs:[0]})},Ro=(s,i)=>{ss(s.inputs),as(s,"ReduceLogSum",i,(l,f)=>[`var value = ${f.type.storage}(0);`,"",`value += ${l.getByIndices("input_indices")};`,"value = log(value);"])},fc=(s,i)=>{ss(s.inputs),as(s,"ReduceL1",i,(l,f)=>[`var value = ${f.type.storage}(0);`,"",`value += abs(${l.getByIndices("input_indices")});`,""])},pc=(s,i)=>{ss(s.inputs),as(s,"ReduceL2",i,(l,f)=>[`var t = ${f.type.value}(0); var value = ${f.type.value}(0);`,"",`t = ${l.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},Fo=(s,i)=>{ss(s.inputs),as(s,"ReduceLogSumExp",i,(l,f)=>[`var value = ${f.type.storage}(0);`,"",`value += exp(${l.getByIndices("input_indices")});`,"value = log(value);"])},mc=(s,i)=>{ss(s.inputs),as(s,"ReduceMax",i,(l,f,p)=>{let g=[];for(let m=0;m=0||p.length===0)&&g.push(l.indicesSet("input_indices",m,0));return[`${g.join(` `)}`,`var value = ${l.getByIndices("input_indices")};`,`value = max(value, ${l.getByIndices("input_indices")});`,""]})},_c=(s,i)=>{ss(s.inputs),as(s,"ReduceMean",i,(l,f,p)=>{let g=1;for(let m=0;m=0||p.length===0)&&(g*=s.inputs[0].dims[m]);return["var sum = f32(0);","",`sum += f32(${l.getByIndices("input_indices")});`,`let value = ${f.type.value}(sum / ${g});`]})},No=(s,i)=>{ss(s.inputs),as(s,"ReduceMin",i,(l,f,p)=>{let g=[];for(let m=0;m=0||p.length===0)&&g.push(`input_indices[${m}] = 0;`);return[`${g.join(` `)}`,`var value = ${l.getByIndices("input_indices")};`,`value = min(value, ${l.getByIndices("input_indices")});`,""]})},gc=(s,i)=>{ss(s.inputs),as(s,"ReduceProd",i,(l,f)=>[`var value = ${f.type.storage}(1);`,"",`value *= ${l.getByIndices("input_indices")};`,""])},bc=(s,i)=>{ss(s.inputs),as(s,"ReduceSum",i,(l,f)=>[`var value = ${f.type.storage}(0);`,"",`value += ${l.getByIndices("input_indices")};`,""])},Do=(s,i)=>{ss(s.inputs),as(s,"ReduceSumSquare",i,(l,f)=>[`var t = ${f.type.value}(0); var value = ${f.type.value}(0);`,"",`t = ${l.getByIndices("input_indices")}; value += t * t;`,""])},is=(s,i,l)=>{if(i.length===0)return l;let f=1,p=1;for(let g=0;g1024},yc=(s,i)=>{is(s.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?_c(s,i):la(s,i)},Bo=(s,i)=>{is(s.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?fc(s,i):oc(s,i)},wc=(s,i)=>{is(s.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?pc(s,i):Bp(s,i)},vc=(s,i)=>{is(s.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?Fo(s,i):uc(s,i)},jo=(s,i)=>{is(s.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?mc(s,i):jp(s,i)},Ec=(s,i)=>{is(s.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?No(s,i):lc(s,i)},Tc=(s,i)=>{is(s.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?gc(s,i):Oo(s,i)},zo=(s,i)=>{is(s.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?bc(s,i):cc(s,i)},xc=(s,i)=>{is(s.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?Do(s,i):dc(s,i)},Mc=(s,i)=>{is(s.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?Ro(s,i):hc(s,i)}}),Uo,Pc,Vo,Wo,Up=c(()=>{Wt(),mr(),Ni(),Uo=s=>{if(!s||s.length===0||s.length>2)throw new Error("ArgMinMaxOp op requires 1 or 2 inputs.");if(s[0].dataType!==1)throw new Error("Invalid input type.")},Pc=(s,i)=>{Uo(s.inputs);let l=(f,p,g)=>{let m=[];for(let v=0;v=0||g.length===0)&&m.push(`input_indices[${v}] = 0;`);return[`${m.join(` `)}`,`var value = ${f.getByIndices("input_indices")}; var best_index : i32 = 0;`,`if (${f.getByIndices("input_indices")} ${i.selectLastIndex>0?"<=":"<"} value) { value = ${f.getByIndices("input_indices")}; best_index = i32(last_index); }`,"",p.setByOffset("global_idx","best_index")]};s.compute(Fi("ArgMin",{hint:i.cacheKey,inputDependencies:["rank"]},[s.inputs[0]],l,[i.axis],7,i.keepDims),{inputs:[0]})},Vo=(s,i)=>{Uo(s.inputs);let l=(f,p,g)=>{let m=[];for(let v=0;v=0||g.length===0)&&m.push(`input_indices[${v}] = 0;`);return[`${m.join(` `)}`,`var value = ${f.getByIndices("input_indices")}; var best_index : i32 = 0;`,`if (${f.getByIndices("input_indices")} ${i.selectLastIndex>0?">=":">"} value) { value = ${f.getByIndices("input_indices")}; best_index = i32(last_index); }`,"",p.setByOffset("global_idx","best_index")]};s.compute(Fi("argMax",{hint:i.cacheKey,inputDependencies:["rank"]},[s.inputs[0]],l,[i.axis],7,i.keepDims),{inputs:[0]})},Wo=s=>Gt(s)}),Go,Di,Cc,Ho,Sc,ti,Ko,Ac,qo=c(()=>{Wt(),jt(),fe(),or(),Go=(s,i)=>{let l=s[0],f=s[1],p=s[2],g=s[3],m=s[4],v=s[5];if(m&&v)throw new Error("Attention cannot have both past and attention_bias");if(l.dims.length!==3)throw new Error('Input "input" must have 3 dimensions');let x=l.dims[0],P=l.dims[1],D=l.dims[2];if(p.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimensions');if(f.dims.length!==2)throw new Error('Input "weights" is expected to have 2 dimensions');if(f.dims[0]!==D)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(p.dims[0]!==f.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let R=p.dims[0]/3,E=R,K=E;if(i.qkvHiddenSizes.length>0){if(i.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let ye of i.qkvHiddenSizes)if(ye%i.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");R=i.qkvHiddenSizes[0],E=i.qkvHiddenSizes[1],K=i.qkvHiddenSizes[2]}let q=P;if(R!==E)throw new Error("qkv_hidden_sizes first element should be same as the second");if(p.dims[0]!==R+E+K)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let Y=0;if(m){if(E!==K)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(m.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(m.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(m.dims[1]!==x)throw new Error('Input "past" second dimension must be batch_size');if(m.dims[2]!==i.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(m.dims[4]!==E/i.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');i.pastPresentShareBuffer||(Y=m.dims[3])}let ne=q+Y,se=-1,te=0;if(g)throw new Error("Mask not supported");if(m)throw new Error("past is not supported");if(v){if(v.dims.length!==4)throw new Error('Input "attention_bias" must have 4 dimensions');if(v.dims[0]!==x||v.dims[1]!==i.numHeads||v.dims[2]!==P||v.dims[3]!==ne)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:x,sequenceLength:P,pastSequenceLength:Y,kvSequenceLength:q,totalSequenceLength:ne,maxSequenceLength:se,inputHiddenSize:D,hiddenSize:R,vHiddenSize:K,headSize:Math.floor(R/i.numHeads),vHeadSize:Math.floor(K/i.numHeads),numHeads:i.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:i.maskFilterValue,maskType:te,scale:i.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},Di=(s,i,l)=>i&&s?` let total_sequence_length_input = u32(${i.getByOffset("0")}); let present_sequence_length = max(total_sequence_length_input, uniforms.past_sequence_length); let is_subsequent_prompt: bool = sequence_length > 1 && sequence_length != total_sequence_length_input; let is_first_prompt: bool = is_subsequent_prompt == false && sequence_length == total_sequence_length_input; total_sequence_length = u32(${s==null?void 0:s.getByOffset("batchIdx")}) + 1; var past_sequence_length: u32 = 0; if (is_first_prompt == false) { past_sequence_length = total_sequence_length - sequence_length; } `:` ${l?"let past_sequence_length = uniforms.past_sequence_length":""}; let present_sequence_length = total_sequence_length; `,Cc=(s,i,l,f,p,g,m,v)=>{let x=sr(m?1:g),P=64,D=g/x;D{let te=Dt("x",s.dataType,s.dims,x),ye=[te],be=m?Qe("seq_lens",m.dataType,m.dims):void 0;be&&ye.push(be);let Ce=v?Qe("total_sequence_length_input",v.dataType,v.dims):void 0;Ce&&ye.push(Ce);let Be=Qr(s.dataType),je=[{name:"batch_size",type:"u32"},{name:"num_heads",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"sequence_length",type:"u32"},{name:"total_sequence_length",type:"u32"},{name:"elements_per_thread",type:"u32"}];return` var thread_max: array; var thread_sum: array; ${se.registerUniforms(je).declareVariables(...ye)} ${se.mainStart([P,1,1])} let batchIdx = workgroup_id.z / uniforms.num_heads; let headIdx = workgroup_id.z % uniforms.num_heads; let sequence_length = uniforms.sequence_length; var total_sequence_length = uniforms.total_sequence_length; ${Di(be,Ce,!1)} let local_offset = local_idx * uniforms.elements_per_thread; let offset = (global_idx / ${P}) * uniforms.total_sequence_length + local_offset; let seq_causal_length = ${m?"u32(past_sequence_length + workgroup_id.y + 1)":"total_sequence_length"}; var thread_max_vector = ${q}(-3.402823e+38f); for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { thread_max_vector = max(${q}(x[offset + i]), thread_max_vector); } thread_max[local_idx] = ${(()=>{switch(x){case 1:return"thread_max_vector";case 2:return"max(thread_max_vector.x, thread_max_vector.y)";case 4:return"max(max(thread_max_vector.x, thread_max_vector.y), max(thread_max_vector.z, thread_max_vector.w))";default:throw new Error(`Unsupported components: ${x}`)}})()}; workgroupBarrier(); var max_value = f32(-3.402823e+38f); for (var i = 0u; i < ${P}; i++) { max_value = max(thread_max[i], max_value); } var sum_vector = ${q}(0); for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { sum_vector += exp(${q}(x[offset + i]) - max_value); } thread_sum[local_idx] = ${(()=>{switch(x){case 1:return"sum_vector";case 2:return"sum_vector.x + sum_vector.y";case 4:return"sum_vector.x + sum_vector.y + sum_vector.z + sum_vector.w";default:throw new Error(`Unsupported components: ${x}`)}})()}; workgroupBarrier(); var sum: f32 = 0; for (var i = 0u; i < ${P}; i++) { sum += thread_sum[i]; } if (sum == 0) { for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { x[offset + i] = ${te.type.value}(${Be}(1.0) / ${Be}(seq_causal_length)); } } else { for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { var f32input = ${q}(x[offset + i]); x[offset + i] = ${te.type.value}(exp(f32input - max_value) / sum); } } ${m?` for (var total_seq_id: u32 = seq_causal_length; total_seq_id + local_offset < uniforms.total_sequence_length; total_seq_id++) { x[offset + total_seq_id] = ${te.type.value}(${Be}(0)); }`:""}; }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${P};${K};${x}`,inputDependencies:Y},getShaderSource:ne,getRunData:()=>({outputs:[],dispatchGroup:{x:Math.ceil(g/P),y:p,z:i*l},programUniforms:E})}},Ho=(s,i,l,f,p,g,m,v,x)=>{let P=m+g.kvSequenceLength,D=[g.batchSize,g.numHeads,g.sequenceLength,P],R=s>1&&f,E=g.kvNumHeads?g.kvNumHeads:g.numHeads,K=R?[g.batchSize,E,P,g.headSize]:void 0,q=g.nReps?g.nReps:1,Y=g.scale===0?1/Math.sqrt(g.headSize):g.scale,ne=sr(g.headSize),se=g.headSize/ne,te=12,ye={x:Math.ceil(P/te),y:Math.ceil(g.sequenceLength/te),z:g.batchSize*g.numHeads},be=[{type:12,data:g.sequenceLength},{type:12,data:se},{type:12,data:P},{type:12,data:g.numHeads},{type:12,data:g.headSize},{type:1,data:Y},{type:12,data:m},{type:12,data:g.kvSequenceLength},{type:12,data:q}],Ce=R&&f&&ze.size(f.dims)>0,Be=["type","type"];Ce&&Be.push("type"),p&&Be.push("type"),v&&Be.push("type"),x&&Be.push("type");let je=[{dims:D,dataType:i.dataType,gpuDataType:0}];R&&je.push({dims:K,dataType:i.dataType,gpuDataType:0});let tt=lt=>{let kt=Qe("q",i.dataType,i.dims,ne),ir=Qe("key",l.dataType,l.dims,ne),cr=[kt,ir];if(Ce){let Kt=Qe("past_key",f.dataType,f.dims,ne);cr.push(Kt)}p&&cr.push(Qe("attention_bias",p.dataType,p.dims));let Pt=v?Qe("seq_lens",v.dataType,v.dims):void 0;Pt&&cr.push(Pt);let pr=x?Qe("total_sequence_length_input",x.dataType,x.dims):void 0;pr&&cr.push(pr);let Rt=Dt("output",i.dataType,D),zt=[Rt];R&&zt.push(Dt("present_key",i.dataType,K,ne));let Br=Qr(1,ne),rr=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"alpha",type:"f32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return` const TILE_SIZE = ${te}u; var tileQ: array<${kt.type.storage}, ${te*te}>; var tileK: array<${kt.type.storage}, ${te*te}>; ${lt.registerUniforms(rr).declareVariables(...cr,...zt)} ${lt.mainStart([te,te,1])} // x holds the N and y holds the M let headIdx = workgroup_id.z % uniforms.num_heads; let kvHeadIdx = ${q===1?"headIdx":"headIdx / uniforms.n_reps"}; let kv_num_heads = ${q===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"}; let batchIdx = workgroup_id.z / uniforms.num_heads; let m = workgroup_id.y * TILE_SIZE; let n = workgroup_id.x * TILE_SIZE; let sequence_length = uniforms.M; var total_sequence_length = uniforms.N; ${Di(Pt,pr,!0)} let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; let qOffset = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; ${Ce&&R?"let pastKeyOffset = absKvHeadIdx * uniforms.past_sequence_length * uniforms.K;":""}; let kOffset = absKvHeadIdx * uniforms.kv_sequence_length * uniforms.K; ${R?"let presentKeyOffset = absKvHeadIdx * uniforms.N * uniforms.K;":""} var value = ${Br}(0); for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { if (global_id.y < uniforms.M && w + local_id.x < uniforms.K) { tileQ[TILE_SIZE * local_id.y + local_id.x] = q[qOffset + local_id.y * uniforms.K + w + local_id.x]; } if (n + local_id.y < uniforms.N && w + local_id.x < uniforms.K) { var idx = TILE_SIZE * local_id.y + local_id.x; ${Ce&&R?` if (n + local_id.y < past_sequence_length) { tileK[idx] = past_key[pastKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; } else if (n + local_id.y - past_sequence_length < uniforms.kv_sequence_length) { tileK[idx] = key[kOffset + (n + local_id.y - past_sequence_length) * uniforms.K + w + local_id.x]; }`:` if (n + local_id.y < uniforms.kv_sequence_length) { tileK[idx] = key[kOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; }`} ${R?`if (n + local_id.y < present_sequence_length) { present_key[presentKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x] = tileK[idx]; }`:""} } workgroupBarrier(); for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) { value += ${Br}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]); } workgroupBarrier(); } if (global_id.y < uniforms.M && global_id.x < total_sequence_length) { let headOffset = workgroup_id.z * uniforms.M * uniforms.N; let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x; var sum: f32 = ${(()=>{switch(ne){case 1:return"value";case 2:return"value.x + value.y";case 4:return"value.x + value.y + value.z + value.w";default:throw new Error(`Unsupported components: ${ne}`)}})()}; output[outputIdx] = ${Rt.type.value} (sum * uniforms.alpha) + ${p?"attention_bias[outputIdx]":"0.0"}; } }`};return{name:"AttentionProbs",shaderCache:{hint:`${ne};${p!==void 0};${f!==void 0};${s}`,inputDependencies:Be},getRunData:()=>({outputs:je,dispatchGroup:ye,programUniforms:be}),getShaderSource:tt}},Sc=(s,i,l,f,p,g,m=void 0,v=void 0)=>{let x=g+p.kvSequenceLength,P=p.nReps?p.nReps:1,D=p.vHiddenSize*P,R=s>1&&f,E=p.kvNumHeads?p.kvNumHeads:p.numHeads,K=R?[p.batchSize,E,x,p.headSize]:void 0,q=[p.batchSize,p.sequenceLength,D],Y=12,ne={x:Math.ceil(p.vHeadSize/Y),y:Math.ceil(p.sequenceLength/Y),z:p.batchSize*p.numHeads},se=[{type:12,data:p.sequenceLength},{type:12,data:x},{type:12,data:p.vHeadSize},{type:12,data:p.numHeads},{type:12,data:p.headSize},{type:12,data:D},{type:12,data:g},{type:12,data:p.kvSequenceLength},{type:12,data:P}],te=R&&f&&ze.size(f.dims)>0,ye=["type","type"];te&&ye.push("type"),m&&ye.push("type"),v&&ye.push("type");let be=[{dims:q,dataType:i.dataType,gpuDataType:0}];R&&be.push({dims:K,dataType:i.dataType,gpuDataType:0});let Ce=Be=>{let je=Qe("probs",i.dataType,i.dims),tt=Qe("v",l.dataType,l.dims),lt=[je,tt];te&<.push(Qe("past_value",f.dataType,f.dims));let kt=m?Qe("seq_lens",m.dataType,m.dims):void 0;m&<.push(kt);let ir=v?Qe("total_sequence_length_input",v.dataType,v.dims):void 0;v&<.push(ir);let cr=[Dt("output",i.dataType,q)];R&&cr.push(Dt("present_value",i.dataType,K));let Pt=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"v_hidden_size",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return` const TILE_SIZE = ${Y}u; var tileQ: array<${je.type.value}, ${Y*Y}>; var tileV: array<${je.type.value}, ${Y*Y}>; ${Be.registerUniforms(Pt).declareVariables(...lt,...cr)} ${Be.mainStart([Y,Y,1])} let headIdx = workgroup_id.z % uniforms.num_heads; let batchIdx = workgroup_id.z / uniforms.num_heads; let kvHeadIdx = ${P===1?"headIdx":"headIdx / uniforms.n_reps"}; let kv_num_heads = ${P===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"}; let m = global_id.y; let n = global_id.x; let sequence_length = uniforms.M; var total_sequence_length = uniforms.K; ${Di(kt,ir,!0)} let offsetA = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; // kvHeadIdx is relative to the batch ${te&&R?"let pastValueOffset = absKvHeadIdx * uniforms.N * uniforms.past_sequence_length + n;":""}; let vOffset = absKvHeadIdx * uniforms.N * uniforms.kv_sequence_length + n; ${R?"let presentValueOffset = absKvHeadIdx * uniforms.N * uniforms.K + n;":""} var value = ${je.type.storage}(0); for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { if (m < uniforms.M && w + local_id.x < uniforms.K) { tileQ[TILE_SIZE * local_id.y + local_id.x] = probs[offsetA + w + local_id.x]; } if (n < uniforms.N && w + local_id.y < uniforms.K) { var idx = TILE_SIZE * local_id.y + local_id.x; ${te&&R?` if (w + local_id.y < past_sequence_length) { tileV[idx] = past_value[pastValueOffset + (w + local_id.y) * uniforms.N]; } else if (w + local_id.y - past_sequence_length < uniforms.kv_sequence_length) { tileV[idx] = v[vOffset + (w + local_id.y - past_sequence_length) * uniforms.N]; } `:` if (w + local_id.y < uniforms.kv_sequence_length) { tileV[idx] = v[vOffset + (w + local_id.y) * uniforms.N]; }`} ${R?` if (w + local_id.y < present_sequence_length) { present_value[presentValueOffset + (w + local_id.y) * uniforms.N] = tileV[idx]; }`:""} } workgroupBarrier(); for (var k: u32 = 0u; k < TILE_SIZE && w+k < total_sequence_length; k++) { value += tileQ[TILE_SIZE * local_id.y + k] * tileV[TILE_SIZE * k + local_id.x]; } workgroupBarrier(); } // we need to transpose output from BNSH_v to BSND_v if (m < uniforms.M && n < uniforms.N) { let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size + headIdx * uniforms.N + n; output[outputIdx] = value; } }`};return{name:"AttentionScore",shaderCache:{hint:`${f!==void 0};${s}`,inputDependencies:ye},getRunData:()=>({outputs:be,dispatchGroup:ne,programUniforms:se}),getShaderSource:Ce}},ti=(s,i,l,f,p,g,m,v,x,P,D=void 0,R=void 0)=>{let E=Math.min(s.outputCount,1+(m?1:0)+(v?1:0)),K=E>1?P.pastSequenceLength:0,q=K+P.kvSequenceLength,Y=x&&ze.size(x.dims)>0?x:void 0,ne=[i,l];E>1&&m&&ze.size(m.dims)>0&&ne.push(m),Y&&ne.push(Y),D&&ne.push(D),R&&ne.push(R);let se=s.compute(Ho(E,i,l,m,Y,P,K,D,R),{inputs:ne,outputs:E>1?[-1,1]:[-1]})[0];s.compute(Cc(se,P.batchSize,P.numHeads,K,P.sequenceLength,q,D,R),{inputs:D&&R?[se,D,R]:[se],outputs:[]});let te=[se,f];E>1&&v&&ze.size(v.dims)>0&&te.push(v),D&&te.push(D),R&&te.push(R),s.compute(Sc(E,se,f,v,P,K,D,R),{inputs:te,outputs:E>1?[0,2]:[0]})},Ko=(s,i)=>{let l=[i.batchSize,i.numHeads,i.sequenceLength,i.headSize],f=i.sequenceLength,p=i.inputHiddenSize,g=i.headSize,m=12,v={x:Math.ceil(i.headSize/m),y:Math.ceil(i.sequenceLength/m),z:i.batchSize*i.numHeads},x=[s.inputs[0],s.inputs[1],s.inputs[2]],P=[{type:12,data:f},{type:12,data:p},{type:12,data:g},{type:12,data:i.numHeads},{type:12,data:i.headSize},{type:12,data:i.hiddenSize},{type:12,data:i.hiddenSize+i.hiddenSize+i.vHiddenSize}],D=R=>{let E=Dt("output_q",x[0].dataType,l),K=Dt("output_k",x[0].dataType,l),q=Dt("output_v",x[0].dataType,l),Y=Qe("input",x[0].dataType,x[0].dims),ne=Qe("weight",x[1].dataType,x[1].dims),se=Qe("bias",x[2].dataType,x[2].dims),te=Y.type.storage,ye=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"hidden_size",type:"u32"},{name:"ldb",type:"u32"}];return` const TILE_SIZE = ${m}u; var tileInput: array<${te}, ${m*m}>; var tileWeightQ: array<${te}, ${m*m}>; var tileWeightK: array<${te}, ${m*m}>; var tileWeightV: array<${te}, ${m*m}>; ${R.registerUniforms(ye).declareVariables(Y,ne,se,E,K,q)} ${R.mainStart([m,m,1])} let batchIndex = workgroup_id.z / uniforms.num_heads; let headNumber = workgroup_id.z % uniforms.num_heads; let m = global_id.y; let n = global_id.x; let inputOffset = batchIndex * (uniforms.M * uniforms.K) + m * uniforms.K; let biasOffsetQ = headNumber * uniforms.head_size; let biasOffsetK = uniforms.hidden_size + biasOffsetQ; let biasOffsetV = uniforms.hidden_size + biasOffsetK; var valueQ = ${te}(0); var valueK = ${te}(0); var valueV = ${te}(0); for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { if (m < uniforms.M && w + local_id.x < uniforms.K) { tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x]; } if (n < uniforms.N && w + local_id.y < uniforms.K) { let offset = n + (w + local_id.y) * uniforms.ldb; tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset]; tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset]; tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset]; } workgroupBarrier(); for (var k: u32 = 0u; k({outputs:[{dims:l,dataType:s.inputs[0].dataType,gpuDataType:0},{dims:l,dataType:s.inputs[0].dataType,gpuDataType:0},{dims:l,dataType:s.inputs[0].dataType,gpuDataType:0}],dispatchGroup:v,programUniforms:P}),getShaderSource:D},{inputs:x,outputs:[-1,-1,-1]})},Ac=(s,i)=>{let l=Go(s.inputs,i),[f,p,g]=Ko(s,l);return ti(s,f,p,g,s.inputs[4],void 0,void 0,void 0,s.inputs[5],l)}}),Zo,kc,Ic,Yo,Vp=c(()=>{Ze(),Wt(),jt(),mr(),or(),Zo=(s,i)=>{if(!s||s.length!==5)throw new Error("BatchNormalization requires 5 inputs");let l=(f,p,g)=>{let m=p.length;if(m!==f.length)throw new Error(`${g}: num dimensions != ${m}`);p.forEach((v,x)=>{if(v!==f[x])throw new Error(`${g}: dim[${x}] do not match`)})};if(s[0].dims.length>1){let f=i.format==="NHWC"?i.spatial?s[0].dims.slice(-1):s[0].dims.slice(-1).concat(s[0].dims.slice(1,s[0].dims.length-1)):s[0].dims.slice(1,i.spatial?2:void 0);l(s[1].dims,f,"Invalid input scale"),l(s[2].dims,f,"Invalid input B"),l(s[3].dims,f,"Invalid input mean"),l(s[4].dims,f,"Invalid input var")}else l(s[1].dims,[1],"Invalid input scale"),l(s[2].dims,[1],"Invalid input B"),l(s[3].dims,[1],"Invalid input mean"),l(s[4].dims,[1],"Invalid input var")},kc=(s,i)=>{let{epsilon:l,spatial:f,format:p}=i,g=s[0].dims,m=f?sr(g[g.length-1]):1,v=p==="NHWC"&&g.length>1?m:1,x=ze.size(g)/m,P=f,D=P?g.length:g,R=Qe("x",s[0].dataType,s[0].dims,m),E=Qe("scale",s[1].dataType,s[1].dims,v),K=Qe("bias",s[2].dataType,s[2].dims,v),q=Qe("inputMean",s[3].dataType,s[3].dims,v),Y=Qe("inputVar",s[4].dataType,s[4].dims,v),ne=Dt("y",s[0].dataType,D,m),se=()=>{let ye="";if(f)ye=`let cOffset = ${g.length===1?"0u":p==="NHWC"?`outputIndices[${g.length-1}] / ${m}`:"outputIndices[1]"};`;else if(p==="NCHW")ye=` ${ne.indicesSet("outputIndices","0","0")} let cOffset = ${ne.indicesToOffset("outputIndices")};`;else{ye=`var cIndices = ${E.type.indices}(0); cIndices[0] = outputIndices[${g.length-1}];`;for(let be=1;be` const epsilon = ${l}; ${ye.registerUniform("outputSize","u32").declareVariables(R,E,K,q,Y,ne)} ${ye.mainStart()} ${ye.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var outputIndices = ${ne.offsetToIndices(`global_idx * ${m}`)}; ${se()} let scale = ${E.getByOffset("cOffset")}; let bias = ${K.getByOffset("cOffset")}; let inputMean = ${q.getByOffset("cOffset")}; let inputVar = ${Y.getByOffset("cOffset")}; let x = ${R.getByOffset("global_idx")}; let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; ${ne.setByOffset("global_idx","value")} }`;return{name:"BatchNormalization",shaderCache:{hint:`${i.epsilon}_${i.format}_${f}_${m}`,inputDependencies:P?["rank","type","type","type","type"]:void 0},getShaderSource:te,getRunData:()=>({outputs:[{dims:s[0].dims,dataType:s[0].dataType}],dispatchGroup:{x:Math.ceil(x/64)},programUniforms:P?[{type:12,data:x},...xt(g)]:[{type:12,data:x}]})}},Ic=s=>Gt(s),Yo=(s,i)=>{let{inputs:l,outputCount:f}=s,p=Ic({...i,outputCount:f});if(j.webgpu.validateInputContent&&Zo(l,p),i.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");s.compute(kc(l,p))}}),$c,Xo,Oc,Wp=c(()=>{jt(),or(),$c=s=>{if(s[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![320,640,1280].includes(s[0].dims[2]))throw new Error("number of channels should be 320, 640 or 1280");if(s[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(s[0].dims[2]!==s[1].dims[0])throw new Error("last dimension of input and bias are not the same")},Xo=s=>{let i=s[0].dims,l=s[0].dims[2],f=ze.size(i)/4,p=s[0].dataType,g=Qe("input",p,i,4),m=Qe("bias",p,[l],4),v=Qe("residual",p,i,4),x=Dt("output",p,i,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:i,dataType:s[0].dataType}],dispatchGroup:{x:Math.ceil(f/64)}}),getShaderSource:P=>` const channels = ${l}u / 4; ${P.declareVariables(g,m,v,x)} ${P.mainStart()} ${P.guardAgainstOutOfBoundsWorkgroupSizes(f)} let value = ${g.getByOffset("global_idx")} + ${m.getByOffset("global_idx % channels")} + ${v.getByOffset("global_idx")}; ${x.setByOffset("global_idx","value")} }`}},Oc=s=>{$c(s.inputs),s.compute(Xo(s.inputs))}}),Qo,Cr,Lc,Jo,Rc,Fc,eu,Nc,Dc,tu,Bc,jc,zc,Uc,ru,Vc,ri,nu,Bi,Wc,su,Gc,Hc,au,Kc,qc,iu,Zc,Yc,ou,Xc,Qc,uu,Jc,ed,lu,td,ji,cu,rd,nd,sd,du,ad,id,hu=c(()=>{Wt(),jt(),mr(),or(),Qo=(s,i,l,f,p,g,m)=>{let v=Math.ceil(i/4),x="";typeof p=="string"?x=`${p}(a)`:x=p("a");let P=Qe("inputData",l,[v],4),D=Dt("outputData",f,[v],4),R=[{name:"vec_size",type:"u32"}];return m&&R.push(...m),` ${s.registerUniforms(R).declareVariables(P,D)} ${g??""} ${s.mainStart()} ${s.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} let a = ${P.getByOffset("global_idx")}; ${D.setByOffset("global_idx",x)} }`},Cr=(s,i,l,f,p,g=s.dataType,m,v)=>{let x=[{type:12,data:Math.ceil(ze.size(s.dims)/4)}];return m&&x.push(...m),{name:i,shaderCache:{hint:p,inputDependencies:["type"]},getShaderSource:P=>Qo(P,ze.size(s.dims),s.dataType,g,l,f,v),getRunData:P=>({outputs:[{dims:s.dims,dataType:g}],dispatchGroup:{x:Math.ceil(ze.size(P[0].dims)/64/4)},programUniforms:x})}},Lc=s=>{s.compute(Cr(s.inputs[0],"Abs","abs"))},Jo=s=>{s.compute(Cr(s.inputs[0],"Acos","acos"))},Rc=s=>{s.compute(Cr(s.inputs[0],"Acosh","acosh"))},Fc=s=>{s.compute(Cr(s.inputs[0],"Asin","asin"))},eu=s=>{s.compute(Cr(s.inputs[0],"Asinh","asinh"))},Nc=s=>{s.compute(Cr(s.inputs[0],"Atan","atan"))},Dc=s=>{s.compute(Cr(s.inputs[0],"Atanh","atanh"))},tu=s=>Gt(s),Bc=(s,i)=>{let l;switch(i.to){case 10:l="vec4";break;case 1:l="vec4";break;case 12:l="vec4";break;case 6:l="vec4";break;case 9:l="vec4";break;default:throw new RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${i.to}`)}s.compute(Cr(s.inputs[0],"Cast",l,void 0,i.cacheKey,i.to))},jc=s=>{let i,l,f=s.length>=2&&s[1].data!==0,p=s.length>=3&&s[2].data!==0;switch(s[0].dataType){case 1:i=f?s[1].getFloat32Array()[0]:-34028234663852886e22,l=p?s[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:i=f?s[1].getUint16Array()[0]:64511,l=p?s[2].getUint16Array()[0]:31743;break;default:throw new Error("Unsupport data type")}return Gt({min:i,max:l})},zc=(s,i)=>{let l=i||jc(s.inputs),f=Qr(s.inputs[0].dataType);s.compute(Cr(s.inputs[0],"Clip",p=>`clamp(${p}, vec4<${f}>(uniforms.min), vec4<${f}>(uniforms.max))`,void 0,l.cacheKey,void 0,[{type:s.inputs[0].dataType,data:l.min},{type:s.inputs[0].dataType,data:l.max}],[{name:"min",type:f},{name:"max",type:f}]),{inputs:[0]})},Uc=s=>{s.compute(Cr(s.inputs[0],"Ceil","ceil"))},ru=s=>{s.compute(Cr(s.inputs[0],"Cos","cos"))},Vc=s=>{s.compute(Cr(s.inputs[0],"Cosh","cosh"))},ri=s=>Gt(s),nu=(s,i)=>{let l=Qr(s.inputs[0].dataType);s.compute(Cr(s.inputs[0],"Elu",f=>`elu_vf32(${f})`,` const elu_alpha_ = ${l}(${i.alpha}); fn elu_f32(a: ${l}) -> ${l} { return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0); } fn elu_vf32(v: vec4<${l}>) -> vec4<${l}> { return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w)); }`,i.cacheKey))},Bi=(s="f32")=>` const r0: ${s} = 0.3275911; const r1: ${s} = 0.254829592; const r2: ${s} = -0.284496736; const r3: ${s} = 1.421413741; const r4: ${s} = -1.453152027; const r5: ${s} = 1.061405429; fn erf_vf32(v: vec4<${s}>) -> vec4<${s}> { let absv = abs(v); let x = 1.0 / (1.0 + r0 * absv); return sign(v) * (1.0 - ((((r5 * x + r4) * x + r3) * x + r2) * x + r1) * x * exp(-absv * absv)); }`,Wc=s=>{let i=Qr(s.inputs[0].dataType);s.compute(Cr(s.inputs[0],"Erf",l=>`erf_vf32(${l})`,Bi(i)))},su=s=>{s.compute(Cr(s.inputs[0],"Exp","exp"))},Gc=s=>{s.compute(Cr(s.inputs[0],"Floor","floor"))},Hc=s=>{let i=Qr(s.inputs[0].dataType);s.compute(Cr(s.inputs[0],"Gelu",l=>`0.5 * ${l} * (1.0 + erf_vf32(${l} * 0.7071067811865475))`,Bi(i)))},au=(s,i)=>{let l=Qr(s.inputs[0].dataType);s.compute(Cr(s.inputs[0],"LeakyRelu",f=>`select(leaky_relu_alpha_ * ${f}, ${f}, ${f} >= vec4<${l}>(0.0))`,`const leaky_relu_alpha_ = ${l}(${i.alpha});`,i.cacheKey))},Kc=s=>{s.compute(Cr(s.inputs[0],"Not",i=>`!${i}`))},qc=s=>{s.compute(Cr(s.inputs[0],"Neg",i=>`-${i}`))},iu=s=>{s.compute(Cr(s.inputs[0],"Reciprocal",i=>`1.0/${i}`))},Zc=s=>{let i=Qr(s.inputs[0].dataType);s.compute(Cr(s.inputs[0],"Relu",l=>`select(vec4<${i}>(0.0), ${l}, ${l} > vec4<${i}>(0.0))`))},Yc=s=>{s.compute(Cr(s.inputs[0],"Sigmoid",i=>`(1.0 / (1.0 + exp(-${i})))`))},ou=s=>Gt(s),Xc=(s,i)=>{let l=Qr(s.inputs[0].dataType);s.compute(Cr(s.inputs[0],"HardSigmoid",f=>`max(vec4<${l}>(0.0), min(vec4<${l}>(1.0), ${i.alpha} * ${f} + vec4<${l}>(${i.beta})))`,void 0,i.cacheKey))},Qc=s=>{s.compute(Cr(s.inputs[0],"Sin","sin"))},uu=s=>{s.compute(Cr(s.inputs[0],"Sinh","sinh"))},Jc=s=>{s.compute(Cr(s.inputs[0],"Sqrt","sqrt"))},ed=s=>{s.compute(Cr(s.inputs[0],"Tan","tan"))},lu=s=>`sign(${s}) * (1 - exp(-2 * abs(${s}))) / (1 + exp(-2 * abs(${s})))`,td=s=>{s.compute(Cr(s.inputs[0],"Tanh",lu))},ji=(s="f32")=>` const fast_gelu_a: ${s} = 0.5; const fast_gelu_b: ${s} = 0.7978845608028654; const fast_gelu_c: ${s} = 0.035677408136300125; fn tanh_v(v: vec4<${s}>) -> vec4<${s}> { return ${lu("v")}; } `,cu=s=>`(fast_gelu_a + fast_gelu_a * tanh_v(${s} * (fast_gelu_c * ${s} * ${s} + fast_gelu_b))) * ${s}`,rd=s=>{let i=Qr(s.inputs[0].dataType);s.compute(Cr(s.inputs[0],"FastGelu",cu,ji(i),void 0,s.inputs[0].dataType))},nd=(s,i)=>{let l=Qr(s.inputs[0].dataType);return s.compute(Cr(s.inputs[0],"ThresholdedRelu",f=>`select(vec4<${l}>(0.0), ${f}, ${f} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${l}>(${i.alpha});`,i.cacheKey)),0},sd=s=>{s.compute(Cr(s.inputs[0],"Log","log"))},du=(s,i)=>` const alpha = vec4<${s}>(${i}); const one = ${s}(1.0); const zero = ${s}(0.0); fn quick_gelu_impl(x: vec4<${s}>) -> vec4<${s}> { let v = x *alpha; var x1 : vec4<${s}>; for (var i = 0; i < 4; i = i + 1) { if (v[i] >= zero) { x1[i] = one / (one + exp(-v[i])); } else { x1[i] = one - one / (one + exp(v[i])); } } return x * x1; } `,ad=s=>`quick_gelu_impl(${s})`,id=(s,i)=>{let l=Qr(s.inputs[0].dataType);s.compute(Cr(s.inputs[0],"QuickGelu",ad,du(l,i.alpha),i.cacheKey,s.inputs[0].dataType))}}),od,fu,ud,Gp=c(()=>{jt(),or(),hu(),od=s=>{if(s[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![2560,5120,10240].includes(s[0].dims[2]))throw new Error("hidden state should be 2560, 5120 or 10240");if(s[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(s[0].dims[2]!==s[1].dims[0])throw new Error("last dimension of input and bias are not the same")},fu=s=>{let i=s[0].dims.slice();i[2]=i[2]/2;let l=Qe("input",s[0].dataType,s[0].dims,4),f=Qe("bias",s[0].dataType,[s[0].dims[2]],4),p=Dt("output",s[0].dataType,i,4),g=ze.size(i)/4,m=Ir(s[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:i,dataType:s[0].dataType}],dispatchGroup:{x:Math.ceil(g/64)}}),getShaderSource:v=>` const M_SQRT2 = sqrt(2.0); const halfChannels = ${s[0].dims[2]/4/2}u; ${v.declareVariables(l,f,p)} ${Bi(m)} ${v.mainStart()} ${v.guardAgainstOutOfBoundsWorkgroupSizes(g)} let biasIdx = global_idx % halfChannels; let batchIndex = global_idx / halfChannels; let inputOffset = biasIdx + batchIndex * halfChannels * 2; let valueLeft = input[inputOffset] + bias[biasIdx]; let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels]; let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1); ${p.setByOffset("global_idx","valueLeft * geluRight")} }`}},ud=s=>{od(s.inputs),s.compute(fu(s.inputs))}}),ld,cd,Yn,dd,hd,pu,fd,pd,mu,md,_d,_u,gd,Hp=c(()=>{Wt(),jt(),or(),ld=(s,i,l,f,p,g,m,v,x,P,D,R)=>{let E,K;typeof v=="string"?E=K=(te,ye)=>`${v}((${te}),(${ye}))`:typeof v=="function"?E=K=v:(E=v.scalar,K=v.vector);let q=Dt("outputData",D,f.length,4),Y=Qe("aData",x,i.length,4),ne=Qe("bData",P,l.length,4),se;if(p)if(g){let te=ze.size(i)===1,ye=ze.size(l)===1,be=i.length>0&&i[i.length-1]%4===0,Ce=l.length>0&&l[l.length-1]%4===0;te||ye?se=q.setByOffset("global_idx",K(te?`${Y.type.value}(${Y.getByOffset("0")}.x)`:Y.getByOffset("global_idx"),ye?`${ne.type.value}(${ne.getByOffset("0")}.x)`:ne.getByOffset("global_idx"))):se=` let outputIndices = ${q.offsetToIndices("global_idx * 4u")}; let offsetA = ${Y.broadcastedIndicesToOffset("outputIndices",q)}; let offsetB = ${ne.broadcastedIndicesToOffset("outputIndices",q)}; ${q.setByOffset("global_idx",K(m||be?Y.getByOffset("offsetA / 4u"):`${Y.type.value}(${Y.getByOffset("offsetA / 4u")}[offsetA % 4u])`,m||Ce?ne.getByOffset("offsetB / 4u"):`${ne.type.value}(${ne.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} `}else se=q.setByOffset("global_idx",K(Y.getByOffset("global_idx"),ne.getByOffset("global_idx")));else{if(!g)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let te=(ye,be,Ce="")=>{let Be=`aData[indexA${be}][componentA${be}]`,je=`bData[indexB${be}][componentB${be}]`;return` let outputIndices${be} = ${q.offsetToIndices(`global_idx * 4u + ${be}u`)}; let offsetA${be} = ${Y.broadcastedIndicesToOffset(`outputIndices${be}`,q)}; let offsetB${be} = ${ne.broadcastedIndicesToOffset(`outputIndices${be}`,q)}; let indexA${be} = offsetA${be} / 4u; let indexB${be} = offsetB${be} / 4u; let componentA${be} = offsetA${be} % 4u; let componentB${be} = offsetB${be} % 4u; ${ye}[${be}] = ${Ce}(${E(Be,je)}); `};D===9?se=` var data = vec4(0); ${te("data",0,"u32")} ${te("data",1,"u32")} ${te("data",2,"u32")} ${te("data",3,"u32")} outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:se=` ${te("outputData[global_idx]",0)} ${te("outputData[global_idx]",1)} ${te("outputData[global_idx]",2)} ${te("outputData[global_idx]",3)} `}return` ${s.registerUniform("vec_size","u32").declareVariables(Y,ne,q)} ${R??""} ${s.mainStart()} ${s.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${se} }`},cd=(s,i,l,f,p,g,m=l.dataType)=>{let v=l.dims.map(Y=>Number(Y)??1),x=f.dims.map(Y=>Number(Y)??1),P=!ze.areEqual(v,x),D=v,R=ze.size(v),E=!1,K=!1,q=[P];if(P){let Y=mn.calcShape(v,x,!1);if(!Y)throw new Error("Can't perform binary op on the given tensors");D=Y.slice(),R=ze.size(D);let ne=ze.size(v)===1,se=ze.size(x)===1,te=v.length>0&&v[v.length-1]%4===0,ye=x.length>0&&x[x.length-1]%4===0;q.push(ne),q.push(se),q.push(te),q.push(ye);let be=1;for(let Ce=1;CeY.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:Y=>ld(Y,v,x,D,E,P,K,p,l.dataType,f.dataType,m,g),getRunData:()=>({outputs:[{dims:D,dataType:m}],dispatchGroup:{x:Math.ceil(R/64/4)},programUniforms:[{type:12,data:Math.ceil(ze.size(D)/4)},...xt(v,x,D)]})}},Yn=(s,i,l,f,p,g)=>{s.compute(cd(i,p??"",s.inputs[0],s.inputs[1],l,f,g))},dd=s=>{Yn(s,"Add",(i,l)=>`${i}+${l}`)},hd=s=>{Yn(s,"Div",(i,l)=>`${i}/${l}`)},pu=s=>{Yn(s,"Equal",{scalar:(i,l)=>`u32(${i}==${l})`,vector:(i,l)=>`vec4(${i}==${l})`},void 0,void 0,9)},fd=s=>{Yn(s,"Mul",(i,l)=>`${i}*${l}`)},pd=s=>{let i=Qe("input",s.inputs[0].dataType,s.inputs[0].dims).type.value;Yn(s,"Pow",{scalar:(l,f)=>`pow_custom(${l},${f})`,vector:(l,f)=>`pow_vector_custom(${l},${f})`},` fn pow_custom(a : ${i}, b : ${i}) -> ${i} { if (b == ${i}(0.0)) { return ${i}(1.0); } else if (a < ${i}(0.0) && f32(b) != floor(f32(b))) { return ${i}(pow(f32(a), f32(b))); // NaN } return select(sign(a), ${i}(1.0), round(f32(abs(b) % ${i}(2.0))) != 1.0) * ${i}(${i==="i32"?"round":""}(pow(f32(abs(a)), f32(b)))); } fn pow_vector_custom(a : vec4<${i}>, b : vec4<${i}>) -> vec4<${i}> { // TODO: implement vectorized pow return vec4<${i}>(pow_custom(a.x, b.x), pow_custom(a.y, b.y), pow_custom(a.z, b.z), pow_custom(a.w, b.w)); } `)},mu=s=>{Yn(s,"Sub",(i,l)=>`${i}-${l}`)},md=s=>{Yn(s,"Greater",{scalar:(i,l)=>`u32(${i}>${l})`,vector:(i,l)=>`vec4(${i}>${l})`},void 0,void 0,9)},_d=s=>{Yn(s,"Less",{scalar:(i,l)=>`u32(${i}<${l})`,vector:(i,l)=>`vec4(${i}<${l})`},void 0,void 0,9)},_u=s=>{Yn(s,"GreaterOrEqual",{scalar:(i,l)=>`u32(${i}>=${l})`,vector:(i,l)=>`vec4(${i}>=${l})`},void 0,void 0,9)},gd=s=>{Yn(s,"LessOrEqual",{scalar:(i,l)=>`u32(${i}<=${l})`,vector:(i,l)=>`vec4(${i}<=${l})`},void 0,void 0,9)}}),gu,bd,yd,zi,wd,vd,Ed=c(()=>{Wt(),jt(),mr(),or(),gu=(s,i)=>{if(!s||s.length<1)throw new Error("too few inputs");let l=0,f=s[l],p=f.dataType,g=f.dims.length;s.forEach((m,v)=>{if(v!==l){if(m.dataType!==p)throw new Error("input tensors should be one type");if(m.dims.length!==g)throw new Error("input tensors should have the same shape");m.dims.forEach((x,P)=>{if(P!==i&&x!==f.dims[P])throw new Error("non concat dimensions must match")})}})},bd=(s,i)=>` fn calculateInputIndex(index: u32) -> u32 { let sizeInConcatAxis = array(${i}); for (var i: u32 = 0u; i < ${s}; i += 1u ) { if (index < sizeInConcatAxis[i]) { return i; } } return ${s}u; }`,yd=(s,i)=>{let l=s.length,f=[];for(let p=0;p{let p=ze.size(l),g=new Array(s.length),m=new Array(s.length),v=0,x=[],P=[],D=[{type:12,data:p}];for(let Y=0;Y`uniforms.sizeInConcatAxis${Y}`).join(","),q=Y=>` ${(()=>{Y.registerUniform("outputSize","u32");for(let ne=0;ne(${K}); ${E} -= sizeInConcatAxis[inputIndex - 1u]; } ${yd(m,R)} }`;return{name:"Concat",shaderCache:{hint:`${i}`,inputDependencies:x},getRunData:()=>({outputs:[{dims:l,dataType:f}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:D}),getShaderSource:q}},wd=(s,i)=>{let l=s.inputs,f=l[0].dims,p=ze.normalizeAxis(i.axis,f.length);gu(l,p);let g=f.slice();g[p]=l.reduce((v,x)=>v+(x.dims.length>p?x.dims[p]:0),0);let m=l.filter(v=>ze.size(v.dims)>0);s.compute(zi(m,p,g,l[0].dataType),{inputs:m})},vd=s=>Gt({axis:s.axis})}),Ws,ca,Gs,bu,da=c(()=>{Wt(),jt(),Ws=(s,i,l="f32")=>{switch(s.activation){case"Relu":return`value = max(value, ${i}(0.0));`;case"Sigmoid":return`value = (${i}(1.0) / (${i}(1.0) + exp(-value)));`;case"Clip":return`value = clamp(value, ${i}(${l}(uniforms.clip_min)), ${i}(${l}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${i}(0.0), min(${i}(1.0), ${l}(uniforms.alpha) * value + ${l}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${l}(uniforms.alpha) * value, value, value >= ${i}(0.0));`;case"Tanh":return`let e2x = exp(-2.0 * abs(value)); value = sign(value) * (1.0 - e2x) / (1.0 + e2x); `;case"":return"";default:throw new Error(`Unsupported activation ${s.activation}`)}},ca=(s,i)=>{s.activation==="Clip"?i.push({type:1,data:s.clipMax},{type:1,data:s.clipMin}):s.activation==="HardSigmoid"?i.push({type:1,data:s.alpha},{type:1,data:s.beta}):s.activation==="LeakyRelu"&&i.push({type:1,data:s.alpha})},Gs=(s,i)=>{s.activation==="Clip"?i.push({name:"clip_max",type:"f32"},{name:"clip_min",type:"f32"}):s.activation==="HardSigmoid"?i.push({name:"alpha",type:"f32"},{name:"beta",type:"f32"}):s.activation==="LeakyRelu"&&i.push({name:"alpha",type:"f32"})},bu=s=>{let i=(s==null?void 0:s.activation)||"";if(i==="HardSigmoid"){let[l,f]=(s==null?void 0:s.activation_params)||[.2,.5];return{activation:i,alpha:l,beta:f}}else if(i==="Clip"){let[l,f]=(s==null?void 0:s.activation_params)||[Xr,yn];return{activation:i,clipMax:f,clipMin:l}}else if(i==="LeakyRelu"){let[l]=(s==null?void 0:s.activation_params)||[.01];return{activation:i,alpha:l}}return{activation:i}}}),wn,yu,wu=c(()=>{wn=(s,i)=>{switch(s){case 1:return i;case 2:return`vec2<${i}>`;case 3:return`vec3<${i}>`;case 4:return`vec4<${i}>`;default:throw new Error(`${s}-component is not supported.`)}},yu=s=>` ${s?"value = value + getBiasByOutputCoords(coords);":""} `}),Td,Kp=c(()=>{Td=s=>` fn getIndexFromCoords4D(coords : vec4, shape : vec4) -> i32 { return dot(coords, vec4( shape.y * shape.z * shape.w, shape.z * shape.w, shape.w, 1)); } fn getOutputIndexFromCoords(coords : vec4) -> i32 { return dot(coords, vec4( i32(${s}.x), i32(${s}.y), i32(${s}.z), 1)); } `}),$a,vu,Eu=c(()=>{Wt(),jt(),or(),da(),$a=(s,i,l,f,p)=>{let g=f-l;return` ${Array.from({length:l}).map((m,v)=>` if (${Ft(i.shape,v,i.rank)} != 1) { ${i.indicesSet(s,v,Ft(p,v+g,f))} } else { ${i.indicesSet(s,v,0)} }`).join("")} `},vu=(s,i,l,f,p=!1,g)=>{let m=s[0].dims,v=s[1].dims,x=m[m.length-2],P=v[v.length-1],D=m[m.length-1],R=sr(P),E=sr(D),K=sr(x),q=ze.size(l)/R/K,Y=s.length>2,ne=f?f.slice(0,-2):l.slice(0,-2),se=[ze.size(ne),x,P],te=[{type:12,data:q},{type:12,data:x},{type:12,data:P},{type:12,data:D}];ca(i,te),te.push(...xt(ne,m,v)),Y&&te.push(...xt(s[2].dims)),te.push(...xt(se));let ye=be=>{let Ce=Co("batch_dims",s[0].dataType,ne.length),Be=Qe("a",s[0].dataType,m.length,E),je=Qe("b",s[1].dataType,v.length,R),tt=Dt("output",s[0].dataType,se.length,R),lt=Ir(tt.type.tensor),kt=Ws(i,tt.type.value,lt),ir=[Be,je],cr="";if(Y){let Rt=p?R:1;ir.push(Qe("bias",s[2].dataType,s[2].dims.length,Rt)),cr=`${p?`value += bias[col / ${Rt}];`:`value += ${tt.type.value}(bias[row + i]);`}`}let Pt=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];Gs(i,Pt);let pr=()=>{let Rt=`var a_data: ${Be.type.value};`;for(let zt=0;zt; for (var k: u32 = 0u; k < uniforms.K; k = k + ${E}) { ${pr()} } for (var i = 0u; i < ${K}u; i++) { var value = values[i]; ${cr} ${kt} let cur_indices = ${tt.type.indices}(batch, row + i, col); let offset = ${tt.indicesToOffset("cur_indices")}; ${tt.setByOffset(`offset / ${R}`,"value")}; } } `};return{name:"MatMulNaive",shaderCache:{hint:`${i.activation};${R};${E};${K};${p}`,inputDependencies:Y?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:g?g(l):l,dataType:s[0].dataType}],dispatchGroup:{x:Math.ceil(q/64)},programUniforms:te}),getShaderSource:ye}}}),Tu,xd,xu,Ui,Md,Mu,Pu,Vi,Cu=c(()=>{Wt(),jt(),or(),da(),Eu(),wu(),Tu=(s,i)=>s?` mm_Asub[inputRow][inputCol] = mm_readA(batch, kStart + inputRow, globalRowStart / innerElementSize + inputCol${i?", batchIndices":""}); `:` mm_Asub[inputRow][inputCol] = mm_readA(batch, globalRow + innerRow, kStart / innerElementSize + inputCol${i?", batchIndices":""}); `,xd=(s,i)=>s?` let ACached0 = mm_Asub[k * innerElementSize][localRow]; let ACached1 = mm_Asub[k * innerElementSize + 1][localRow]; let ACached2 = mm_Asub[k * innerElementSize + 2][localRow]; ${i===3?"":"let ACached3 = mm_Asub[k * innerElementSize + 3][localRow];"} for (var i = 0; i < rowPerThread; i = i + 1) { acc[i] = BCached0 * ACached0[i] + acc[i]; acc[i] = BCached1 * ACached1[i] + acc[i]; acc[i] = BCached2 * ACached2[i] + acc[i]; ${i===3?"":"acc[i] = BCached3 * ACached3[i] + acc[i];"} }`:` for (var i = 0; i < rowPerThread; i = i + 1) { let ACached = mm_Asub[tileRow + i][k]; acc[i] = BCached0 * ACached.x + acc[i]; acc[i] = BCached1 * ACached.y + acc[i]; acc[i] = BCached2 * ACached.z + acc[i]; ${i===3?"":"acc[i] = BCached3 * ACached.w + acc[i];"} }`,xu=(s,i,l="f32",f,p=!1,g=32,m=!1,v=32)=>{let x=i[1]*s[1],P=i[0]*s[0],D=p?x:g,R=p?g:x,E=D/i[0],K=g/i[1];if(!((p&&E===4&&s[1]===4||!p&&(E===3||E===4))&&D%i[0]===0&&g%i[1]===0&&s[0]===4))throw new Error(`If transposeA ${p} is true, innerElementSize ${E} and workPerThread[1] ${s[1]} must be 4. Otherwise, innerElementSize ${E} must be 3 or 4. tileAWidth ${D} must be divisible by workgroupSize[0]${i[0]}. tileInner ${g} must be divisible by workgroupSize[1] ${i[1]}. colPerThread ${s[0]} must be 4.`);return` var mm_Asub: array, ${D/E}>, ${R}>; var mm_Bsub: array, ${P/s[0]}>, ${g}>; const rowPerThread = ${s[1]}; const colPerThread = ${s[0]}; const innerElementSize = ${E}; const tileInner = ${g}; @compute @workgroup_size(${i[0]}, ${i[1]}, ${i[2]}) fn main(@builtin(local_invocation_id) localId : vec3, @builtin(global_invocation_id) globalId : vec3, @builtin(workgroup_id) workgroupId : vec3) { let localRow = i32(localId.y); let tileRow = localRow * rowPerThread; let tileCol = i32(localId.x); let globalRow =i32(globalId.y) * rowPerThread; let globalCol = i32(globalId.x); let batch = ${m?"0":"i32(globalId.z)"}; ${f?`let batchIndices = ${f.offsetToIndices("u32(batch)")};`:""} let globalRowStart = i32(workgroupId.y) * ${x}; let num_tiles = ${m?`${Math.ceil(v/g)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; var kStart = ${m?`i32(globalId.z) * ${v}`:"0"}; var acc: array, rowPerThread>; // Loop over shared dimension. let tileRowB = localRow * ${K}; for (var t = 0; t < num_tiles; t = t + 1) { // Load one tile of A into local memory. for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { let inputRow = tileRow + innerRow; let inputCol = tileCol; ${Tu(p,f)} } // Load one tile of B into local memory. for (var innerRow = 0; innerRow < ${K}; innerRow = innerRow + 1) { let inputRow = tileRowB + innerRow; let inputCol = tileCol; mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${f?", batchIndices":""}); } kStart = kStart + tileInner; workgroupBarrier(); // Compute acc values for a single thread. for (var k = 0; k < tileInner / innerElementSize; k = k + 1) { let BCached0 = mm_Bsub[k * innerElementSize][tileCol]; let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol]; let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol]; ${E===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} ${xd(p,E)} } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); } }`},Ui=(s,i)=>s?` mm_Asub[inputRow][inputCol] = mm_readA(batch, kStart + inputRow, globalRowStart + inputCol${i?", batchIndices":""}); `:` mm_Asub[inputRow][inputCol] = mm_readA(batch, globalRowStart + inputRow, kStart + inputCol${i?", batchIndices":""}); `,Md=s=>s?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",Mu=(s,i,l="f32",f,p=!1,g=32,m=!1,v=32,x=!1)=>{let P=s[1]*i[1],D=s[0]*i[0],R=p?P:g,E=p?g:P;if(!(E%i[1]===0&&R%i[0]===0&&g%i[1]===0))throw new Error(`tileAHight ${E} must be divisible by workgroupSize[1]${i[1]}, tileAWidth ${R} must be divisible by workgroupSize[0]${i[0]}, tileInner ${g} must be divisible by workgroupSize[1]${i[1]}`);let K=E/i[1],q=R/i[0],Y=g/i[1],ne=x?` let localRow = i32(localId.y); let localCol = i32(localId.x); let globalRowStart = i32(workgroupId.y) * ${P}; let globalColStart = i32(workgroupId.x) * ${D}; // Loop over shared dimension. for (var t = 0; t < num_tiles; t = t + 1) { // Load one tile of A into local memory. for (var inputRow = localRow; inputRow < ${E}; inputRow = inputRow + ${i[1]}) { for (var inputCol = localCol; inputCol < ${R}; inputCol = inputCol + ${i[0]}) { ${Ui(p,f)} } } // Load one tile of B into local memory. for (var inputRow = localRow; inputRow < ${g}; inputRow = inputRow + ${i[1]}) { for (var inputCol = localCol; inputCol < ${D}; inputCol = inputCol + ${i[0]}) { mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalColStart + inputCol${f?", batchIndices":""}); } } kStart = kStart + tileInner; workgroupBarrier(); // Compute acc values for a single thread. var BCached : array<${l}, colPerThread>; for (var k = 0; k < tileInner; k = k + 1) { for (var inner = 0; inner < colPerThread; inner = inner + 1) { BCached[inner] = mm_Bsub[k][localCol + inner * ${i[0]}]; } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { let ACached = ${p?`mm_Asub[k][localRow + innerRow * ${i[1]}];`:`mm_Asub[localRow + innerRow * ${i[1]}][k];`} for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; } } } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { let gRow = globalRowStart + localRow + innerRow * ${i[1]}; for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { let gCol = globalColStart + localCol + innerCol * ${i[0]}; mm_write(batch, gRow, gCol, acc[innerRow][innerCol]); } } `:` let tileRow = i32(localId.y) * rowPerThread; let tileCol = i32(localId.x) * colPerThread; let globalRow = i32(globalId.y) * rowPerThread; let globalCol = i32(globalId.x) * colPerThread; let globalRowStart = i32(workgroupId.y) * ${P}; let tileRowA = i32(localId.y) * ${K}; let tileColA = i32(localId.x) * ${q}; let tileRowB = i32(localId.y) * ${Y}; // Loop over shared dimension. for (var t = 0; t < num_tiles; t = t + 1) { // Load one tile of A into local memory. for (var innerRow = 0; innerRow < ${K}; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < ${q}; innerCol = innerCol + 1) { let inputRow = tileRowA + innerRow; let inputCol = tileColA + innerCol; ${Ui(p,f)} } } // Load one tile of B into local memory. for (var innerRow = 0; innerRow < ${Y}; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { let inputRow = tileRowB + innerRow; let inputCol = tileCol + innerCol; mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol + innerCol${f?", batchIndices":""}); } } kStart = kStart + tileInner; workgroupBarrier(); // Compute acc values for a single thread. var BCached : array<${l}, colPerThread>; for (var k = 0; k < tileInner; k = k + 1) { for (var inner = 0; inner < colPerThread; inner = inner + 1) { BCached[inner] = mm_Bsub[k][tileCol + inner]; } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { ${Md(p)} for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; } } } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { mm_write(batch, globalRow + innerRow, globalCol + innerCol, acc[innerRow][innerCol]); } } `;return` var mm_Asub : array, ${E}>; var mm_Bsub : array, ${g}>; const rowPerThread = ${s[1]}; const colPerThread = ${s[0]}; const tileInner = ${g}; @compute @workgroup_size(${i[0]}, ${i[1]}, ${i[2]}) fn main(@builtin(local_invocation_id) localId : vec3, @builtin(global_invocation_id) globalId : vec3, @builtin(workgroup_id) workgroupId : vec3) { let batch = ${m?"0":"i32(globalId.z)"}; ${f?`let batchIndices = ${f.offsetToIndices("u32(batch)")};`:""} let num_tiles = ${m?`${Math.ceil(v/g)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; var kStart = ${m?`i32(globalId.z) * ${v}`:"0"}; var acc : array, rowPerThread>; ${ne} } `},Pu=(s,i,l,f,p=!1)=>{let[g,m,v,x]=f,P=Ir(f[0].type.tensor);return` fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${g.type.indices}) -> ${wn(s,P)} { var value = ${wn(s,P)}(0.0); let col = colIn * ${s}; if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) { var aIndices: ${m.type.indices}; ${$a("aIndices",m,m.rank-2,g.rank,"batchIndices")} ${m.indicesSet("aIndices",m.rank-2,"u32(row)")} ${m.indicesSet("aIndices",m.rank-1,"u32(colIn)")} value = ${m.getByIndices("aIndices")}; } return value; } fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${g.type.indices}) -> ${wn(s,P)} { var value = ${wn(s,P)}(0.0); let col = colIn * ${s}; if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) { var bIndices: ${v.type.indices}; ${$a("bIndices",v,v.rank-2,g.rank,"batchIndices")} ${v.indicesSet("bIndices",v.rank-2,"u32(row)")} ${v.indicesSet("bIndices",v.rank-1,"u32(colIn)")} value = ${v.getByIndices("bIndices")}; } return value; } fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${wn(s,P)}) { let col = colIn * ${s}; if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { var value = valueIn; let coords = vec3(batch, row, colIn); ${i?`value = value + ${p?"bias[colIn]":`${wn(s,P)}(bias[row])`};`:""} ${l} ${x.setByIndices("vec3(coords)","value")} } } `},Vi=(s,i,l,f,p=!1,g)=>{let m=s[0].dims,v=s[1].dims,x=m.slice(0,-2),P=v.slice(0,-2),D=f?f.slice(0,-2):l.slice(0,-2),R=ze.size(D),E=m[m.length-2],K=m[m.length-1],q=v[v.length-1],Y=K%4===0&&q%4===0,ne=E<=8?[4,1,1]:[4,4,1],se=[8,8,1],te=[Math.ceil(q/se[0]/ne[0]),Math.ceil(E/se[1]/ne[1]),Math.ceil(R/se[2]/ne[2])],ye=Y?4:1,be=[...x,E,K/ye],Ce=be.length,Be=[...P,K,q/ye],je=Be.length,tt=[R,E,q/ye],lt=[{type:6,data:E},{type:6,data:q},{type:6,data:K}];ca(i,lt),lt.push(...xt(D,be,Be));let kt=["rank","rank"],ir=s.length>2;ir&&(lt.push(...xt(s[2].dims)),kt.push("rank")),lt.push(...xt(tt));let cr=Pt=>{let pr=D.length,Rt=Co("batchDims",s[0].dataType,pr,1),zt=Ir(s[0].dataType),Br=Qe("a",s[0].dataType,Ce,ye),rr=Qe("b",s[1].dataType,je,ye),Kt=Dt("result",s[0].dataType,tt.length,ye),Or=[Br,rr];if(ir){let ls=p?ye:1;Or.push(Qe("bias",s[2].dataType,s[2].dims.length,ls))}let ut=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];Gs(i,ut);let It=Ir(Kt.type.tensor),Sr=Ws(i,Kt.type.value,It),ln=Pu(ye,ir,Sr,[Rt,Br,rr,Kt],p);return` ${Pt.registerUniforms(ut).registerInternalVariables(Rt).declareVariables(...Or,Kt)} ${ln} ${Y?xu(ne,se,zt,Rt):Mu(ne,se,zt,Rt)} `};return{name:"MatMul",shaderCache:{hint:`${ne};${i.activation};${Y};${p}`,inputDependencies:kt},getRunData:()=>({outputs:[{dims:g?g(l):l,dataType:s[0].dataType}],dispatchGroup:{x:te[0],y:te[1],z:te[2]},programUniforms:lt}),getShaderSource:cr}}}),Su,Pd,qp=c(()=>{Wt(),Ie(),or(),da(),wu(),Kp(),Cu(),Su=(s,i,l,f,p=!1,g,m=4,v=4,x=4,P="f32")=>{let D=lt=>{switch(lt){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${P}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${lt} is not supported.`)}},R=lt=>{switch(lt){case 1:return"return w[row * i32(uniforms.w_shape[3]) + colIn];";case 4:return"return w[row * i32(uniforms.w_shape[3]) / 4 + colIn];";default:throw new Error(`innerElementSize ${lt} is not supported.`)}},E=s?` let coord = vec4(batch, xRow, xCol, xCh); `:` let coord = vec4(batch, xCh, xRow, xCol); `,K=s?` let coords = vec4( batch, row / outWidth, row % outWidth, col); `:` let coords = vec4( batch, row, col / outWidth, col % outWidth); `,q=s?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",Y=s?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",ne=s?"row":"col",se=s?"col":"row",te=` let inChannels = i32(uniforms.w_shape[2]); let outWidth = ${s?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; let outRow = ${ne} / outWidth; let outCol = ${ne} % outWidth; let WRow = ${se} / (i32(uniforms.w_shape[1]) * inChannels); let WCol = ${se} / inChannels % i32(uniforms.w_shape[1]); let xRow = outRow * uniforms.stride[0] + uniforms.dilation[0] * WRow - uniforms.pad[0]; let xCol = outCol * uniforms.stride[1] + uniforms.dilation[1] * WCol - uniforms.pad[1]; let xCh = ${se} % inChannels; var resData = ${wn(m,P)}(0.0); // The bounds checking is always needed since we use it to pad zero for // the 'same' padding type. if (xRow >= 0 && xRow < ${q} && xCol >= 0 && xCol < ${Y}) { ${E} let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); ${D(m)} } return resData;`,ye=s?i&&f?` let col = colIn * ${m}; ${te}`:` let col = colIn * ${m}; if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { ${te} } return ${wn(m,P)}(0.0);`:f&&l?` let col = colIn * ${m}; ${te}`:` let col = colIn * ${m}; if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${te} } return ${wn(m,P)}(0.0);`,be=s?f&&l?R(v):` let col = colIn * ${v}; if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${R(v)} } return ${wn(v,P)}(0.0);`:` let col = colIn * ${v}; if (row < uniforms.dim_inner && col < uniforms.dim_a_outer) { ${R(v)} } return ${wn(v,P)}(0.0);`,Ce=wn(x,P),Be=wn(s?m:v,P),je=wn(s?v:m,P),tt=Ws(g,Ce,P);return` fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${Be} { ${s?ye:be} } fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${je} { ${s?be:ye} } fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${Ce}) { let col = colIn * ${x}; if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { var value = valueIn; let outWidth = ${s?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; ${K} ${yu(p)} ${tt} setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); } }`},Pd=(s,i,l,f,p,g,m,v,x)=>{let P=i.format==="NHWC",D=P?s[0].dims[3]:s[0].dims[1],R=l[0],E=P?l[2]:l[3],K=P?l[1]:l[2],q=P?l[3]:l[1],Y=P&&(D%4===0||D%3===0)&&q%4===0,ne=P?q:E*K,se=P?E*K:q,te=[8,8,1],ye=f<=8?[4,1,1]:[4,4,1],be=[Math.ceil(ne/te[0]/ye[0]),Math.ceil(se/te[1]/ye[1]),Math.ceil(R/te[2]/ye[2])];Tr("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${be}`);let Ce=Y?P&&D%4!==0?3:4:1,Be=te[1]*ye[1],je=te[0]*ye[0],tt=Math.max(te[0]*Ce,te[1]),lt=f%Be===0,kt=p%je===0,ir=g%tt===0,cr=Y?[Ce,4,4]:[1,1,1],Pt=[{type:6,data:f},{type:6,data:p},{type:6,data:g},{type:6,data:[i.pads[0],i.pads[1]]},{type:6,data:i.strides},{type:6,data:i.dilations}];ca(i,Pt),Pt.push(...xt(s[0].dims,s[1].dims));let pr=["rank","rank"];m&&(Pt.push(...xt(s[2].dims)),pr.push("rank")),Pt.push(...xt(l));let Rt=zt=>{let Br=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"},{name:"pad",type:"i32",length:2},{name:"stride",type:"i32",length:2},{name:"dilation",type:"i32",length:2}];Gs(i,Br);let rr=Y?4:1,Kt=Ir(s[0].dataType),Or=` fn setOutputAtIndex(flatIndex : i32, value : ${Y?`vec4<${Kt}>`:Kt}) { result[flatIndex] = ${Y?`vec4<${Kt}>`:Kt}(value); } fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${Y?`vec4<${Kt}>`:Kt}) { let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); setOutputAtIndex(flatIndex ${Y?"/ 4":""}, value); }`,ut=Qe("x",s[0].dataType,s[0].dims.length,Ce===3?1:Ce),It=Qe("w",s[1].dataType,s[1].dims.length,rr),Sr=[ut,It],ln=Dt("result",s[0].dataType,l.length,rr);if(m){let ls=Qe("bias",s[2].dataType,s[2].dims.length,rr);Sr.push(ls),Or+=` fn getBiasByOutputCoords(coords : vec4) -> ${Y?`vec4<${Kt}>`:Kt} { return bias[coords.${P?"w":"y"}${Y?"/ 4":""}]; }`}return` ${Td("uniforms.result_strides")} //struct Uniforms { xShape : vec4, wShape : vec4, outShape : vec4, // outShapeStrides: vec3, filterDims : vec2, pad : vec2, stride : vec2, // dilation : vec2, dimAOuter : i32, dimBOuter : i32, dimInner : i32 }; ${zt.registerUniforms(Br).declareVariables(...Sr,ln)} ${Or} ${Su(P,lt,kt,ir,m,i,cr[0],cr[1],cr[2],Kt)} ${Y?xu(ye,te,Kt,void 0,!P,tt):Mu(ye,te,Kt,void 0,!P,tt,!1,void 0,v)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${i.cacheKey};${Ce};${Y};${lt};${kt};${ir};${Be};${je};${tt}`,inputDependencies:pr},getRunData:()=>({outputs:[{dims:x?x(l):l,dataType:s[0].dataType}],dispatchGroup:{x:be[0],y:be[1],z:be[2]},programUniforms:Pt}),getShaderSource:Rt}}}),Au,ku,ni,Cd,Iu,Wi,Sd,Ad,Zp=c(()=>{Wt(),Ie(),jt(),or(),da(),wu(),Au=s=>{let i=1;for(let l=0;ltypeof s=="number"?[s,s,s]:s,ni=(s,i)=>i<=1?s:s+(s-1)*(i-1),Cd=(s,i,l,f=1)=>{let p=ni(i,f);return Math.floor((s[0]*(l-1)-l+p)/2)},Iu=(s,i,l,f,p)=>{p==null&&(p=Cd(s,i[0],f[0]));let g=[0,0,0,l];for(let m=0;m<3;m++)s[m]+2*p>=i[m]&&(g[m]=Math.trunc((s[m]-i[m]+2*p)/f[m]+1));return g},Wi=(s,i,l,f,p,g,m,v,x,P)=>{let D,R,E,K;if(s==="VALID"&&(s=0),typeof s=="number"){D={top:s,bottom:s,left:s,right:s,front:s,back:s};let q=Iu([i,l,f,1],[v,x,P],1,[p,g,m],s);R=q[0],E=q[1],K=q[2]}else if(Array.isArray(s)){if(!s.every((Y,ne,se)=>Y===se[0]))throw Error(`Unsupported padding parameter: ${s}`);D={top:s[0],bottom:s[1],left:s[2],right:s[3],front:s[4],back:s[5]};let q=Iu([i,l,f,1],[v,x,P],1,[p,g,m],s[0]);R=q[0],E=q[1],K=q[2]}else if(s==="SAME_UPPER"){R=Math.ceil(i/p),E=Math.ceil(l/g),K=Math.ceil(f/m);let q=(R-1)*p+v-i,Y=(E-1)*g+x-l,ne=(K-1)*m+P-f,se=Math.floor(q/2),te=q-se,ye=Math.floor(Y/2),be=Y-ye,Ce=Math.floor(ne/2),Be=ne-Ce;D={top:ye,bottom:be,left:Ce,right:Be,front:se,back:te}}else throw Error(`Unknown padding parameter: ${s}`);return{padInfo:D,outDepth:R,outHeight:E,outWidth:K}},Sd=(s,i,l,f,p,g=!1,m="channelsLast")=>{let v,x,P,D,R;if(m==="channelsLast")[v,x,P,D,R]=s;else if(m==="channelsFirst")[v,R,x,P,D]=s;else throw new Error(`Unknown dataFormat ${m}`);let[E,,K,q,Y]=i,[ne,se,te]=ku(l),[ye,be,Ce]=ku(f),Be=ni(K,ye),je=ni(q,be),tt=ni(Y,Ce),{padInfo:lt,outDepth:kt,outHeight:ir,outWidth:cr}=Wi(p,x,P,D,ne,se,te,Be,je,tt),Pt=g?E*R:E,pr=[0,0,0,0,0];return m==="channelsFirst"?pr=[v,Pt,kt,ir,cr]:m==="channelsLast"&&(pr=[v,kt,ir,cr,Pt]),{batchSize:v,dataFormat:m,inDepth:x,inHeight:P,inWidth:D,inChannels:R,outDepth:kt,outHeight:ir,outWidth:cr,outChannels:Pt,padInfo:lt,strideDepth:ne,strideHeight:se,strideWidth:te,filterDepth:K,filterHeight:q,filterWidth:Y,effectiveFilterDepth:Be,effectiveFilterHeight:je,effectiveFilterWidth:tt,dilationDepth:ye,dilationHeight:be,dilationWidth:Ce,inShape:s,outShape:pr,filterShape:i}},Ad=(s,i,l,f,p,g)=>{let m=g==="channelsLast";m?s[0].dims[3]:s[0].dims[1];let v=[64,1,1],x={x:l.map((ne,se)=>se)},P=[Math.ceil(Au(x.x.map(ne=>l[ne]))/v[0]),1,1];Tr("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${P}`);let D=1,R=ze.size(l),E=[{type:12,data:R},{type:12,data:f},{type:12,data:p},{type:12,data:i.strides},{type:12,data:i.dilations}];ca(i,E),E.push(...xt(s[0].dims,s[1].dims));let K=["rank","rank"],q=s.length===3;q&&(E.push(...xt(s[2].dims)),K.push("rank")),E.push(...xt(l));let Y=ne=>{let se=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:f.length},{name:"pads",type:"u32",length:p.length},{name:"strides",type:"u32",length:i.strides.length},{name:"dilations",type:"u32",length:i.dilations.length}];Gs(i,se);let te=1,ye=Ir(s[0].dataType),be=Qe("x",s[0].dataType,s[0].dims.length,D),Ce=Qe("W",s[1].dataType,s[1].dims.length,te),Be=[be,Ce],je=Dt("result",s[0].dataType,l.length,te),tt="";if(q){let ir=Qe("bias",s[2].dataType,s[2].dims.length,te);Be.push(ir),tt+=` fn getBiasByOutputCoords(coords : array) -> ${ye} { return bias[${m?Ft("coords",4,5):Ft("coords",1,5)}]; }`}let lt=wn(D,ye),kt=Ws(i,lt,ye);return` ${tt} fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { let aIndices = array(d0, d1, d2, d3, d4); return ${be.getByIndices("aIndices")}; } fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { let aIndices = array(d0, d1, d2, d3, d4); return ${Ce.getByIndices("aIndices")}; } ${ne.registerUniforms(se).declareVariables(...Be,je)} ${ne.mainStart()} ${ne.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let coords = ${je.offsetToIndices("global_idx")}; let batch = ${Ft("coords",0,be.rank)}; let d2 = ${m?Ft("coords",be.rank-1,be.rank):Ft("coords",1,be.rank)}; let xFRCCorner = vec3(${m?Ft("coords",1,be.rank):Ft("coords",2,be.rank)}, ${m?Ft("coords",2,be.rank):Ft("coords",3,be.rank)}, ${m?Ft("coords",3,be.rank):Ft("coords",4,be.rank)}) * uniforms.strides - uniforms.pads; let xFCorner = xFRCCorner.x; let xRCorner = xFRCCorner.y; let xCCorner = xFRCCorner.z; let xShapeY = ${m?Ft("uniforms.x_shape",1,be.rank):Ft("uniforms.x_shape",2,be.rank)}; let xShapeZ = ${m?Ft("uniforms.x_shape",2,be.rank):Ft("uniforms.x_shape",3,be.rank)}; let xShapeW = ${m?Ft("uniforms.x_shape",3,be.rank):Ft("uniforms.x_shape",4,be.rank)}; let xShapeU = ${m?Ft("uniforms.x_shape",4,be.rank):Ft("uniforms.x_shape",1,be.rank)}; let inputDepthNearestVec4 = (xShapeU / 4) * 4; let inputDepthVec4Remainder = xShapeU % 4; var value = 0.0; for (var wF = 0u; wF < uniforms.filter_dims[0]; wF++) { let xF = xFCorner + wF * uniforms.dilations[0]; if (xF < 0 || xF >= xShapeY) { continue; } for (var wR = 0u; wR < uniforms.filter_dims[1]; wR++) { let xR = xRCorner + wR * uniforms.dilations[1]; if (xR < 0 || xR >= xShapeZ) { continue; } for (var wC = 0u; wC < uniforms.filter_dims[2]; wC++) { let xC = xCCorner + wC * uniforms.dilations[2]; if (xC < 0 || xC >= xShapeW) { continue; } for (var d1 = 0u; d1 < inputDepthNearestVec4; d1 += 4) { ${m?`let xValues = vec4( getX(batch, xF, xR, xC, d1), getX(batch, xF, xR, xC, d1 + 1), getX(batch, xF, xR, xC, d1 + 2), getX(batch, xF, xR, xC, d1 + 3)); `:`let xValues = vec4( getX(batch, d1, xF, xR, xC), getX(batch, d1 + 1, xF, xR, xC), getX(batch, d1 + 2, xF, xR, xC), getX(batch, d1 + 3, xF, xR, xC)); `} let wValues = vec4( getW(d2, d1, wF, wR, wC), getW(d2, d1 + 1, wF, wR, wC), getW(d2, d1 + 2, wF, wR, wC), getW(d2, d1 + 3, wF, wR, wC)); value += dot(xValues, wValues); } if (inputDepthVec4Remainder == 1) { ${m?`value += getX(batch, xF, xR, xC, inputDepthNearestVec4) * getW(d2, inputDepthNearestVec4, wF, wR, wC);`:`value += getX(batch, inputDepthNearestVec4, xF, xR, xC) * getW(d2, inputDepthNearestVec4, wF, wR, wC);`} } else if (inputDepthVec4Remainder == 2) { ${m?`let xValues = vec2( getX(batch, xF, xR, xC, inputDepthNearestVec4), getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1)); `:`let xValues = vec2( getX(batch, inputDepthNearestVec4, xF, xR, xC), getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC)); `} let wValues = vec2( getW(d2, inputDepthNearestVec4, wF, wR, wC), getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC)); value += dot(xValues, wValues); } else if (inputDepthVec4Remainder == 3) { ${m?`let xValues = vec3( getX(batch, xF, xR, xC, inputDepthNearestVec4), getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1), getX(batch, xF, xR, xC, inputDepthNearestVec4 + 2)); `:`let xValues = vec3( getX(batch, inputDepthNearestVec4, xF, xR, xC), getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC), getX(batch, inputDepthNearestVec4 + 2, xF, xR, xC)); `} let wValues = vec3( getW(d2, inputDepthNearestVec4, wF, wR, wC), getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC), getW(d2, inputDepthNearestVec4 + 2, wF, wR, wC)); value += dot(xValues, wValues); } } } } ${q?"value = value + getBiasByOutputCoords(coords)":""}; ${kt} result[global_idx] = f32(value); }`};return{name:"Conv3DNaive",shaderCache:{hint:`${i.cacheKey};${m};${D};${q}`,inputDependencies:K},getRunData:()=>({outputs:[{dims:l,dataType:s[0].dataType}],dispatchGroup:{x:P[0],y:P[1],z:P[2]},programUniforms:E}),getShaderSource:Y}}}),kd,Id,$d=c(()=>{Wt(),jt(),or(),da(),kd=(s,i,l,f)=>{let p=s.length>2,g=p?"value += b[output_channel];":"",m=s[0].dims,v=s[1].dims,x=i.format==="NHWC",P=x?l[3]:l[1],D=P/i.group,R=x&&D>=4?sr(P):1,E=ze.size(l)/R,K=[{type:12,data:E},{type:12,data:i.dilations},{type:12,data:[i.strides[0],i.strides[1]]},{type:12,data:[i.pads[0],i.pads[1]]},{type:12,data:D}];ca(i,K),K.push(...xt(m,[v[0],v[1],v[2],v[3]/R]));let q=p?["rank","rank","rank"]:["rank","rank"];K.push(...xt([l[0],l[1],l[2],l[3]/R]));let Y=ne=>{let se=Dt("output",s[0].dataType,l.length,R),te=Ir(se.type.tensor),ye=Ws(i,se.type.value,te),be=Qe("x",s[0].dataType,m.length),Ce=Qe("w",s[1].dataType,v.length,R),Be=[be,Ce];p&&Be.push(Qe("b",s[2].dataType,s[2].dims,R));let je=[{name:"output_size",type:"u32"},{name:"dilations",type:"u32",length:i.dilations.length},{name:"strides",type:"u32",length:2},{name:"pads",type:"u32",length:2},{name:"output_channels_per_group",type:"u32"}];Gs(i,je);let tt=x?` for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[0]; wHeight++) { let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; if (xHeight < 0u || xHeight >= uniforms.x_shape[1]) { continue; } for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[1]; wWidth++) { let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1]; if (xWidth < 0u || xWidth >= uniforms.x_shape[2]) { continue; } for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[2]; wInChannel++) { let input_channel = in_channel_offset + wInChannel; let xVal = ${be.get("batch","xHeight","xWidth","input_channel")}; let wVal = ${Ce.get("wHeight","wWidth","wInChannel","output_channel")}; value += xVal * wVal; } } } `:` for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) { let input_channel = in_channel_offset + wInChannel; for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[2]; wHeight++) { let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; if (xHeight < 0u || xHeight >= uniforms.x_shape[2]) { continue; } for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[3]; wWidth++) { let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1]; if (xWidth < 0u || xWidth >= uniforms.x_shape[3]) { continue; } let xVal = ${be.get("batch","input_channel","xHeight","xWidth")}; let wVal = ${Ce.get("output_channel","wInChannel","wHeight","wWidth")}; value += xVal * wVal; } } } `;return` ${ne.registerUniforms(je).declareVariables(...Be,se)} ${ne.mainStart()} ${ne.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let outputIndices = ${se.offsetToIndices("global_idx")}; let batch: u32 = outputIndices[0]; let output_channel: u32 = outputIndices[${x?3:1}]; let xRCCorner: vec2 = vec2(outputIndices[${x?1:2}], outputIndices[${x?2:3}]) * uniforms.strides - uniforms.pads; let group_id: u32 = output_channel * ${R} / uniforms.output_channels_per_group; var in_channel_offset = group_id * uniforms.w_shape[${x?2:1}]; var value: ${se.type.value} = ${se.type.value}(0); ${tt} ${g} ${ye} ${se.setByOffset("global_idx","value")} }`};return{name:"GroupedConv",shaderCache:{hint:`${i.cacheKey}_${R}`,inputDependencies:q},getRunData:()=>({outputs:[{dims:f?f(l):l,dataType:s[0].dataType}],dispatchGroup:{x:Math.ceil(E/64)},programUniforms:K}),getShaderSource:Y}},Id=(s,i,l,f)=>{let p=s.length>2,g=sr(l[3]),m=sr(l[2]),v=ze.size(l)/g/m,x=[s[0].dims[0],s[0].dims[1],s[0].dims[2],s[0].dims[3]/g],P=[s[1].dims[0],s[1].dims[1],s[1].dims[2],s[1].dims[3]/g],D=[l[0],l[1],l[2],l[3]/g],R=[{type:12,data:v},{type:6,data:[i.strides[0],i.strides[1]]},{type:6,data:[i.pads[0],i.pads[1]]}];ca(i,R),R.push(...xt(x,P,D));let E=(m-1)*i.strides[1]+P[1],K=q=>{let Y=Dt("output",s[0].dataType,D.length,g),ne=Ir(Y.type.tensor),se=Ws(i,Y.type.value,ne),te=Qe("x",s[0].dataType,x.length,g),ye=Qe("w",s[1].dataType,P.length,g),be=[te,ye];p&&be.push(Qe("b",s[2].dataType,s[2].dims,g));let Ce=p?"value += b[output_channel];":"",Be=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return Gs(i,Be),` ${q.registerUniforms(Be).declareVariables(...be,Y)} ${q.mainStart()} ${q.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let width0 = uniforms.output_shape[3]; let output_channel = global_idx % width0; var index1 = global_idx / width0; let width1 = uniforms.output_shape[2] / ${m}u; let col = (index1 % width1) * ${m}u; index1 = index1 / width1; let row = index1 % uniforms.output_shape[1]; let batch = index1 / uniforms.output_shape[1]; let x_corner = vec2(i32(row), i32(col)) * uniforms.strides - uniforms.pads; var x_vals: array<${te.type.value}, ${E}>; var values: array<${Y.type.value}, ${m}>; let input_channel = output_channel; // Use constant instead of uniform can give better performance for w's height/width. for (var w_height: u32 = 0u; w_height < ${P[0]}; w_height++) { let x_height = x_corner.x + i32(w_height); if (x_height >= 0 && u32(x_height) < uniforms.x_shape[1]) { for (var i = 0; i < ${E}; i++) { let x_width = x_corner.y + i; if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) { x_vals[i] = ${te.get("batch","u32(x_height)","u32(x_width)","input_channel")}; } else { x_vals[i] = ${te.type.value}(0); } } for (var w_width: u32 = 0u; w_width < ${P[1]}; w_width++) { let w_val = ${ye.get("w_height","w_width","0","output_channel")}; for (var i = 0u; i < ${m}u; i++) { values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]); } } } } for (var i = 0u; i < ${m}u; i++) { var value = values[i]; ${Ce} ${se} ${Y.set("batch","row","col + i","output_channel","value")}; } }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${i.cacheKey};${g};${m};${E};${P[0]};${P[1]}`,inputDependencies:p?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:f?f(l):l,dataType:s[0].dataType}],dispatchGroup:{x:Math.ceil(v/64)},programUniforms:R}),getShaderSource:K}}}),Od,Gi,$u,Hi,Ou,Lu,Ld,Ru,Fu,Yp=c(()=>{jt(),qp(),Zp(),Cu(),$d(),da(),Eu(),Vs(),Od=(s,i,l,f,p,g)=>{let m=s[0],v=s.slice(g?1:2,g?3:4),x=v.length,P=i[0],D=i.slice(2).map((E,K)=>E+(E-1)*(l[K]-1)),R=v.map((E,K)=>E+f[K]+f[K+x]).map((E,K)=>Math.floor((E-D[K]+p[K])/p[K]));return R.splice(0,0,m),R.splice(g?3:1,0,P),R},Gi=[2,3,1,0],$u=(s,i)=>{if(!s||s.length!==2&&s.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(s[0].dims.length>5)throw new Error("greater than 5D is not supported");if(s[0].dims.length!==s[1].dims.length)throw new Error("filter does not have same dimension as input");let l=s[0].dims[i.format==="NHWC"?s[0].dims.length-1:1],f=s[1].dims[1]*i.group;if(l!==f)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(s.length===3&&(s[2].dims.length!==1||s[1].dims[0]!==s[2].dims[0]))throw new Error("invalid bias");let p=s[0].dims.length-2;if(i.dilations.length!==p)throw new Error(`dilations should be ${p}D`);if(i.strides.length!==p)throw new Error(`strides should be ${p}D`);if(i.pads.length!==p*2)throw new Error(`pads should be ${p*2}D`);if(i.kernelShape.length!==0&&i.kernelShape.length!==s[1].dims.length-2)throw new Error("invalid kernel shape")},Hi=(s,i)=>{let l=s.kernelShape.slice();l.length{let i=bu(s),l=s.format,f=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][s.auto_pad],p=s.dilations,g=s.group,m=s.kernel_shape,v=s.pads,x=s.strides,P=s.w_is_const();return{autoPad:f,format:l,dilations:p,group:g,kernelShape:m,pads:v,strides:x,wIsConst:P,...i,cacheKey:`${s.format};${i.activation};`}},Lu=(s,i,l,f)=>{let p=l.format==="NHWC",g=Od(i[0].dims,i[1].dims,l.dilations,l.pads,l.strides,p);if(l.group!==1){let Be=[i[0]];if(p){let je=s.kernelCustomData.wT??s.compute(qn(i[1],Gi),{inputs:[1],outputs:[l.wIsConst?-2:-1]})[0];l.wIsConst&&!s.kernelCustomData.wT&&(s.kernelCustomData.wT=je),Be.push(je)}else Be.push(i[1]);i.length===3&&Be.push(i[2]),!s.adapterInfo.isArchitecture("ampere")&&p&&i[1].dims[0]===l.group&&i[1].dims[1]===1&&l.dilations[0]===1&&l.dilations[1]===1?s.compute(Id(Be,l,g,f),{inputs:Be}):s.compute(kd(Be,l,g,f),{inputs:Be});return}let m=i.length===3,v=i[0].dims[p?1:2],x=i[0].dims[p?2:3],P=i[0].dims[p?3:1],D=i[1].dims[2],R=i[1].dims[3],E=g[p?1:2],K=g[p?2:3],q=g[p?3:1],Y=p&&D===v&&R===x&&l.pads[0]===0&&l.pads[1]===0;if(Y||D===1&&R===1&&l.dilations[0]===1&&l.dilations[1]===1&&l.strides[0]===1&&l.strides[1]===1&&l.pads[0]===0&&l.pads[1]===0){let Be=g[0],je,tt,lt,kt=[];if(p){let Pt=s.kernelCustomData.wT??s.compute(qn(i[1],Gi),{inputs:[1],outputs:[l.wIsConst?-2:-1]})[0];if(l.wIsConst&&!s.kernelCustomData.wT&&(s.kernelCustomData.wT=Pt),Y){let pr=v*x*P;je=i[0].reshape([1,Be,pr]),tt=Pt.reshape([1,pr,q]),lt=[1,Be,q]}else je=i[0].reshape([Be,v*x,P]),tt=Pt.reshape([1,P,q]),lt=[Be,E*K,q];kt.push(je),kt.push(tt)}else je=i[0].reshape([Be,P,v*x]),tt=i[1].reshape([1,q,P]),lt=[Be,q,E*K],kt.push(tt),kt.push(je);m&&kt.push(i[2]);let ir=lt[2],cr=kt[0].dims[kt[0].dims.length-1];ir<8&&cr<8?s.compute(vu(kt,l,g,lt,p,f),{inputs:kt}):s.compute(Vi(kt,l,g,lt,p,f),{inputs:kt});return}let ne=!0,se=s.kernelCustomData.wT??s.compute(qn(i[1],Gi),{inputs:[1],outputs:[l.wIsConst?-2:-1]})[0];l.wIsConst&&!s.kernelCustomData.wT&&(s.kernelCustomData.wT=se);let te=[i[0],se];m&&te.push(i[2]);let ye=p?E*K:q,be=p?q:E*K,Ce=D*R*P;s.compute(Pd(te,l,g,ye,be,Ce,m,ne,f),{inputs:te})},Ld=(s,i)=>{let l=i.format==="NHWC",f=[s.inputs[0].reshape(l?[s.inputs[0].dims[0],1,s.inputs[0].dims[1],s.inputs[0].dims[2]]:[s.inputs[0].dims[0],s.inputs[0].dims[1],1,s.inputs[0].dims[2]]),s.inputs[1].reshape([s.inputs[1].dims[0],s.inputs[1].dims[1],1,s.inputs[1].dims[2]])];s.inputs.length===3&&f.push(s.inputs[2]);let p=[0,i.pads[0],0,i.pads[1]],g=[1].concat(i.strides),m=[1].concat(i.dilations),v=[1].concat(i.kernelShape),x=Hi({...i,pads:p,strides:g,dilations:m,kernelShape:v},f);Lu(s,f,x,P=>l?[P[0],P[2],P[3]]:[P[0],P[1],P[3]])},Ru=(s,i,l)=>{let f=l.format==="NHWC"?"channelsLast":"channelsFirst",p=Hi(l,i),g=l.autoPad==="NOTSET"?l.pads:l.autoPad,m=Sd(i[0].dims,i[1].dims,l.strides,l.dilations,g,!1,f);s.compute(Ad(i,p,m.outShape,[m.filterDepth,m.filterHeight,m.filterWidth],[m.padInfo.front,m.padInfo.top,m.padInfo.left],f))},Fu=(s,i)=>{if($u(s.inputs,i),s.inputs[0].dims.length===3)Ld(s,i);else if(s.inputs[0].dims.length===5)Ru(s,s.inputs,i);else{let l=Hi(i,s.inputs);Lu(s,s.inputs,l)}}}),Nu,Xp=c(()=>{Wt(),Ie(),jt(),or(),Nu=(s,i,l)=>{let f=s.length>2,p=i.outputShape,g=i.format==="NHWC",m=i.group,v=s[1].dims,x=v[2]/m,P=v[3],D=g?sr(x):1,R=g?sr(P):1,E=g?P===1?D:R:1,K=ze.size(p)/R,q=[Math.ceil(K/64),1,1];Tr("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${q}`);let Y=["rank","rank"],ne=[i.strides[0],i.strides[1]],se=[i.kernelShape[g?1:2],i.kernelShape[g?2:3]],te=[i.dilations[0],i.dilations[1]],ye=[se[0]+(i.dilations[0]<=1?0:(i.kernelShape[g?1:2]-1)*(i.dilations[0]-1)),se[1]+(i.dilations[1]<=1?0:(i.kernelShape[g?2:3]-1)*(i.dilations[1]-1))],be=[ye[0]-1-Math.floor((i.pads[0]+i.pads[2])/2),ye[1]-1-Math.floor((i.pads[1]+i.pads[3])/2)],Ce=[{type:12,data:K},{type:12,data:ne},{type:12,data:se},{type:12,data:te},{type:12,data:ye},{type:6,data:be},{type:12,data:x},{type:12,data:P},...xt(s[0].dims,s[1].dims)];f&&(Ce.push(...xt(s[2].dims)),Y.push("rank")),Ce.push(...xt(p));let Be=je=>{let tt=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:ne.length},{name:"filter_dims",type:"u32",length:se.length},{name:"dilations",type:"u32",length:se.length},{name:"effective_filter_dims",type:"u32",length:ye.length},{name:"pads",type:"i32",length:be.length},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],lt=Ir(s[0].dataType),kt=g?1:2,ir=g?2:3,cr=g?3:1,Pt=Qe("W",s[1].dataType,s[1].dims.length,E),pr=Qe("Dy",s[0].dataType,s[0].dims.length,D),Rt=[pr,Pt];f&&Rt.push(Qe("bias",s[2].dataType,[p[cr]].length,R));let zt=Dt("result",s[0].dataType,p.length,R),Br=()=>{let Kt="";if(D===1)Kt+=` let w_offset = ${Pt.indicesToOffset(`${Pt.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel, wOutChannel)`)}; let wValue = ${Pt.getByOffset(`w_offset / ${E}`)}; dotProd = dotProd + xValue * wValue;`;else if(P===1)Kt+=` let wValue = ${Pt.getByOffset(`${Pt.indicesToOffset(`${Pt.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel, wOutChannel)`)} / ${E}`)}; dotProd = dotProd + dot(xValue, wValue);`;else for(let Or=0;Or(i32(r), i32(c)) - uniforms.pads; let dyRCorner = dyCorner.x; let dyCCorner = dyCorner.y; let groupId = d1 / uniforms.output_channels_per_group; let wOutChannel = d1 - groupId * uniforms.output_channels_per_group; // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). // ? = to be determined. : = across all values in that axis. var dotProd = ${zt.type.value}(0.0); for (var wR: u32 = 0; wR < uniforms.effective_filter_dims.x; wR = wR + 1) { if (wR % uniforms.dilations.x != 0) { continue; } let dyR = (${lt}(dyRCorner) + ${lt}(wR)) / ${lt}(uniforms.strides[0]); let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; if (dyR < 0.0 || dyR >= ${lt}(uniforms.Dy_shape[${kt}]) || fract(dyR) > 0.0 || wRPerm < 0) { continue; } wR = wR + uniforms.strides[0] - 1; let idyR: u32 = u32(dyR); for (var wC: u32 = 0; wC < uniforms.effective_filter_dims.y; wC = wC + 1) { if (wC % uniforms.dilations.y != 0) { continue; } let dyC = (${lt}(dyCCorner) + ${lt}(wC)) / ${lt}(uniforms.strides.y); let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; if (dyC < 0.0 || dyC >= ${lt}(uniforms.Dy_shape[${ir}]) || fract(dyC) > 0.0 || wCPerm < 0) { continue; } wC = wC + uniforms.strides.y - 1; let idyC: u32 = u32(dyC); var inputChannel = groupId * uniforms.input_channels_per_group; for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group; d2 = d2 + ${D}) { let xValue = ${g?pr.getByOffset(`${pr.indicesToOffset(`${pr.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${D}`):pr.get("batch","inputChannel","idyR","idyC")}; ${Br()} inputChannel = inputChannel + ${D}; } } } let value = dotProd${f?` + bias[d1 / ${R}]`:""}; ${zt.setByOffset("global_idx","value")}; `;return` ${je.registerUniforms(tt).declareVariables(...Rt,zt)} ${je.mainStart()} ${je.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; ${rr}}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${i.cacheKey};${D}${E}${R}${P===1}`,inputDependencies:Y},getRunData:()=>({dispatchGroup:{x:q[0],y:q[1],z:q[2]},outputs:[{dims:l?l(p):p,dataType:s[0].dataType}],programUniforms:Ce}),getShaderSource:Be}}}),Rd,Du,Fd,Bu,ju,Nd,zu,Dd,Bd,jd=c(()=>{Xp(),da(),Vs(),Rd=(s,i,l,f,p,g)=>(s-1)*i+l+(f-1)*p+1-g,Du=(s,i,l,f,p)=>{let g=Math.floor(s/2);i==="SAME_UPPER"?(l[f]=g,l[p]=s-g):i==="SAME_LOWER"&&(l[f]=s-g,l[p]=g)},Fd=(s,i,l,f,p,g,m,v,x,P)=>{let D=s.length-2,R=P.length===0;x.length{let l=s.kernelShape.slice();if(s.kernelShape.length===0||s.kernelShape.reduce((R,E)=>R*E,1)===0){l.length=0;for(let R=2;RR+E,0)===0){let R=i[0].dims.length-2;x=new Array(R).fill(1)}let P=s.strides.slice();if(P.reduce((R,E)=>R+E,0)===0){let R=i[0].dims.length-2;P=new Array(R).fill(1)}Fd(v,l,x,s.autoPad,s.group,p,P,f,m,g);let D=Object.assign({},s);return Object.assign(D,{kernelShape:l,pads:p,outputPadding:m,outputShape:g,dilations:x,strides:P}),D},ju=s=>{let i=bu(s),l=s.format,f=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof s.autoPad>"u"?0:s.autoPad],p=s.dilations,g=s.group,m=s.kernelShape,v=s.pads,x=s.strides,P=s.wIsConst(),D=s.outputPadding,R=s.outputShape;return{autoPad:f,format:l,dilations:p,group:g,kernelShape:m,outputPadding:D,outputShape:R,pads:v,strides:x,wIsConst:P,...i,cacheKey:`${s.format};${i.activation};`}},Nd=(s,i)=>{if(!s||s.length!==2&&s.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(s[0].dims.length!==4&&s[0].dims.length!==3)throw new Error("currently only support 2-dimensional conv");if(s[0].dims.length!==s[1].dims.length)throw new Error("filter does not have same dimension as input");let l=s[0].dims[i.format==="NHWC"?s[0].dims.length-1:1],f=s[1].dims[0];if(l!==f)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let p=s[1].dims[1]*i.group;if(s.length===3&&(s[2].dims.length!==1||s[2].dims[0]!==p))throw new Error("invalid bias");let g=s[0].dims.length-2;if(i.dilations.reduce((m,v)=>m+v,0)>0&&i.dilations.length!==g)throw new Error(`dilations should be ${g}D`);if(i.strides.reduce((m,v)=>m+v,0)>0&&i.strides.length!==g)throw new Error(`strides should be ${g}D`);if(i.pads.reduce((m,v)=>m+v,0)>0&&i.pads.length!==g*2)throw new Error(`pads should be ${g*2}D`);if(i.outputPadding.length!==g&&i.outputPadding.length!==0)throw new Error(`output_padding should be ${g}D`);if(i.kernelShape.reduce((m,v)=>m+v,0)>0&&i.kernelShape.length!==0&&i.kernelShape.length!==s[1].dims.length-2)throw new Error("invalid kernel shape");if(i.outputShape.length!==0&&i.outputShape.length!==s[0].dims.length-2)throw new Error("invalid output shape")},zu=(s,i,l,f)=>{let p=s.kernelCustomData.wT??s.compute(qn(i[1],[2,3,0,1]),{inputs:[1],outputs:[l.wIsConst?-2:-1]})[0];l.wIsConst&&!s.kernelCustomData.wT&&(s.kernelCustomData.wT=p);let g=[i[0],p];i.length===3&&g.push(i[2]),s.compute(Nu(g,l,f),{inputs:g})},Dd=(s,i)=>{let l=i.format==="NHWC",f=[s.inputs[0].reshape(l?[s.inputs[0].dims[0],1,s.inputs[0].dims[1],s.inputs[0].dims[2]]:[s.inputs[0].dims[0],s.inputs[0].dims[1],1,s.inputs[0].dims[2]]),s.inputs[1].reshape([s.inputs[1].dims[0],s.inputs[1].dims[1],1,s.inputs[1].dims[2]])];s.inputs.length===3&&f.push(s.inputs[2]);let p=i.kernelShape;(p.length===0||p[0]===0)&&(p=[s.inputs[1].dims[2]]);let g=i.dilations;(g.length===0||g[0]===0)&&(g=[1]);let m=i.strides;(m.length===0||m[0]===0)&&(m=[1]);let v=i.pads;v.length===0&&(v=[0,0]),v=[0,v[0],0,v[1]],m=[1].concat(m),g=[1].concat(g),p=[1].concat(p);let x=Bu({...i,pads:v,strides:m,dilations:g,kernelShape:p},f);zu(s,f,x,P=>l?[P[0],P[2],P[3]]:[P[0],P[1],P[3]])},Bd=(s,i)=>{if(Nd(s.inputs,i),s.inputs[0].dims.length===3)Dd(s,i);else{let l=Bu(i,s.inputs);zu(s,s.inputs,l)}}}),zd,Ud,Vd,Qp=c(()=>{Wt(),jt(),mr(),or(),zd=(s,i,l,f)=>{let p=ze.size(i),g=i.length,m=Qe("input",s,g),v=Dt("output",s,g),x=l.dataType===6?l.getInt32Array()[0]:Number(l.getBigInt64Array()[0]),P=ze.normalizeAxis(x,g),D=R=>{let E=` i32(${m.indicesGet("inputIndices","uniforms.axis")}) `,K=Ft("uniforms.input_shape","uniforms.axis",g),q=f.reverse?E+(f.exclusive?" + 1":""):"0",Y=f.reverse?K:E+(f.exclusive?"":" + 1");return` ${R.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(m,v)} ${R.mainStart()} ${R.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var inputIndices = ${v.offsetToIndices("global_idx")}; var sum = ${v.type.value}(0); let first : i32 = ${q}; let last : i32 = ${Y}; for (var i : i32 = first; i < last; i++) { ${m.indicesSet("inputIndices","uniforms.axis","u32(i)")}; sum = sum + ${m.getByIndices("inputIndices")}; } ${v.setByOffset("global_idx","sum")}; }`};return{name:"CumSum",shaderCache:{hint:f.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:i,dataType:s}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:[{type:12,data:p},{type:12,data:P},...xt(i,i)]}),getShaderSource:D}},Ud=(s,i)=>{let l=s.inputs[0].dims,f=s.inputs[0].dataType,p=s.inputs[1];s.compute(zd(f,l,p,i),{inputs:[0]})},Vd=s=>{let i=s.exclusive===1,l=s.reverse===1;return Gt({exclusive:i,reverse:l})}}),Wd,Gd,Uu,Hd,Kd,qd=c(()=>{Wt(),jt(),mr(),or(),Wd=s=>{if(!s||s.length!==1)throw new Error("DepthToSpace requires 1 input.");if(s[0].dims.length!==4)throw new Error("DepthToSpace requires 4D input.")},Gd=(s,i,l,f)=>{let p=[];p.push(`fn perm(i: ${f.type.indices}) -> ${l.type.indices} { var a: ${l.type.indices};`);for(let g=0;g{let l,f,p,g,m,v,x=i.format==="NHWC",P=i.blocksize,D=i.mode==="DCR";x?([l,f,p,g]=s.dims,m=D?[l,f,p,P,P,g/P**2]:[l,f,p,g/P**2,P,P],v=D?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([l,f,p,g]=[s.dims[0],s.dims[2],s.dims[3],s.dims[1]],m=D?[l,P,P,g/P**2,f,p]:[l,g/P**2,P,P,f,p],v=D?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let R=s.reshape(m),E=R.dims.length,K=s.dataType,q=Qe("a",K,E),Y=Dt("output",K,E),ne=se=>` ${se.registerUniform("output_size","u32").declareVariables(q,Y)} ${Gd(v,E,q,Y)} ${se.mainStart()} ${se.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${Y.offsetToIndices("global_idx")}; let aIndices = perm(indices); ${Y.setByOffset("global_idx",q.getByIndices("aIndices"))} }`;return{name:"DepthToSpace",shaderCache:{hint:`${s.dims};${i.blocksize};${i.mode}`,inputDependencies:["rank"]},getRunData:se=>{let te=x?[l,f*P,p*P,g/P**2]:[l,g/P**2,f*P,p*P],ye=ze.size(te),be=R.dims,Ce=ze.sortBasedOnPerm(be,v);return{outputs:[{dims:te,dataType:se[0].dataType}],dispatchGroup:{x:Math.ceil(ye/64)},programUniforms:[{type:12,data:ye},...xt(be,Ce)]}},getShaderSource:ne}},Hd=(s,i)=>{Wd(s.inputs),s.compute(Uu(s.inputs[0],i))},Kd=s=>Gt({blocksize:s.blocksize,mode:s.mode,format:s.format})}),Ki,si,Ss,Zd,Yd,Xd,Qd,qi,Jd,eh,th,Jp=c(()=>{Wt(),jt(),mr(),or(),Ki="[a-zA-Z]|\\.\\.\\.",si="("+Ki+")+",Ss="^"+si+"$",Zd="("+si+",)*"+si,Yd="^"+Zd+"$",Xd=class{constructor(s=-1){this.symbolToIndices=new Map,this.inputIndex=s}addSymbol(s,i){let l=this.symbolToIndices.get(s);l===void 0?l=[i]:l.push(i),this.symbolToIndices.set(s,l)}},Qd=class{constructor(s,i){var p;this.equation=i,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[l,f]=i.includes("->")?i.split("->",2):[i,""];if(!l.match(RegExp(Yd)))throw new Error("Invalid LHS term");if(l.split(",").forEach((g,m)=>{let v=s[m].dims.slice();if(!g.match(RegExp(Ss)))throw new Error("Invalid LHS term");let x=this.processTerm(g,!0,v,m);this.lhs.push(x)}),f==="")f+=[...this.symbolToInfo.entries()].filter(([g,m])=>m.count===1||g==="...").map(([g])=>g).join("");else if(!f.match(RegExp(si)))throw new Error("Invalid RHS");(p=f.match(RegExp(Ki,"g")))==null||p.forEach(g=>{if(g==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let m=this.symbolToInfo.get(g);if(m===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(m.dimValue)}}),this.rhs=this.processTerm(f,!1,this.outputDims)}addSymbol(s,i,l){let f=this.symbolToInfo.get(s);if(f!==void 0){if(f.dimValue!==i&&f.count!==1)throw new Error("Dimension mismatch");f.count++,f.inputIndices.push(l)}else f={count:1,dimValue:i,inputIndices:[l]};this.symbolToInfo.set(s,f)}processTerm(s,i,l,f=-1){let p=l.length,g=!1,m=[],v=0;if(!s.match(RegExp(Ss))&&!i&&s!=="")throw new Error("Invalid LHS term");let x=s.match(RegExp(Ki,"g")),P=new Xd(f);return x==null||x.forEach((D,R)=>{if(D==="..."){if(g)throw new Error("Only one ellipsis is allowed per input term");g=!0;let E=p-x.length+1;if(E<0)throw new Error("Ellipsis out of bounds");if(m=l.slice(v,v+E),this.hasEllipsis){if(this.ellipsisDims.length!==m.length||this.ellipsisDims.toString()!==m.toString())throw new Error("Ellipsis dimensions mismatch")}else if(i)this.hasEllipsis=!0,this.ellipsisDims=m;else throw new Error("Ellipsis must be specified in the LHS");for(let K=0;Ks+"_max",Jd=(s,i,l,f)=>{let p=s.map(P=>P.length).map((P,D)=>Qe(`input${D}`,i,P)),g=ze.size(f),m=Dt("output",i,f.length),v=[...l.symbolToInfo.keys()].filter(P=>!l.rhs.symbolToIndices.has(P)),x=P=>{let D=[],R="var prod = 1.0;",E="var sum = 0.0;",K="sum += prod;",q=[],Y=[],ne=[],se=[],te=l.symbolToInfo.size===l.rhs.symbolToIndices.size;l.symbolToInfo.forEach((be,Ce)=>{var Be;if(l.rhs.symbolToIndices.has(Ce)){let je=(Be=l.rhs.symbolToIndices.get(Ce))==null?void 0:Be[0];je!==void 0&&l.lhs.forEach((tt,lt)=>{if(be.inputIndices.includes(lt)){let kt=tt.symbolToIndices.get(Ce);if(kt===void 0)throw new Error("Invalid symbol error");kt.forEach(ir=>{D.push(`${p[lt].indicesSet(`input${lt}Indices`,ir,m.indicesGet("outputIndices",je))}`)})}})}else l.lhs.forEach((je,tt)=>{if(be.inputIndices.includes(tt)){let lt=je.symbolToIndices.get(Ce);if(lt===void 0)throw new Error("Invalid symbol error");lt.forEach(kt=>{q.push(`${p[tt].indicesSet(`input${tt}Indices`,kt,`${Ce}`)}`)}),se.push(`prod *= ${p[tt].getByIndices(`input${tt}Indices`)};`)}}),Y.push(`for(var ${Ce}: u32 = 0; ${Ce} < uniforms.${qi(Ce)}; ${Ce}++) {`),ne.push("}")});let ye=te?[...D,`let sum = ${p.map((be,Ce)=>be.getByIndices(`input${Ce}Indices`)).join(" * ")};`]:[...D,E,...Y,...q,R,...se,K,...ne];return` ${P.registerUniforms(v.map(be=>({name:`${qi(be)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...p,m)} ${P.mainStart()} ${P.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var outputIndices = ${m.offsetToIndices("global_idx")}; ${p.map((be,Ce)=>`var input${Ce}Indices: ${p[Ce].type.indices};`).join(` `)} ${ye.join(` `)}; ${m.setByOffset("global_idx","sum")}; }`};return{name:"Einsum",shaderCache:{hint:l.equation,inputDependencies:s.map(()=>"rank")},getRunData:()=>{let P=v.filter(R=>l.symbolToInfo.has(R)).map(R=>{var E;return{type:12,data:((E=l.symbolToInfo.get(R))==null?void 0:E.dimValue)||0}});P.push({type:12,data:g});let D=s.map((R,E)=>[...xt(R)]).reduce((R,E)=>R.concat(E),P);return D.push(...xt(f)),{outputs:[{dims:f,dataType:i}],dispatchGroup:{x:Math.ceil(g/64)},programUniforms:D}},getShaderSource:x}},eh=(s,i)=>{let l=new Qd(s.inputs,i.equation),f=l.outputDims,p=s.inputs.map((g,m)=>g.dims);s.compute(Jd(p,s.inputs[0].dataType,l,f))},th=s=>{let i=s.equation.replace(/\s+/g,"");return Gt({equation:i})}}),Zi,Vu,rh,nh,ai,em=c(()=>{Wt(),jt(),or(),Zi=s=>{if(!s||s.length!==2)throw new Error("Expand requires 2 input.");let i=s[0].dims,l=Array.from(s[1].getBigInt64Array(),Number),f=l.length{let l=s.length-i.length,f=[];for(let p=0;ps.length>i.length?Vu(s,i):Vu(i,s),nh=s=>{let i=s[0].dims,l=Array.from(s[1].getBigInt64Array(),Number),f=rh(i,l),p=s[0].dataType,g=p===9||ze.size(i)===1,m=p===9||i.length>0&&i[i.length-1]%4===0?4:1,v=g||f.length>0&&f[f.length-1]%4===0?4:1,x=Math.ceil(ze.size(f)/v),P=R=>{let E=Qe("input",p,i.length,m),K=Dt("output",p,f.length,v),q;if(p===9){let Y=(ne,se,te="")=>` let outputIndices${se} = ${K.offsetToIndices(`outputOffset + ${se}u`)}; let offset${se} = ${E.broadcastedIndicesToOffset(`outputIndices${se}`,K)}; let index${se} = offset${se} / 4u; let component${se} = offset${se} % 4u; ${ne}[${se}] = ${te}(${E.getByOffset(`index${se}`)}[component${se}]); `;q=` let outputOffset = global_idx * ${v}; var data = vec4(0); ${Y("data",0,"u32")} ${Y("data",1,"u32")} ${Y("data",2,"u32")} ${Y("data",3,"u32")} ${K.setByOffset("global_idx","data")} }`}else q=` let outputIndices = ${K.offsetToIndices(`global_idx * ${v}`)}; let inputOffset = ${E.broadcastedIndicesToOffset("outputIndices",K)}; let data = ${K.type.value}(${E.getByOffset(`inputOffset / ${m}`)}); ${K.setByOffset("global_idx","data")} }`;return` ${R.registerUniform("vec_size","u32").declareVariables(E,K)} ${R.mainStart()} ${R.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${q}`},D=[{type:12,data:x},...xt(i,f)];return{name:"Expand",shaderCache:{hint:`${f.length};${m}${v}`,inputDependencies:["rank"]},getShaderSource:P,getRunData:()=>({outputs:[{dims:f,dataType:s[0].dataType}],dispatchGroup:{x:Math.ceil(x/64)},programUniforms:D})}},ai=s=>{Zi(s.inputs),s.compute(nh(s.inputs),{inputs:[0]})}}),sh,ah,tm=c(()=>{Wt(),jt(),or(),hu(),sh=s=>{let i=s[0].dataType,l=ze.size(s[0].dims),f=ze.size(s[1].dims),p=f%4===0,g=m=>{let v=Qe("x",i,[1],4),x=Qe("bias",i,[1],4),P=Dt("y",i,[1],4),D=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],R=K=>` let bias${K}_offset: u32 = (global_idx * 4 + ${K}) % uniforms.bias_size; let bias${K} = ${x.getByOffset(`bias${K}_offset / 4`)}[bias${K}_offset % 4];`,E=p?` let bias = ${x.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${R(0)}${R(1)}${R(2)}${R(3)} let bias = ${v.type.value}(bias0, bias1, bias2, bias3);`;return`${m.registerUniforms(D).declareVariables(v,x,P)} ${ji(Qr(i))} ${m.mainStart(Nn)} ${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} let x = ${v.getByOffset("global_idx")}; ${E} let x_in = x + bias; ${P.setByOffset("global_idx",cu("x_in"))} }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${p}`,inputDependencies:["type","type"]},getShaderSource:g,getRunData:m=>({outputs:[{dims:m[0].dims,dataType:m[0].dataType}],programUniforms:[{type:12,data:Math.ceil(l/4)},{type:12,data:f}],dispatchGroup:{x:Math.ceil(l/Nn/4)}})}},ah=s=>{s.inputs.length<2||ze.size(s.inputs[1].dims)===0?rd(s):s.compute(sh(s.inputs))}}),Yi,ih,oh,uh,W_=c(()=>{Wt(),jt(),mr(),or(),Yi=s=>{if(!s||s.length!==2)throw new Error("Gather requires 2 inputs.")},ih=(s,i)=>{let l=s[0].dims,f=s[1].dims,p=l.length,g=ze.normalizeAxis(i.axis,p),m=l.slice(0);m.splice(g,1,...f);let v=l[g],x=s[0].dataType===9?4:1,P=Math.ceil(ze.size(m)/x),D=[{type:12,data:P},{type:6,data:v},{type:12,data:g},...xt(s[0].dims,s[1].dims,m)],R=E=>{let K=Qe("data",s[0].dataType,s[0].dims.length,x),q=Qe("inputIndices",s[1].dataType,s[1].dims.length),Y=Dt("output",s[0].dataType,m.length,x),ne=te=>{let ye=f.length,be=`var indicesIndices${te} = ${q.type.indices}(0);`;for(let Ce=0;Ce1?`indicesIndices${te}[${Ce}]`:`indicesIndices${te}`} = ${m.length>1?`outputIndices${te}[uniforms.axis + ${Ce}]`:`outputIndices${te}`};`;be+=` var idx${te} = ${q.getByIndices(`indicesIndices${te}`)}; if (idx${te} < 0) { idx${te} = idx${te} + uniforms.axisDimLimit; } var dataIndices${te} : ${K.type.indices}; `;for(let Ce=0,Be=0;Ce1?`dataIndices${te}[${Ce}]`:`dataIndices${te}`} = u32(idx${te});`,Be+=ye):(be+=`${p>1?`dataIndices${te}[${Ce}]`:`dataIndices${te}`} = ${m.length>1?`outputIndices${te}[${Be}]`:`outputIndices${te}`};`,Be++);return be},se;if(s[0].dataType===9){let te=(ye,be,Ce="")=>` let outputIndices${be} = ${Y.offsetToIndices(`outputOffset + ${be}u`)}; ${ne(be)}; let offset${be} = ${K.indicesToOffset(`dataIndices${be}`)}; let index${be} = offset${be} / 4u; let component${be} = offset${be} % 4u; ${ye}[${be}] = ${Ce}(${K.getByOffset(`index${be}`)}[component${be}]); `;se=` let outputOffset = global_idx * ${x}; var value = vec4(0); ${te("value",0,"u32")} ${te("value",1,"u32")} ${te("value",2,"u32")} ${te("value",3,"u32")} ${Y.setByOffset("global_idx","value")} `}else se=` let outputIndices = ${Y.offsetToIndices("global_idx")}; ${ne("")}; let value = ${K.getByIndices("dataIndices")}; ${Y.setByOffset("global_idx","value")}; `;return` ${E.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(K,q,Y)} ${E.mainStart()} ${E.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} ${se} }`};return{name:"Gather",shaderCache:{hint:i.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:m,dataType:s[0].dataType}],dispatchGroup:{x:Math.ceil(P/64)},programUniforms:D}),getShaderSource:R}},oh=s=>Gt({axis:s.axis}),uh=(s,i)=>{let l=s.inputs;Yi(l),s.compute(ih(s.inputs,i))}}),lh,ch,dh,ii=c(()=>{Wt(),jt(),or(),lh=(s,i,l,f,p,g,m,v,x)=>{let P=[{type:12,data:g},{type:12,data:f},{type:12,data:p},{type:12,data:l},{type:12,data:m},{type:12,data:v},{type:12,data:x}],D=[g];P.push(...xt(i.dims,D));let R=E=>{let K=Qe("indices_data",i.dataType,i.dims.length),q=Dt("input_slice_offsets_data",12,1,1),Y=[K,q],ne=[{name:"output_size",type:"u32"},{name:"batch_dims",type:"u32"},{name:"input_dims",type:"u32",length:p.length},{name:"sizes_from_slice_dims_data",type:"u32",length:l.length},{name:"num_slices_per_batch",type:"u32"},{name:"input_batch_stride",type:"u32"},{name:"num_slice_dims",type:"u32"}];return` ${E.registerUniforms(ne).declareVariables(...Y)} ${E.mainStart()} ${E.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let batch_idx = global_idx / uniforms.num_slices_per_batch; let base_offset = batch_idx * uniforms.input_batch_stride; let slice_indices_base_offset = global_idx * uniforms.num_slice_dims; var relative_slice_offset = 0; for (var dim_idx = 0u; dim_idx < uniforms.num_slice_dims; dim_idx ++) { var index = i32(indices_data[dim_idx + slice_indices_base_offset].x); let input_dim_idx = uniforms.batch_dims + dim_idx; if (index < 0) { ${p.length===1?"index += i32(uniforms.input_dims);":"index += i32(uniforms.input_dims[input_dim_idx]);"} } ${l.length===1?"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data);":"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data[dim_idx]);"} } input_slice_offsets_data[global_idx] = base_offset + u32(relative_slice_offset); }`};return s.compute({name:"computeSliceOffsets",shaderCache:{hint:`${p.length}_${l.length}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:D,dataType:s.inputs[1].dataType}],dispatchGroup:{x:Math.ceil(g/64)},programUniforms:P}),getShaderSource:R},{inputs:[i],outputs:[-1]})[0]},ch=(s,i)=>{let l=s.inputs,f=l[0].dims,p=l[0].dataType,g=l[1].dims,m=g[g.length-1],v=ze.sizeToDimension(g,g.length-1),x=ze.sizeFromDimension(f,i.batchDims+m),P=ze.sizeToDimension(f,i.batchDims),D=ze.sizeFromDimension(f,i.batchDims),R=v/P,E=new Array(m),K=x;for(let be=0;bef.length)throw new Error("last dimension of indices must not be larger than rank of input tensor");let ne=g.slice(0,-1).concat(f.slice(Y)),se=ze.size(ne),te=[{type:12,data:se},{type:12,data:x},...xt(l[0].dims,q.dims,ne)],ye=be=>{let Ce=Qe("data",l[0].dataType,l[0].dims.length),Be=Qe("slice_offsets",12,q.dims.length),je=Dt("output",l[0].dataType,ne.length);return` ${be.registerUniform("output_size","u32").registerUniform("slice_size","u32").declareVariables(Ce,Be,je)} ${be.mainStart()} ${be.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let slice_offset = slice_offsets[global_idx / uniforms.slice_size]; output[global_idx] = data[u32(slice_offset) + global_idx % uniforms.slice_size]; }`};s.compute({name:"GatherND",shaderCache:{hint:i.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:ne,dataType:p}],dispatchGroup:{x:Math.ceil(se/64)},programUniforms:te}),getShaderSource:ye},{inputs:[l[0],q]})},dh=s=>({batchDims:s.batch_dims,cacheKey:""})}),hh,fh,ph,mh,rm=c(()=>{Wt(),jt(),mr(),or(),hh=(s,i)=>{if(s.length<3||s.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let l=ze.normalizeAxis(i.quantizeAxis,s[0].dims.length),f=i.blockSize,p=s[0],g=s[2],m=s.length===4?s[3]:void 0;if(g.dims.length!==p.dims.length||!p.dims.map((v,x)=>x===l?Math.ceil(v/f)===g.dims[x]:v===g.dims[x]).reduce((v,x)=>v&&x,!0))throw new Error("Scales must have the same rank as the input tensor and the dims should match except on gatherAxis.");if(m){if(m.dataType!==p.dataType)throw new Error("Zero point must have the same data type as the input tensor.");if(m.dims.length!==g.dims.length||!m.dims.map((v,x)=>v===g.dims[x]).reduce((v,x)=>v&&x,!0))throw new Error("Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis.")}},fh=(s,i)=>{let l=s[0].dims,f=s[1].dims,p=l.length,g=ze.normalizeAxis(i.gatherAxis,p),m=ze.normalizeAxis(i.quantizeAxis,p),v=l.slice(0);v.splice(g,1,...f);let x=ze.size(v),P=s[2].dataType,D=s[0].dataType===22,R=[{type:12,data:x},{type:12,data:m},{type:12,data:g},{type:12,data:i.blockSize},...xt(...s.map((K,q)=>K.dims),v)],E=K=>{let q=Qe("data",s[0].dataType,s[0].dims.length),Y=Qe("inputIndices",s[1].dataType,s[1].dims.length),ne=Qe("scales",s[2].dataType,s[2].dims.length),se=s.length>3?Qe("zeroPoint",s[3].dataType,s[3].dims.length):void 0,te=Dt("output",P,v.length),ye=[q,Y,ne];se&&ye.push(se);let be=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return` ${K.registerUniforms(be).declareVariables(...ye,te)} ${K.mainStart()} let output_indices = ${te.offsetToIndices("global_idx")}; var indices_indices = ${Y.type.indices}(0); ${f.length>1?` for (var i: u32 = 0; i < ${f.length}; i++) { let index = ${te.indicesGet("output_indices","uniforms.gather_axis + i")}; ${Y.indicesSet("indices_indices","i","index")}; }`:`indices_indices = ${te.indicesGet("output_indices","uniforms.gather_axis")};`}; var data_indices = ${q.type.indices}(0); for (var i: u32 = 0; i < uniforms.gather_axis; i++) { let index = ${te.indicesGet("output_indices","i")}; ${q.indicesSet("data_indices","i","index")}; } var index_from_indices = ${Y.getByIndices("indices_indices")}; if (index_from_indices < 0) { index_from_indices += ${l[g]}; } ${q.indicesSet("data_indices","uniforms.gather_axis","u32(index_from_indices)")}; for (var i = uniforms.gather_axis + 1; i < ${v.length}; i++) { let index = ${te.indicesGet("output_indices",`i + ${f.length} - 1`)}; ${q.indicesSet("data_indices","i","index")}; } let data_offset = ${q.indicesToOffset("data_indices")}; let data_index = data_offset % 8; // Convert 4-bit packed data to 8-bit packed data. let packed_4bit_quantized_data = ${q.getByOffset("data_offset / 8")}; let packed_8bit_quantized_data = (packed_4bit_quantized_data >> (4 * (data_index % 2))) & 0x0f0f0f0f; let quantized_data_vec = ${D?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_quantized_data)); let quantized_data = quantized_data_vec[data_index / 2]; var scale_indices = data_indices; let quantize_axis_index = ${ne.indicesGet("data_indices","uniforms.quantize_axis")} / uniforms.block_size; ${ne.indicesSet("scale_indices","uniforms.quantize_axis","quantize_axis_index")}; var scale = ${ne.getByIndices("scale_indices")}; ${se?` let zero_point_indices = scale_indices; let zero_point_offset = ${se.indicesToOffset("zero_point_indices")}; let zero_point_index = zero_point_offset % 8; let packed_4bit_zero_points = ${se.getByOffset("zero_point_offset / 8")}; let packed_8bit_zero_points = (packed_4bit_zero_points >> (4 * (zero_point_index % 2))) & 0x0f0f0f0f; let zero_point_vec = ${D?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_zero_points)); let zero_point = zero_point_vec[zero_point_index / 2];`:"var zero_point = 0"}; let dequantized_data = ${Qr(P)}(quantized_data - zero_point) * scale; ${te.setByOffset("global_idx","dequantized_data")}; }`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${i.cacheKey};${s.filter((K,q)=>q!==1).map(K=>K.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:s.length},(K,q)=>"rank")},getRunData:()=>({outputs:[{dims:v,dataType:P}],dispatchGroup:{x:Math.ceil(x/64)},programUniforms:R}),getShaderSource:E}},ph=(s,i)=>{let l=s.inputs;hh(l,i),s.compute(fh(s.inputs,i))},mh=s=>Gt({blockSize:s.blockSize,gatherAxis:s.gatherAxis,quantizeAxis:s.quantizeAxis})}),_h,gh,Xi,nm,sm=c(()=>{Wt(),jt(),mr(),or(),_h=s=>{if(!s||s.length!==2)throw new Error("GatherElements requires 2 inputs.");if(s[0].dims.length<1)throw new Error("GatherElements requires that the data input be rank >= 1.");if(s[0].dims.length!==s[1].dims.length)throw new Error(`GatherElements requires that the data input and indices input tensors be of same rank.`)},gh=(s,i)=>{let l=s[0].dims,f=s[0].dataType,p=l.length,g=s[1].dims,m=s[1].dataType,v=ze.normalizeAxis(i.axis,p),x=l[v],P=g.slice(0),D=ze.size(P),R=Qe("input",f,p),E=Qe("indicesInput",m,g.length),K=Dt("output",f,P.length),q=[{type:12,data:D},{type:6,data:x},{type:12,data:v}];return q.push(...xt(l,g,P)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:P,dataType:s[0].dataType}],dispatchGroup:{x:Math.ceil(D/64)},programUniforms:q}),getShaderSource:Y=>` ${Y.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(R,E,K)} ${Y.mainStart()} ${Y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let outputIndices = ${K.offsetToIndices("global_idx")}; var idx = ${E.getByOffset("global_idx")}; if (idx < 0) { idx = idx + uniforms.axisDimLimit; } var inputIndices = ${R.type.indices}(outputIndices); ${R.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; let value = ${R.getByIndices("inputIndices")}; ${K.setByOffset("global_idx","value")}; }`}},Xi=s=>Gt({axis:s.axis}),nm=(s,i)=>{let l=s.inputs;_h(l),s.compute(gh(s.inputs,i))}}),bh,yh,wh,vh,Eh=c(()=>{Wt(),jt(),or(),bh=s=>{if(!s)throw new Error("Input is missing");if(s.length<2||s.length>3)throw new Error("Invaid input number.");if(s.length===3&&s[2].dims.length>2)throw new Error("Invalid input shape of C");if(s[0].dataType!==s[1].dataType||s.length===3&&s[0].dataType!==s[2].dataType)throw new Error("Input types are mismatched")},yh=(s,i)=>{let l=s[0].dims.slice(),f=s[1].dims.slice(),[p,g,m]=Cs.getShapeOfGemmResult(l,i.transA,f,i.transB,s.length===3?s[2].dims:void 0),v=[p,g];if(!v)throw new Error("Can't use gemm on the given tensors");let x=16,P=Math.ceil(g/x),D=Math.ceil(p/x),R=!0,E=ze.size(v),K=[{type:12,data:R?P:E},{type:12,data:p},{type:12,data:g},{type:12,data:m},{type:1,data:i.alpha},{type:1,data:i.beta}],q=["type","type"];s.length===3&&(K.push(...xt(s[2].dims)),q.push("rank")),K.push(...xt(v));let Y=se=>{let te="";i.transA&&i.transB?te="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":i.transA&&!i.transB?te="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!i.transA&&i.transB?te="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!i.transA&&!i.transB&&(te="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let ye=i.alpha===1?"":"value *= uniforms.alpha;",be=Qe("a",s[0].dataType,s[0].dims),Ce=Qe("b",s[1].dataType,s[1].dims),Be=be.type.value,je=null,tt=[be,Ce];s.length===3&&(je=Qe("c",s[2].dataType,s[2].dims.length),tt.push(je));let lt=Dt("output",s[0].dataType,v.length);tt.push(lt);let kt=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"},{name:"alpha",type:"f32"},{name:"beta",type:"f32"}];return` ${se.registerUniforms(kt).declareVariables(...tt)} ${se.mainStart()} ${se.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let m = global_idx / uniforms.N; let n = global_idx % uniforms.N; var value = ${Be}(0); for (var k: u32 = 0u; k < uniforms.K; k++) { ${te} } ${ye} ${je!=null?`let cOffset = ${je.broadcastedIndicesToOffset("vec2(m, n)",lt)}; value += ${Be}(uniforms.beta) * ${je.getByOffset("cOffset")};`:""} output[global_idx] = value; }`},ne=se=>{let te=Qe("a",s[0].dataType,s[0].dims),ye=Qe("b",s[1].dataType,s[1].dims),be=null,Ce=[te,ye];s.length===3&&(be=Qe("c",s[2].dataType,s[2].dims.length),Ce.push(be));let Be=Dt("output",s[0].dataType,v.length);Ce.push(Be);let je=[{name:"num_tile_n",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"},{name:"alpha",type:"f32"},{name:"beta",type:"f32"}],tt="",lt="";i.transA&&i.transB?(lt=` var col = tile_row_start + local_id.x; var row = k_start + local_id.y; if (col < uniforms.M && row < uniforms.K) { tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col]; } else { tile_a[local_id.y][local_id.x] = ${te.type.value}(0); } col = k_start + local_id.x; row = tile_col_start + local_id.y; if (col < uniforms.K && row < uniforms.N) { tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col]; } else { tile_b[local_id.y][local_id.x] = ${ye.type.value}(0); } `,tt="value += tile_a[k][local_id.y] * tile_b[local_id.x][k];"):i.transA&&!i.transB?(lt=` var col = tile_row_start + local_id.x; var row = k_start + local_id.y; if (col < uniforms.M && row < uniforms.K) { tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col]; } else { tile_a[local_id.y][local_id.x] = ${te.type.value}(0); } col = tile_col_start + local_id.x; row = k_start + local_id.y; if (col < uniforms.N && row < uniforms.K) { tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col]; } else { tile_b[local_id.y][local_id.x] = ${ye.type.value}(0); } `,tt="value += tile_a[k][local_id.y] * tile_b[k][local_id.x];"):!i.transA&&i.transB?(lt=` var col = k_start + local_id.x; var row = tile_row_start + local_id.y; if (col < uniforms.K && row < uniforms.M) { tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col]; } else { tile_a[local_id.y][local_id.x] = ${te.type.value}(0); } col = k_start + local_id.x; row = tile_col_start + local_id.y; if (col < uniforms.K && row < uniforms.N) { tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col]; } else { tile_b[local_id.y][local_id.x] = ${ye.type.value}(0); } `,tt="value += tile_a[local_id.y][k] * tile_b[local_id.x][k];"):!i.transA&&!i.transB&&(lt=` var col = k_start + local_id.x; var row = tile_row_start + local_id.y; if (col < uniforms.K && row < uniforms.M) { tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col]; } else { tile_a[local_id.y][local_id.x] = ${te.type.value}(0); } col = tile_col_start + local_id.x; row = k_start + local_id.y; if (col < uniforms.N && row < uniforms.K) { tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col]; } else { tile_b[local_id.y][local_id.x] = ${ye.type.value}(0); } `,tt="value += tile_a[local_id.y][k] * tile_b[k][local_id.x];");let kt=i.alpha===1?"":"value *= uniforms.alpha;";return` ${se.registerUniforms(je).declareVariables(...Ce)} var tile_a: array, ${x}>; var tile_b: array, ${x}>; ${se.mainStart([x,x,1])} let tile_col_start = (workgroup_index % uniforms.num_tile_n) * ${x}; let tile_row_start = (workgroup_index / uniforms.num_tile_n) * ${x}; let num_tiles = (uniforms.K - 1) / ${x} + 1; var k_start = 0u; var value = ${Be.type.value}(0); for (var t: u32 = 0u; t < num_tiles; t++) { ${lt} k_start = k_start + ${x}; workgroupBarrier(); for (var k: u32 = 0u; k < ${x}; k++) { ${tt} } workgroupBarrier(); } ${kt} let m = tile_row_start + local_id.y; let n = tile_col_start + local_id.x; ${be!=null?`let cOffset = ${be.broadcastedIndicesToOffset("vec2(m, n)",Be)}; value += ${Be.type.value}(uniforms.beta) * ${be.getByOffset("cOffset")};`:""} if (m < uniforms.M && n < uniforms.N) { output[m * uniforms.N + n] = value; } }`};return R?{name:"GemmShared",shaderCache:{hint:`${i.cacheKey}`,inputDependencies:q},getRunData:()=>({outputs:[{dims:v,dataType:s[0].dataType}],dispatchGroup:{x:P*D},programUniforms:K}),getShaderSource:ne}:{name:"Gemm",shaderCache:{hint:`${i.cacheKey}`,inputDependencies:q},getRunData:()=>({outputs:[{dims:v,dataType:s[0].dataType}],dispatchGroup:{x:Math.ceil(E/64)},programUniforms:K}),getShaderSource:Y}},wh=s=>{let i=s.transA,l=s.transB,f=s.alpha,p=s.beta;return{transA:i,transB:l,alpha:f,beta:p,cacheKey:`${s.transA};${s.transB};${s.alpha===1}`}},vh=(s,i)=>{bh(s.inputs),s.compute(yh(s.inputs,i))}}),ms,As,Hs,ha,Th,Wu,xh,Mh,Qi,Ph,Ch,Sh,Ah,Gu,Hu=c(()=>{Wt(),jt(),mr(),or(),[ms,As,Hs,ha]=[0,1,2,3],Th=s=>{if(s[0].dims.length!==4)throw new Error("only 4-D tensor is supported.");if(s[0].dims.length!==s[1].dims.length)throw new Error("input dimensions must be equal to grid dimensions");if(s[0].dims.length-2!==s[1].dims[s[1].dims.length-1])throw new Error(`last dimension of grid must be equal to ${s[0].dims.length-2}`);if(s[0].dims[0]!==s[1].dims[0])throw new Error("grid batch size must match input batch size")},Wu=` fn gs_get_cubic_coeffs(x: f32) -> vec4 { let cubic_alpha = -0.75f; let x_abs = abs(x); var coeffs: vec4; coeffs[0] = (((cubic_alpha * (x_abs + 1) - 5 * cubic_alpha) * (x_abs + 1) + 8 * cubic_alpha) * (x_abs + 1) - 4 * cubic_alpha); coeffs[1] = (((cubic_alpha + 2) * x_abs - (cubic_alpha + 3)) * x_abs * x_abs + 1); coeffs[2] = (((cubic_alpha + 2) * (1 - x_abs) - (cubic_alpha + 3)) * (1 - x_abs) * (1 - x_abs) + 1); coeffs[3] = (((cubic_alpha * (2 - x_abs) - 5 * cubic_alpha) * (2 - x_abs) + 8 * cubic_alpha) * (2 - x_abs) - 4 * cubic_alpha); return coeffs; } `,xh=s=>` fn gs_bicubic_interpolate(p: mat4x4<${s}>, x: f32, y: f32) -> ${s} { var v: vec4; var coeffs = gs_get_cubic_coeffs(x); for (var i = 0; i < 4; i++) { v[i] = coeffs[0] * p[i][0] + coeffs[1] * p[i][1] + coeffs[2] * p[i][2] + coeffs[3] * p[i][3]; } coeffs = gs_get_cubic_coeffs(y); let pixel = ${s}(coeffs[0] * v[0] + coeffs[1] * v[1] + coeffs[2] * v[2] + coeffs[3] * v[3]); return pixel; } `,Mh=s=>` fn gs_denormalize(n: f32, length: i32) -> f32 { ${s.alignCorners===0?` // alignCorners: false => [-1, 1] to [-0.5, length - 0.5] return ((n + 1.0) * f32(length) - 1.0) / 2.0; `:` // alignCorners: true => [-1, 1] to [0, length - 1] return (n + 1.0) / 2.0 * (f32(length - 1)); `} } `,Qi=s=>` ${s.paddingMode==="reflection"?` fn gs_reflect(x: i32, x_min: f32, x_max: f32) -> u32 { var dx = 0.0; var fx = f32(x); let range = x_max - x_min; if (fx < x_min) { dx = x_min - fx; let n = u32(dx / range); let r = dx - f32(n) * range; if (n % 2 == 0) { fx = x_min + r; } else { fx = x_max - r; } } else if (fx > x_max) { dx = fx - x_max; let n = u32(dx / range); let r = dx - f32(n) * range; if (n % 2 == 0) { fx = x_max - r; } else { fx = x_min + r; } } return u32(fx); }`:""} `,Ph=(s,i,l)=>` fn pixel_at_grid(r: i32, c: i32, H: i32, W: i32, batch: u32, channel: u32, border: vec4) -> ${i} { var pixel = ${i}(0); var indices = vec4(0); indices[${ms}] = batch; indices[${As}] = channel;`+(()=>{switch(l.paddingMode){case"zeros":return` if (r >= 0 && r < H && c >=0 && c < W) { indices[${Hs}] = u32(r); indices[${ha}] = u32(c); } `;case"border":return` indices[${Hs}] = u32(clamp(r, 0, H - 1)); indices[${ha}] = u32(clamp(c, 0, W - 1)); `;case"reflection":return` indices[${Hs}] = gs_reflect(r, border[1], border[3]); indices[${ha}] = gs_reflect(c, border[0], border[2]); `;default:throw new Error(`padding mode ${l.paddingMode} is not supported`)}})()+` return ${s.getByIndices("indices")}; } `,Ch=(s,i,l)=>(()=>{switch(l.mode){case"nearest":return` let result = pixel_at_grid(i32(round(y)), i32(round(x)), H_in, W_in, indices[${ms}], indices[${As}], border); `;case"bilinear":return` let x1 = i32(floor(x)); let y1 = i32(floor(y)); let x2 = x1 + 1; let y2 = y1 + 1; let p11 = pixel_at_grid(y1, x1, H_in, W_in, indices[${ms}], indices[${As}], border); let p12 = pixel_at_grid(y1, x2, H_in, W_in, indices[${ms}], indices[${As}], border); let p21 = pixel_at_grid(y2, x1, H_in, W_in, indices[${ms}], indices[${As}], border); let p22 = pixel_at_grid(y2, x2, H_in, W_in, indices[${ms}], indices[${As}], border); let dx2 = ${i}(f32(x2) - x); let dx1 = ${i}(x - f32(x1)); let dy2 = ${i}(f32(y2) - y); let dy1 = ${i}(y - f32(y1)); let result = dy2 * (dx2 * p11 + dx1 * p12) + dy1 * (dx2 * p21 + dx1 * p22); `;case"bicubic":return` let x0 = i32(floor(x)) - 1; let y0 = i32(floor(y)) - 1; var p: mat4x4<${i}>; for (var h = 0; h < 4; h++) { for (var w = 0; w < 4; w++) { p[h][w] = pixel_at_grid(h + y0, w + x0, H_in, W_in, indices[${ms}], indices[${As}], border); } } let dx = x - f32(x0 + 1); let dy = y - f32(y0 + 1); let result = gs_bicubic_interpolate(p, dx, dy); `;default:throw new Error(`mode ${l.mode} is not supported`)}})()+`${s.setByOffset("global_idx","result")}`,Sh=(s,i)=>{let l=Qe("x",s[0].dataType,s[0].dims.length),f=[s[1].dims[0],s[1].dims[1],s[1].dims[2]],p=Qe("grid",s[1].dataType,f.length,2),g=[s[0].dims[0],s[0].dims[1],s[1].dims[1],s[1].dims[2]];i.format==="NHWC"&&(g=[s[0].dims[0],s[1].dims[1],s[1].dims[2],s[0].dims[3]],[ms,As,Hs,ha]=[0,3,1,2]);let m=Dt("output",s[0].dataType,g.length),v=l.type.value,x=ze.size(g),P=[{type:12,data:x},...xt(s[0].dims,f,g)],D=R=>` ${R.registerUniform("output_size","u32").declareVariables(l,p,m)} ${Wu} ${xh(v)} ${Mh(i)} ${Qi(i)} ${Ph(l,v,i)} ${R.mainStart()} ${R.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let H_in = i32(uniforms.x_shape[${Hs}]); let W_in = i32(uniforms.x_shape[${ha}]); ${i.alignCorners===0?` let x_min = -0.5; let x_max = f32(W_in) - 0.5; let y_min = -0.5; let y_max = f32(H_in) - 0.5; `:` let x_min = 0.0; let x_max = f32(W_in) - 1.0; let y_min = 0.0; let y_max = f32(H_in) - 1.0; `}; let border = vec4(x_min, y_min, x_max, y_max); let indices = ${m.offsetToIndices("global_idx")}; var grid_indices = vec3(indices[${ms}], indices[${Hs}], indices[${ha}]); let nxy = ${p.getByIndices("grid_indices")}; var x = gs_denormalize(f32(nxy[0]), W_in); var y = gs_denormalize(f32(nxy[1]), H_in); ${Ch(m,v,i)} }`;return{name:"GridSample",shaderCache:{hint:`${i.cacheKey}`,inputDependencies:["type","type"]},getRunData:R=>{let E=ze.size(g);return{outputs:[{dims:g,dataType:R[0].dataType}],dispatchGroup:{x:Math.ceil(E/64)},programUniforms:P}},getShaderSource:D}},Ah=(s,i)=>{Th(s.inputs),s.compute(Sh(s.inputs,i))},Gu=s=>Gt({alignCorners:s.align_corners,mode:s.mode,paddingMode:s.padding_mode,format:s.format})}),Dn,kh,Ih,Ji,$h,oi,Ku,Oh=c(()=>{Wt(),jt(),mr(),fe(),qo(),or(),Vs(),Dn=(s,i)=>s.length>i&&s[i].dims.length>0?s[i]:void 0,kh=(s,i)=>{let l=s[0],f=Dn(s,1),p=Dn(s,2),g=Dn(s,3),m=Dn(s,4),v=Dn(s,5),x=Dn(s,6),P=Dn(s,7);if(l.dims.length!==3&&l.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let D=l.dims[0],R=l.dims[1],E=l.dims.length===3?l.dims[2]:i.numHeads*l.dims[4],K=R,q=0,Y=0,ne=Math.floor(E/i.numHeads);if(x&&P&&ze.size(x.dims)&&ze.size(P.dims)){if(x.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(x.dims[0]!==D||x.dims[1]!==i.numHeads||x.dims[3]!==ne)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(P.dims[0]!==D||P.dims[1]!==i.numHeads||P.dims[3]!==ne)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(x.dims[2]!==P.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(P.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');q=x.dims[2],Y=x.dims[2]}else if(x&&ze.size(x.dims)||P&&ze.size(P.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let se;if(f&&ze.size(f.dims)>0){if(l.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(f.dims.length<3||f.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(l.dims[0]!==f.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(f.dims.length===3){if(f.dims[2]!==l.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');se=2,K=f.dims[1]}else if(f.dims.length===5){if(f.dims[2]!==i.numHeads||f.dims[3]!==2||f.dims[4]!==ne)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(p)throw new Error('Expect "value" be none when "key" has packed kv format.');se=5,K=f.dims[1]}else{if(f.dims[1]!==i.numHeads||f.dims[3]!==ne)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');se=0,K=f.dims[2]}}else{if(l.dims.length!==5)throw new Error('Input "query" is expected to have 5 dimensions when key is empty');if(l.dims[2]!==i.numHeads||l.dims[3]!==3)throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');se=3}if(g&&ze.size(g.dims)>0){if(g.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimension');if(f&&f.dims.length===5&&f.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let te=q+K,ye=0;if(m&&ze.size(m.dims)>0){ye=8;let je=m.dims;throw je.length===1?je[0]===D?ye=1:je[0]===3*D+2&&(ye=3):je.length===2&&je[0]===D&&je[1]===te&&(ye=5),ye===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let be=!1,Ce=E;if(p&&ze.size(p.dims)>0){if(p.dims.length!==3&&p.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(l.dims[0]!==p.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(p.dims.length===3){if(K!==p.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');Ce=p.dims[2]}else{if(K!==p.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');Ce=p.dims[1]*p.dims[3],be=!0}}let Be=!1;if(m&&ze.size(m.dims)>0)throw new Error("Key padding mask is not supported");if(v&&ze.size(v.dims)>0){if(v.dims.length!==4)throw new Error('Input "attention_bias" is expected to have 4 dimensions');if(v.dims[0]!==D||v.dims[1]!==i.numHeads||v.dims[2]!==R||v.dims[3]!==te)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:D,sequenceLength:R,pastSequenceLength:q,kvSequenceLength:K,totalSequenceLength:te,maxSequenceLength:Y,inputHiddenSize:0,hiddenSize:E,vHiddenSize:Ce,headSize:ne,vHeadSize:Math.floor(Ce/i.numHeads),numHeads:i.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:i.maskFilterValue,maskType:ye,scale:i.scale,broadcastResPosBias:Be,passPastInKv:be,qkvFormat:se}},Ih=s=>Gt({...s}),Ji=Gt({perm:[0,2,1,3]}),$h=(s,i,l,f,p,g,m)=>{let v=[f,p,g],x=ze.size(v),P=[{type:12,data:x},{type:12,data:m},{type:12,data:g}],D=R=>{let E=Dt("qkv_with_bias",i.dataType,v),K=Qe("qkv",i.dataType,v),q=Qe("bias",l.dataType,v),Y=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` ${R.registerUniforms(Y).declareVariables(K,q,E)} ${R.mainStart()} ${R.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset; qkv_with_bias[global_idx] = qkv[global_idx] + bias[bias_offset_idx]; }`};return s.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:v,dataType:i.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(x/64)},programUniforms:P}),getShaderSource:D},{inputs:[i,l],outputs:[-1]})[0]},oi=(s,i,l,f,p,g,m,v)=>{let x=g;if(m&&ze.size(m.dims)>0){if(f===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return x=$h(s,g,m,i,f,l*p,v),x=x.reshape([i,f,l,p]),l===1||f===1?x:s.compute(qn(x,Ji.perm),{inputs:[x],outputs:[-1]})[0]}else return g.dims.length===3&&(x=g.reshape([i,f,l,p])),l===1||f===1?x:s.compute(qn(x,Ji.perm),{inputs:[x],outputs:[-1]})[0]},Ku=(s,i)=>{let l=kh(s.inputs,i),f=s.inputs[0],p=Dn(s.inputs,1),g=Dn(s.inputs,2),m=Dn(s.inputs,3),v=Dn(s.inputs,4),x=Dn(s.inputs,5),P=Dn(s.inputs,6),D=Dn(s.inputs,7);if(f.dims.length===5)throw new Error("Packed QKV is not implemented");if((p==null?void 0:p.dims.length)===5)throw new Error("Packed KV is not implemented");let R=p&&g&&p.dims.length===4&&g.dims.length===4,E=oi(s,l.batchSize,l.numHeads,l.sequenceLength,l.headSize,f,m,0);if(R)return ti(s,E,p,g,v,void 0,P,D,x,l);if(!p||!g)throw new Error("key and value must be provided");let K=oi(s,l.batchSize,l.numHeads,l.kvSequenceLength,l.headSize,p,m,l.hiddenSize),q=oi(s,l.batchSize,l.numHeads,l.kvSequenceLength,l.vHeadSize,g,m,2*l.hiddenSize);ti(s,E,K,q,v,void 0,P,D,x,l)}}),Lh,qu,am,im,eo,Zu,Rh,Fh=c(()=>{Wt(),jt(),mr(),or(),Lh=s=>{if(!s||s.length<1)throw new Error("too few inputs")},qu=(s,i)=>{let l=[],f=i.numOutputs;return s[1].dims[0]>0&&(s[1].getBigInt64Array().forEach(p=>l.push(Number(p))),f=l.length),Gt({numOutputs:f,axis:i.axis,splitSizes:l})},am=s=>` fn calculateOutputIndex(index: u32) -> u32 { for (var i: u32 = 0u; i < ${s}u; i += 1u ) { if (index < ${Ft("uniforms.size_in_split_axis","i",s)}) { return i; } } return ${s}u; }`,im=s=>{let i=s.length,l=[];for(let f=0;f{let l=s[0].dims,f=ze.size(l),p=s[0].dataType,g=ze.normalizeAxis(i.axis,l.length),m=new Array(i.numOutputs),v=Qe("input",p,l.length),x=new Array(i.numOutputs),P=[],D=[],R=0,E=[{type:12,data:f}];for(let q=0;q` ${q.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",x.length).declareVariables(v,...m)} ${am(x.length)} ${im(m)} ${q.mainStart()} ${q.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} var indices = ${v.offsetToIndices("global_idx")}; var index = ${v.indicesGet("indices",g)}; let output_number = calculateOutputIndex(index); if (output_number != 0) { index -= ${Ft("uniforms.size_in_split_axis","output_number - 1u",x.length)}; ${v.indicesSet("indices",g,"index")}; } writeBufferData(output_number, indices, global_idx); }`;return{name:"Split",shaderCache:{hint:i.cacheKey,inputDependencies:["rank"]},getShaderSource:K,getRunData:()=>({outputs:P,dispatchGroup:{x:Math.ceil(f/64)},programUniforms:E})}},Zu=(s,i)=>{Lh(s.inputs);let l=s.inputs.length===1?i:qu(s.inputs,i);s.compute(eo(s.inputs,l),{inputs:[0]})},Rh=s=>{let i=s.axis,l=s.splitSizes,f=s.numOutputs<0?l.length:s.numOutputs;if(f!==l.length)throw new Error("numOutputs and splitSizes lengh must be equal");return Gt({axis:i,numOutputs:f,splitSizes:l})}}),Yu,Nh,Xu,Qu,om=c(()=>{mr(),qo(),Oh(),Fh(),Vs(),Yu=(s,i)=>{if(i.doRotary)throw new Error("GroupQuerryAttention do_rotary attribute is not supported");if(i.doRotary&&s.length<=7)throw new Error("cos_cache and sin_cache inputs are required if do_rotary is specified");let l=s[0],f=s[1],p=s[2],g=s[3],m=s[4];if(i.localWindowSize!==-1)throw new Error("Local attention is not supported");if(i.softcap!==0)throw new Error("Softcap is not supported");if(i.rotaryInterleaved!==0)throw new Error("Rotary interleaved is not supported");if(i.smoothSoftmax)throw new Error("Smooth softmax is not supported");if(l.dims.length!==3&&l.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let v=!1,x=l.dims[0],P=l.dims[1],D=l.dims.length===3?v?l.dims[2]/3:l.dims[2]:i.numHeads*l.dims[4],R=P,E=0,K=!f||f.dims.length===0,q=Math.floor(K?D/(i.numHeads+2*i.kvNumHeads):D/i.numHeads);K&&(D=q*i.numHeads);let Y=g&&g.dims.length!==0,ne=m&&m.dims.length!==0;if(Y&&g.dims.length===4&&g.dims[0]===x&&g.dims[1]!==i.kvNumHeads&&g.dims[2]===i.kvNumHeads&&g.dims[3]===q)throw new Error("BSNH pastKey/pastValue is not supported");if(Y&&ne){if(g.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(m.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');E=g.dims[2]}else if(Y||ne)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let se=1;if(f&&f.dims.length>0){if(l.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(f.dims.length<3||f.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(l.dims[0]!==f.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(f.dims.length===3){if(l.dims[2]%f.dims[2]!==0)throw new Error('Dimension 2 of "query" should be a multiple of "key"');R=f.dims[1]}else if(f.dims.length===5){if(f.dims[2]!==i.numHeads||f.dims[3]!==2||f.dims[4]!==q)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(p)throw new Error('Expect "value" be none when "key" has packed kv format.');R=f.dims[1]}else{if(f.dims[1]!==i.numHeads||f.dims[3]!==q)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');R=f.dims[2]}}else{if(l.dims.length!==3&&l.dims.length!==5)throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(l.dims.length===5&&(l.dims[2]!==i.numHeads||l.dims[3]!==3))throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');se=3}let te=0,ye=!1,be=i.kvNumHeads?q*i.kvNumHeads:D;if(p&&p.dims.length>0){if(p.dims.length!==3&&p.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(l.dims[0]!==p.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(p.dims.length===3){if(R!==p.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');be=p.dims[2]}else{if(R!==p.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');be=p.dims[1]*p.dims[3],ye=!0}}let Ce=s.length>4?s[5]:void 0;if(Ce&&Ce.dims.length!==1&&Ce.dims[0]!==x)throw new Error('Input "seqlens" is expected to have 1 dimension and the same dim 0 as batch_size');return{batchSize:x,sequenceLength:P,pastSequenceLength:E,kvSequenceLength:R,totalSequenceLength:-1,maxSequenceLength:-1,inputHiddenSize:0,hiddenSize:D,vHiddenSize:be,headSize:q,vHeadSize:Math.floor(be/i.kvNumHeads),numHeads:i.numHeads,kvNumHeads:i.kvNumHeads,nReps:i.numHeads/i.kvNumHeads,pastPresentShareBuffer:!1,maskType:te,scale:i.scale,broadcastResPosBias:!1,passPastInKv:ye,qkvFormat:se}},Nh=Gt({perm:[0,2,1,3]}),Xu=(s,i,l)=>{let f=i,p=l.kvNumHeads;return i.dims.length===3&&l.kvSequenceLength!==0&&(f=i.reshape([l.batchSize,l.kvSequenceLength,p,l.headSize]),f=s.compute(qn(f,Nh.perm),{inputs:[f],outputs:[-1]})[0]),f},Qu=(s,i)=>{var ne;let l=Yu(s.inputs,i);if(s.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(((ne=s.inputs[1])==null?void 0:ne.dims.length)===5)throw new Error("Packed KV is not implemented");let f=s.inputs[0],p=s.inputs[1]&&s.inputs[1].dims.length>0?s.inputs[1]:void 0,g=s.inputs[2]&&s.inputs[2].dims.length>0?s.inputs[2]:void 0,m=s.inputs[3]&&s.inputs[3].dims.length!==0?s.inputs[3]:void 0,v=s.inputs[4]&&s.inputs[4].dims.length!==0?s.inputs[4]:void 0,x=s.inputs.length>4?s.inputs[5]:void 0,P=s.inputs.length>5?s.inputs[6]:void 0,D=l.kvNumHeads?l.kvNumHeads:l.numHeads,R=Gt({axis:2,numOutputs:3,splitSizes:[l.numHeads*l.headSize,D*l.headSize,D*l.headSize]}),[E,K,q]=!p&&!g?s.compute(eo([f],R),{inputs:[f],outputs:[-1,-1,-1]}):[f,p,g],Y=oi(s,l.batchSize,l.numHeads,l.sequenceLength,l.headSize,E,void 0,0);ti(s,Y,Xu(s,K,l),Xu(s,q,l),void 0,void 0,m,v,void 0,l,x,P)}}),Ju,el,Dh,Bh,um=c(()=>{Wt(),jt(),Vs(),or(),Ju=(s,i,l,f,p,g,m,v)=>{let x=sr(g),P=x===1?"f32":`vec${x}f`,D=x===1?"vec2f":`mat2x${x}f`,R=p*m,E=64;R===1&&(E=256);let K=[p,m,g/x],q=[p,m,2],Y=["rank","type","type"],ne=[];ne.push(...xt(K,q));let se=te=>{let ye=Qe("x",i.dataType,3,x),be=Qe("scale",l.dataType,l.dims),Ce=Qe("bias",f.dataType,f.dims),Be=Dt("output",1,3,2),je=[ye,be,Ce,Be];return` var workgroup_shared : array<${D}, ${E}>; const workgroup_size = ${E}u; ${te.declareVariables(...je)} ${te.mainStart(E)} let batch = workgroup_index / uniforms.x_shape[1]; let channel = workgroup_index % uniforms.x_shape[1]; let hight = uniforms.x_shape[2]; // initialize workgroup memory var sum = ${P}(0); var squared_sum = ${P}(0); for (var h = local_idx; h < hight; h += workgroup_size) { let value = ${P}(${ye.get("batch","channel","h")}); sum += value; squared_sum += value * value; } workgroup_shared[local_idx] = ${D}(sum, squared_sum); workgroupBarrier(); for (var currSize = workgroup_size >> 1; currSize > 0; currSize = currSize >> 1) { if (local_idx < currSize) { workgroup_shared[local_idx] = workgroup_shared[local_idx] + workgroup_shared[local_idx + currSize]; } workgroupBarrier(); } if (local_idx == 0) { let sum_final = ${_n("workgroup_shared[0][0]",x)} / f32(hight * ${x}); let squared_sum_final = ${_n("workgroup_shared[0][1]",x)} / f32(hight * ${x}); let inv_std_dev = inverseSqrt(squared_sum_final - sum_final * sum_final + f32(${v})); let channel_scale = inv_std_dev * f32(scale[channel]); let channel_shift = f32(bias[channel]) - sum_final * channel_scale; output[workgroup_index] = vec2f(channel_scale, channel_shift); } }`};return s.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${x};${v};${E}`,inputDependencies:Y},getRunData:()=>({outputs:[{dims:q,dataType:1}],dispatchGroup:{x:R},programUniforms:ne}),getShaderSource:se},{inputs:[i,l,f],outputs:[-1]})[0]},el=(s,i,l)=>{let f=i[0].dims,p=f,g=2,m=f[0],v=f[1],x=ze.sizeFromDimension(f,g),P=sr(x),D=ze.size(p)/P,R=Ju(s,i[0],i[1],i[2],m,x,v,l.epsilon),E=[m,v,x/P],K=[m,v],q=["type","none"],Y=ne=>{let se=Qe("x",i[0].dataType,E.length,P),te=Qe("scale_shift",1,K.length,2),ye=Dt("output",i[0].dataType,E.length,P),be=[se,te,ye];return` ${ne.registerUniform("output_size","u32").declareVariables(...be)} ${ne.mainStart()} ${ne.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let outputIndices = ${ye.offsetToIndices("global_idx")}; let batch = outputIndices[0]; let channel = outputIndices[1]; let scale_shift = ${te.getByIndices("vec2(batch, channel)")}; let value = ${se.getByOffset("global_idx")} * ${ye.type.value}(scale_shift.x) + ${ye.type.value}(scale_shift.y); ${ye.setByOffset("global_idx","value")}; }`};s.compute({name:"InstanceNormalization",shaderCache:{hint:`${P}`,inputDependencies:q},getRunData:()=>({outputs:[{dims:p,dataType:i[0].dataType}],dispatchGroup:{x:Math.ceil(D/64)},programUniforms:[{type:12,data:D},...xt(E,K,E)]}),getShaderSource:Y},{inputs:[i[0],R]})},Dh=(s,i,l)=>{let f=i[0].dims,p=f,g=f[0],m=f[f.length-1],v=ze.sizeFromDimension(f,1)/m,x=sr(m),P=ze.size(p)/x,D=[{type:12,data:v},{type:12,data:Math.floor(m/x)}],R=["type","type"],E=!1,K=[0,f.length-1];for(let se=0;sef[K[te]])),Y=Ju(s,q,i[1],i[2],g,v,m,l.epsilon),ne=se=>{let te=Ir(i[0].dataType),ye=x===1?"vec2f":`mat${x}x2f`,be=je=>{let tt=je===0?"x":"y",lt=x===1?"f32":`vec${x}f`;switch(x){case 1:return`${te}(${lt}(scale.${tt}))`;case 2:return`vec2<${te}>(${lt}(scale[0].${tt}, scale[1].${tt}))`;case 4:return`vec4<${te}>(${lt}(scale[0].${tt}, scale[1].${tt}, scale[2].${tt}, scale[3].${tt}))`;default:throw new Error(`Not supported compoents ${x}`)}},Ce=Qe("input",i[0].dataType,i[0].dims,x),Be=Dt("output",i[0].dataType,p,x);return` @group(0) @binding(0) var input : array<${Ce.type.storage}>; @group(0) @binding(1) var scale_input : array<${ye}>; @group(0) @binding(2) var output : array<${Be.type.storage}>; struct Uniforms {H: u32, C : u32}; @group(0) @binding(3) var uniforms: Uniforms; ${se.mainStart()} let current_image_number = global_idx / (uniforms.C * uniforms.H); let current_channel_number = global_idx % uniforms.C; let scale_offset = current_image_number * uniforms.C + current_channel_number; let scale = scale_input[scale_offset]; output[global_idx] = fma(input[global_idx], ${be(0)}, ${be(1)}); }`};s.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${x}`,inputDependencies:R},getRunData:()=>({outputs:[{dims:p,dataType:i[0].dataType}],dispatchGroup:{x:Math.ceil(P/64)},programUniforms:D}),getShaderSource:ne},{inputs:[i[0],Y]})},Bh=(s,i)=>{i.format==="NHWC"?Dh(s,s.inputs,i):el(s,s.inputs,i)}}),jh,zh,Uh,lm=c(()=>{Wt(),jt(),or(),jh=s=>{if(!s||s.length<2)throw new Error("layerNorm requires at least 2 inputs.")},zh=(s,i,l)=>{let f=i.simplified,p=s[0].dims,g=s[1],m=!f&&s[2],v=p,x=ze.normalizeAxis(i.axis,p.length),P=ze.sizeToDimension(p,x),D=ze.sizeFromDimension(p,x),R=ze.size(g.dims),E=m?ze.size(m.dims):0;if(R!==D||m&&E!==D)throw new Error(`Size of X.shape()[axis:] == ${D}. Size of scale and bias (if provided) must match this. Got scale size of ${R} and bias size of ${E}`);let K=[];for(let Ce=0;Ce1,te=l>2,ye=Ce=>{let Be=Ir(s[0].dataType),je=[Qe("x",s[0].dataType,s[0].dims,q),Qe("scale",g.dataType,g.dims,q)];m&&je.push(Qe("bias",m.dataType,m.dims,q)),je.push(Dt("output",s[0].dataType,v,q)),se&&je.push(Dt("mean_data_output",1,K)),te&&je.push(Dt("inv_std_output",1,K));let tt=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` ${Ce.registerUniforms(tt).declareVariables(...je)} ${Ce.mainStart()} ${Ce.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} let offset = global_idx * uniforms.norm_size_vectorized; var mean_vector = ${sn("f32",q)}; var mean_square_vector = ${sn("f32",q)}; for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { let value = ${Jr(Be,q,"x[h + offset]")}; mean_vector += value; mean_square_vector += value * value; } let mean = ${_n("mean_vector",q)} / uniforms.norm_size; let inv_std_dev = inverseSqrt(${_n("mean_square_vector",q)} / uniforms.norm_size ${f?"":"- mean * mean"} + uniforms.epsilon); for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { let f32input = ${Jr(Be,q,"x[j + offset]")}; let f32scale = ${Jr(Be,q,"scale[j]")}; output[j + offset] = ${je[0].type.value}((f32input ${f?"":"- mean"}) * inv_std_dev * f32scale ${m?`+ ${Jr(Be,q,"bias[j]")}`:""} ); } ${se?"mean_data_output[global_idx] = mean":""}; ${te?"inv_std_output[global_idx] = inv_std_dev":""}; }`},be=[{dims:v,dataType:s[0].dataType}];return se&&be.push({dims:K,dataType:1}),te&&be.push({dims:K,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${q};${l};${f}`,inputDependencies:Y},getRunData:()=>({outputs:be,dispatchGroup:{x:Math.ceil(P/64)},programUniforms:ne}),getShaderSource:ye}},Uh=(s,i)=>{jh(s.inputs),s.compute(zh(s.inputs,i,s.outputCount))}}),Vh,Wh,Gh=c(()=>{jt(),Eu(),Cu(),Vh=s=>{if(!s||s.length!==2)throw new Error("MatMul requires 2 inputs.");if(s[0].dims[s[0].dims.length-1]!==s[1].dims[s[1].dims.length-2])throw new Error("shared dimension does not match.")},Wh=s=>{Vh(s.inputs);let i=mn.calcShape(s.inputs[0].dims,s.inputs[1].dims,!0);if(!i)throw new Error("Can't use matmul on the given tensors");let l=i[i.length-1],f=s.inputs[0].dims[s.inputs[0].dims.length-1];if(l<8&&f<8)s.compute(vu(s.inputs,{activation:""},i));else{let p=i[i.length-2],g=ze.size(s.inputs[0].dims.slice(0,-2)),m=ze.size(s.inputs[1].dims.slice(0,-2));if(g!==1&&p===1&&m===1){let v=s.inputs[0].reshape([1,g,f]),x=s.inputs[1].reshape([1,f,l]),P=[1,g,l],D=[v,x];s.compute(Vi(D,{activation:""},i,P),{inputs:D})}else s.compute(Vi(s.inputs,{activation:""},i))}}}),Hh,Kh,tl,qh,Zh,Fr=c(()=>{Wt(),jt(),mr(),or(),Hh=(s,i)=>{if(s.length<3||s.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let l=s[0],f=l.dims.length;if(l.dims[f-1]!==i.k)throw new Error("The last dim of input shape does not match the k value");let p=Math.floor((i.k+i.blockSize-1)/i.blockSize),g=i.blockSize/8*i.bits,m=s[1];if(!ze.areEqual(m.dims,[i.n,p,g]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let v=s[2].dims;if(ze.size(v)!==i.n*p)throw new Error("scales input size error.");if(s.length===4){let x=s[3].dims,P=i.bits>4?i.n*p:i.n*Math.floor((p+1)/2);if(ze.size(x)!==P)throw new Error("zeroPoints input size error.")}},Kh=(s,i)=>{let l=s[0].dims,f=l.length,p=l[f-2],g=i.k,m=i.n,v=l.slice(0,f-2),x=ze.size(v),P=s[1].dims[2]/4,D=s[0].dataType,R=sr(i.k),E=sr(P),K=sr(m),q=v.concat([p,m]),Y=p>1&&m/K%2===0?2:1,ne=ze.size(q)/K/Y,se=64,te=[],ye=[x,p,g/R],be=ze.convertShape(s[1].dims).slice();be.splice(-1,1,P/E),te.push(...xt(ye)),te.push(...xt(be)),te.push(...xt(s[2].dims)),s.length===4&&te.push(...xt(ze.convertShape(s[3].dims)));let Ce=[x,p,m/K];te.push(...xt(Ce));let Be=je=>{let tt=ye.length,lt=Qe("a",s[0].dataType,tt,R),kt=Qe("b",12,be.length,E),ir=Qe("scales",s[2].dataType,s[2].dims.length),cr=[lt,kt,ir],Pt=s.length===4?Qe("zero_points",12,s[3].dims.length):void 0;Pt&&cr.push(Pt);let pr=Ce.length,Rt=Dt("output",s[0].dataType,pr,K),zt=Ir(s[0].dataType),Br=(()=>{switch(R){case 1:return`array<${zt}, 8>`;case 2:return`mat4x2<${zt}>`;case 4:return`mat2x4<${zt}>`;default:throw new Error(`${R}-component is not supported.`)}})(),rr=()=>{let ut=` // reuse a data var input_offset = ${lt.indicesToOffset(`${lt.type.indices}(batch, row, word_offset)`)}; var a_data: ${Br}; for (var j: u32 = 0; j < ${8/R}; j++) { a_data[j] = ${lt.getByOffset("input_offset")}; input_offset++; } `;for(let It=0;It> 4) & b_mask); b_quantized_values = ${Br}(${Array.from({length:4},(Sr,ln)=>`${zt}(b_value_lower[${ln}]), ${zt}(b_value_upper[${ln}])`).join(", ")}); b_dequantized_values = ${R===1?`${Br}(${Array.from({length:8},(Sr,ln)=>`(b_quantized_values[${ln}] - ${Pt?`zero_point${It}`:"zero_point"}) * scale${It}`).join(", ")});`:`(b_quantized_values - ${Br}(${Array(8).fill(`${Pt?`zero_point${It}`:"zero_point"}`).join(",")})) * scale${It};`}; workgroup_shared[local_id.x * ${Y} + ${Math.floor(It/K)}]${K>1?`[${It%K}]`:""} += ${Array.from({length:8/R},(Sr,ln)=>`${R===1?`a_data[${ln}] * b_dequantized_values[${ln}]`:`dot(a_data[${ln}], b_dequantized_values[${ln}])`}`).join(" + ")}; `;return ut},Kt=()=>{let ut=` var col_index = col * ${K}; ${Pt?` let zero_point_bytes_per_col = (nBlocksPerCol + 1) / 2; var zero_point_byte_count: u32; var zero_point_word_index: u32; var zero_point_byte_offset: u32; let zero_point_nibble_offset: u32 = block & 0x1u; var zero_point_bits_offset: u32; var zero_point_word: u32;`:` // The default zero point is 8 for unsigned 4-bit quantization. let zero_point = ${zt}(8);`} `;for(let It=0;It> 0x1u); zero_point_word_index = zero_point_byte_count >> 0x2u; zero_point_byte_offset = zero_point_byte_count & 0x3u; zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); zero_point_word = ${Pt.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; let zero_point${It} = ${zt}((zero_point_word) & 0xFu);`:""} col_index += 1;`;return ut},Or=()=>{let ut=`col_index = col * ${K};`;for(let It=0;It; var b_value_upper: vec4; var b_quantized_values: ${Br}; var b_dequantized_values: ${Br};`,ut};return` var workgroup_shared: array<${Rt.type.value}, ${Y*se}>; ${je.declareVariables(...cr,Rt)} ${je.mainStart([se,1,1])} let output_indices = ${Rt.offsetToIndices(`(global_idx / ${se}) * ${Y}`)}; let col = output_indices[2]; let row = output_indices[1]; let batch = output_indices[0]; let nBlocksPerCol = uniforms.b_shape[1]; for (var block = local_id.x; block < nBlocksPerCol; block += ${se}) { //process one block var word_offset: u32 = block * ${i.blockSize/R}; ${Kt()} for (var word: u32 = 0; word < ${P}; word += ${E}) { ${Or()} for (var i: u32 = 0; i < ${E}; i++) { ${rr()} word_offset += ${8/R}; } } } workgroupBarrier(); if (local_id.x < ${Y}) { var output_value: ${Rt.type.value} = ${Rt.type.value}(0); var workgroup_shared_offset: u32 = local_id.x; for (var b: u32 = 0u; b < ${se}u; b++) { output_value += workgroup_shared[workgroup_shared_offset]; workgroup_shared_offset += ${Y}; } ${Rt.setByIndices(`${Rt.type.indices}(batch, row, col + local_id.x)`,"output_value")}; } }`};return{name:"MatMulNBits",shaderCache:{hint:`${i.blockSize};${i.bits};${R};${E};${K};${Y};${se}`,inputDependencies:Array(s.length).fill("rank")},getRunData:()=>({outputs:[{dims:q,dataType:D}],dispatchGroup:{x:ne},programUniforms:te}),getShaderSource:Be}},tl=(s,i)=>{let l=s[0].dims,f=l.length,p=l[f-2],g=i.k,m=i.n,v=l.slice(0,f-2),x=ze.size(v),P=s[1].dims[2]/4,D=s[0].dataType,R=sr(i.k),E=sr(P),K=v.concat([p,m]),q=128,Y=m%8===0?8:m%4===0?4:1,ne=q/Y,se=ne*E*8,te=se/R,ye=se/i.blockSize,be=ze.size(K)/Y,Ce=[],Be=[x,p,g/R],je=ze.convertShape(s[1].dims).slice();je.splice(-1,1,P/E),Ce.push(...xt(Be)),Ce.push(...xt(je)),Ce.push(...xt(s[2].dims)),s.length===4&&Ce.push(...xt(ze.convertShape(s[3].dims)));let tt=[x,p,m];Ce.push(...xt(tt));let lt=kt=>{let ir=Be.length,cr=Qe("a",s[0].dataType,ir,R),Pt=Qe("b",12,je.length,E),pr=Qe("scales",s[2].dataType,s[2].dims.length),Rt=[cr,Pt,pr],zt=s.length===4?Qe("zero_points",12,s[3].dims.length):void 0;zt&&Rt.push(zt);let Br=tt.length,rr=Dt("output",s[0].dataType,Br),Kt=Ir(s[0].dataType),Or=()=>{switch(R){case 1:return` let a_data0 = vec4<${Kt}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]); let a_data1 = vec4<${Kt}>(sub_a[word_offset + 4], sub_a[word_offset + 5], sub_a[word_offset + 6], sub_a[word_offset + 7]);`;case 2:return` let a_data0 = vec4<${Kt}>(sub_a[word_offset], sub_a[word_offset + 1]); let a_data1 = vec4<${Kt}>(sub_a[word_offset + 2], sub_a[word_offset + 3]);`;case 4:return` let a_data0 = sub_a[word_offset]; let a_data1 = sub_a[word_offset + 1];`;default:throw new Error(`${R}-component is not supported.`)}};return` var sub_a: array<${cr.type.value}, ${te}>; var inter_results: array, ${Y}>; ${kt.declareVariables(...Rt,rr)} ${kt.mainStart([ne,Y,1])} let output_indices = ${rr.offsetToIndices(`workgroup_index * ${Y}`)}; let col = output_indices[2]; let row = output_indices[1]; let batch = output_indices[0]; let n_blocks_per_col = uniforms.b_shape[1]; let num_tiles = (n_blocks_per_col - 1) / ${ye} + 1; // Loop over shared dimension. for (var tile: u32 = 0; tile < num_tiles; tile += 1) { let a_col_start = tile * ${te}; // load one tile A data into shared memory. for (var a_offset = local_idx; a_offset < ${te}; a_offset += ${q}) { let a_col = a_col_start + a_offset; if (a_col < uniforms.a_shape[2]) { sub_a[a_offset] = ${cr.getByIndices(`${cr.type.indices}(batch, row, a_col)`)}; } else { sub_a[a_offset] = ${cr.type.value}(0); } } workgroupBarrier(); // each thread process one block let b_row = col + local_id.y; let block = tile * ${ye} + local_id.x; ${zt?` let zero_point_bytes_per_col = (n_blocks_per_col + 1) / 2; let zero_point_byte_count = b_row * zero_point_bytes_per_col + (block >> 0x1u); let zero_point_word_index = zero_point_byte_count >> 0x2u; let zero_point_byte_offset = zero_point_byte_count & 0x3u; let zero_point_nibble_offset: u32 = block & 0x1u; let zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); let zero_point_word = ${zt.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; let zero_point = ${Kt}((zero_point_word) & 0xFu);`:` // The default zero point is 8 for unsigned 4-bit quantization. let zero_point = ${Kt}(8);`} let scale = ${pr.getByOffset("b_row * n_blocks_per_col + block")}; let b_data = ${Pt.getByIndices(`${Pt.type.indices}(b_row, block, 0)`)}; var word_offset = local_id.x * ${i.blockSize/R}; for (var i: u32 = 0; i < ${E}; i++) { ${Or()} let b_value = ${E===1?"b_data":"b_data[i]"}; let b_value_lower = unpack4xU8(b_value & 0x0F0F0F0Fu); let b_value_upper = unpack4xU8((b_value >> 4) & 0x0F0F0F0Fu); let b_quantized_values = mat2x4<${Kt}>(${Array.from({length:4},(ut,It)=>`${Kt}(b_value_lower[${It}]), ${Kt}(b_value_upper[${It}])`).join(", ")}); let b_dequantized_values = (b_quantized_values - mat2x4<${Kt}>(${Array(8).fill("zero_point").join(",")})) * scale; inter_results[local_id.y][local_id.x] += ${Array.from({length:2},(ut,It)=>`${`dot(a_data${It}, b_dequantized_values[${It}])`}`).join(" + ")}; word_offset += ${8/R}; } workgroupBarrier(); } if (local_idx < ${Y}) { var output_value: ${rr.type.value} = ${rr.type.value}(0); for (var b = 0u; b < ${ne}; b++) { output_value += inter_results[local_idx][b]; } if (col + local_idx < uniforms.output_shape[2]) { ${rr.setByIndices(`${rr.type.indices}(batch, row, col + local_idx)`,"output_value")} } } }`};return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${i.blockSize};${R};${E};${ne};${Y}`,inputDependencies:Array(s.length).fill("rank")},getRunData:()=>({outputs:[{dims:K,dataType:D}],dispatchGroup:{x:be},programUniforms:Ce}),getShaderSource:lt}},qh=(s,i)=>{Hh(s.inputs,i),i.blockSize===32&&s.adapterInfo.isVendor("intel")&&s.adapterInfo.isArchitecture("gen-12lp")?s.compute(tl(s.inputs,i)):s.compute(Kh(s.inputs,i))},Zh=s=>Gt(s)}),cm,dm,hm,rl,Yh,Xh,Qh,Jh,nl,ef=c(()=>{Wt(),jt(),or(),cm=s=>{if(!s||s.length<1)throw new Error("Too few inputs");if(s[0].dataType!==1&&s[0].dataType!==10)throw new Error("Input type must be float or float16.");if(s.length>=2){let i=s[0].dims.length*2===s[1].dims[0];if(s.length===4&&(i=s[3].dims[0]*2===s[1].dims[0]),!i)throw new Error("The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes].")}},dm=(s,i,l)=>{let f="";for(let p=i-1;p>=0;--p)f+=` k = i32(${s.indicesGet("indices",p)}) - ${Ft("uniforms.pads",p,l)}; if (k < 0) { break; } if (k >= i32(${Ft("uniforms.x_shape",p,i)})) { break; } offset += k * i32(${Ft("uniforms.x_strides",p,i)}); `;return` value = ${s.type.value}(uniforms.constant_value); for (var i = 0; i < 1; i++) { var offset = 0; var k = 0; ${f} value = x[offset]; } `},hm=(s,i,l)=>{let f="";for(let p=i-1;p>=0;--p)f+=` k = i32(${s.indicesGet("indices",p)}) - ${Ft("uniforms.pads",p,l)}; if (k < 0) { k = -k; } { let _2n_1 = 2 * (i32(${Ft("uniforms.x_shape",p,i)}) - 1); k = k % _2n_1; if(k >= i32(${Ft("uniforms.x_shape",p,i)})) { k = _2n_1 - k; } } offset += k * i32(${Ft("uniforms.x_strides",p,i)}); `;return` var offset = 0; var k = 0; ${f} value = x[offset]; `},rl=(s,i,l)=>{let f="";for(let p=i-1;p>=0;--p)f+=` k = i32(${s.indicesGet("indices",p)}) - ${Ft("uniforms.pads",p,l)}; if (k < 0) { k = 0; } if (k >= i32(${Ft("uniforms.x_shape",p,i)})) { k = i32(${Ft("uniforms.x_shape",p,i)}) - 1; } offset += k * i32(${Ft("uniforms.x_strides",p,i)}); `;return` var offset = 0; var k = 0; ${f} value = x[offset]; `},Yh=(s,i,l)=>{let f="";for(let p=i-1;p>=0;--p)f+=` k = i32(${s.indicesGet("indices",p)}) - ${Ft("uniforms.pads",p,l)}; if (k < 0) { k += i32(${Ft("uniforms.x_shape",p,i)}]); } if (k >= i32(${Ft("uniforms.x_shape",p,i)})) { k -= i32(${Ft("uniforms.x_shape",p,i)}); } offset += k * i32(${Ft("uniforms.x_strides",p,i)}); `;return` var offset = 0; var k = 0; ${f} value = x[offset]; `},Xh=(s,i,l)=>{switch(l.mode){case 0:return dm(s,i,l.pads.length);case 1:return hm(s,i,l.pads.length);case 2:return rl(s,i,l.pads.length);case 3:return Yh(s,i,l.pads.length);default:throw new Error("Invalid mode")}},Qh=(s,i)=>{let l=ze.padShape(s[0].dims.slice(),i.pads),f=s[0].dims,p=ze.size(l),g=[{type:12,data:p},{type:6,data:i.pads}],m=s.length>=3&&s[2].data;i.mode===0&&g.push({type:m?s[2].dataType:1,data:i.value}),g.push(...xt(s[0].dims,l));let v=["rank"],x=P=>{let D=Dt("output",s[0].dataType,l.length),R=Qe("x",s[0].dataType,f.length),E=R.type.value,K=Xh(D,f.length,i),q=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:i.pads.length}];return i.mode===0&&q.push({name:"constant_value",type:m?E:"f32"}),` ${P.registerUniforms(q).declareVariables(R,D)} ${P.mainStart()} ${P.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${D.offsetToIndices("global_idx")}; var value = ${E}(0); ${K} output[global_idx] = value; }`};return{name:"Pad",shaderCache:{hint:`${i.mode}${m}`,inputDependencies:v},getRunData:()=>({outputs:[{dims:l,dataType:s[0].dataType}],dispatchGroup:{x:Math.ceil(ze.size(l)/64)},programUniforms:g}),getShaderSource:x}},Jh=(s,i)=>{if(s.length>1){let l=s[1].getBigInt64Array(),f=s.length>=3&&s[2].data?s[2].dataType===10?s[2].getUint16Array()[0]:s[2].getFloat32Array()[0]:0,p=s[0].dims.length,g=new Int32Array(2*p).fill(0);if(s.length>=4){let v=s[3].getBigInt64Array();for(let x=0;xg[Number(x)]=Number(v));let m=[];return g.forEach(v=>m.push(v)),{mode:i.mode,value:f,pads:m}}else return i},nl=(s,i)=>{cm(s.inputs);let l=Jh(s.inputs,i);s.compute(Qh(s.inputs,l),{inputs:[0]})}}),to,sl,al,ro,tf,fm,rf,il,ol,nf,sf,ul,af,of,ll,uf,lf,cf,pm,mm=c(()=>{Ze(),Wt(),jt(),or(),to=s=>{if(j.webgpu.validateInputContent&&(!s||s.length!==1))throw new Error("Pool ops requires 1 input.")},sl=(s,i,l)=>{let f=i.format==="NHWC",p=s.dims.slice();f&&p.splice(1,0,p.pop());let g=Object.hasOwnProperty.call(i,"dilations"),m=i.kernelShape.slice(),v=i.strides.slice(),x=g?i.dilations.slice():[],P=i.pads.slice();xn.adjustPoolAttributes(l,p,m,v,x,P);let D=xn.computePoolOutputShape(l,p,v,x,m,P,i.autoPad),R=Object.assign({},i);g?Object.assign(R,{kernelShape:m,strides:v,pads:P,dilations:x,cacheKey:i.cacheKey}):Object.assign(R,{kernelShape:m,strides:v,pads:P,cacheKey:i.cacheKey});let E=D.slice();return E.push(E.splice(1,1)[0]),[R,f?E:D]},al=(s,i)=>{let l=i.format==="NHWC",f=ze.size(s),p=ze.size(i.kernelShape),g=[{type:12,data:f},{type:12,data:p}],m=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(i.kernelShape.length<=2){let v=i.kernelShape[i.kernelShape.length-1],x=i.strides[i.strides.length-1],P=i.pads[i.pads.length/2-1],D=i.pads[i.pads.length-1],R=!!(P+D);g.push({type:12,data:v},{type:12,data:x},{type:12,data:P},{type:12,data:D}),m.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let E=!1;if(i.kernelShape.length===2){let K=i.kernelShape[i.kernelShape.length-2],q=i.strides[i.strides.length-2],Y=i.pads[i.pads.length/2-2],ne=i.pads[i.pads.length-2];E=!!(Y+ne),g.push({type:12,data:K},{type:12,data:q},{type:12,data:Y},{type:12,data:ne}),m.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[g,m,!0,R,E]}else{if(l)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let v=ze.computeStrides(i.kernelShape);g.push({type:12,data:v},{type:12,data:i.pads},{type:12,data:i.strides}),m.push({name:"kernelStrides",type:"u32",length:v.length},{name:"pads",type:"u32",length:i.pads.length},{name:"strides",type:"u32",length:i.strides.length});let x=i.pads.reduce((P,D)=>P+D);return[g,m,!!x,!1,!1]}},ro=(s,i,l,f,p,g,m,v,x,P,D,R)=>{let E=p.format==="NHWC",K=i.type.value,q=Dt("output",i.type.tensor,f);if(p.kernelShape.length<=2){let Y="",ne="",se="",te=l-(E?2:1);if(D?Y=` for (var i: u32 = 0u; i < uniforms.kw; i++) { xIndices[${te}] = indices[${te}] * uniforms.sw - uniforms.pwStart + i; if (xIndices[${te}] < 0 || xIndices[${te}] >= uniforms.x_shape[${te}]) { pad++; continue; } let x_val = x[${i.indicesToOffset("xIndices")}]; ${g} }`:Y=` for (var i: u32 = 0u; i < uniforms.kw; i++) { xIndices[${te}] = indices[${te}] * uniforms.sw - uniforms.pwStart + i; let x_val = x[${i.indicesToOffset("xIndices")}]; ${g} }`,p.kernelShape.length===2){let ye=l-(E?3:2);R?ne=` for (var j: u32 = 0u; j < uniforms.kh; j++) { xIndices[${ye}] = indices[${ye}] * uniforms.sh - uniforms.phStart + j; if (xIndices[${ye}] < 0 || xIndices[${ye}] >= uniforms.x_shape[${ye}]) { pad += i32(uniforms.kw); continue; } `:ne=` for (var j: u32 = 0u; j < uniforms.kh; j++) { xIndices[${ye}] = indices[${ye}] * uniforms.sh - uniforms.phStart + j; `,se=` } `}return` ${s.registerUniforms(x).declareVariables(i,q)} ${s.mainStart()} ${s.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let indices = ${q.offsetToIndices("global_idx")}; var xIndices = ${q.offsetToIndices("global_idx")}; var value = ${K}(${v}); var pad = 0; ${ne} ${Y} ${se} ${m} output[global_idx] = value; }`}else{if(E)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let Y=p.kernelShape.length,ne=p.pads.length,se="";return P?se=` if (xIndices[j] >= uniforms.x_shape[j]) { pad++; isPad = true; break; } } if (!isPad) { let x_val = x[${i.indicesToOffset("xIndices")}]; ${g} }`:se=` } let x_val = x[${i.indicesToOffset("xIndices")}]; ${g} `,` ${s.registerUniforms(x).declareVariables(i,q)} ${s.mainStart()} ${s.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let indices = ${q.offsetToIndices("global_idx")}; var xIndices = ${q.offsetToIndices("global_idx")}; var offsets: array; var value = ${K}(${v}); var pad = 0; var isPad = false; for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { var offset = i; for (var j = 0u; j < ${Y-1}u; j++) { offsets[j] = offset / ${Ft("uniforms.kernelStrides","j",Y)}; offset -= offsets[j] * ${Ft("uniforms.kernelStrides","j",Y)}; } offsets[${Y-1}] = offset; isPad = false; for (var j = ${l-Y}u; j < ${l}u; j++) { xIndices[j] = indices[j] * ${Ft("uniforms.strides",`j - ${l-Y}u`,Y)} + offsets[j - ${l-Y}u] - ${Ft("uniforms.pads","j - 2u",ne)}; ${se} } ${m} output[global_idx] = value; }`}},tf=s=>`${s.format};${s.ceilMode};${s.autoPad};${s.kernelShape.length}`,fm=s=>`${tf(s)};${s.countIncludePad}`,rf=s=>`${tf(s)};${s.storageOrder};${s.dilations}`,il=s=>({format:s.format,autoPad:["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][s.auto_pad],ceilMode:s.ceil_mode,kernelShape:s.kernel_shape,strides:s.strides,pads:s.pads}),ol=(s,i,l,f)=>{let[p,g]=sl(i,f,l),m=Qe("x",i.dataType,i.dims.length),v=m.type.value,x="value += x_val;",P="";p.countIncludePad?P+=`value /= ${v}(uniforms.kernelSize);`:P+=`value /= ${v}(i32(uniforms.kernelSize) - pad);`;let[D,R,E,K,q]=al(g,p);D.push(...xt(i.dims,g));let Y=["rank"];return{name:s,shaderCache:{hint:`${f.cacheKey};${E};${K};${q}`,inputDependencies:Y},getRunData:()=>({outputs:[{dims:g,dataType:i.dataType}],dispatchGroup:{x:Math.ceil(ze.size(g)/64)},programUniforms:D}),getShaderSource:ne=>ro(ne,m,i.dims.length,g.length,p,x,P,0,R,E,K,q)}},nf=s=>{let i=s.count_include_pad!==0,l=il(s);if(l.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let f={countIncludePad:i,...l,cacheKey:""};return{...f,cacheKey:fm(f)}},sf=(s,i)=>{to(s.inputs),s.compute(ol("AveragePool",s.inputs[0],!1,i))},ul={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},af=s=>{let i=s.format;return{format:i,...ul,cacheKey:i}},of=(s,i)=>{to(s.inputs),s.compute(ol("GlobalAveragePool",s.inputs[0],!0,i))},ll=(s,i,l,f)=>{let[p,g]=sl(i,f,l),m=` value = max(x_val, value); `,v="",x=Qe("x",i.dataType,i.dims.length),P=["rank"],[D,R,E,K,q]=al(g,p);return D.push(...xt(i.dims,g)),{name:s,shaderCache:{hint:`${f.cacheKey};${E};${K};${q}`,inputDependencies:P},getRunData:()=>({outputs:[{dims:g,dataType:i.dataType}],dispatchGroup:{x:Math.ceil(ze.size(g)/64)},programUniforms:D}),getShaderSource:Y=>ro(Y,x,i.dims.length,g.length,p,m,v,i.dataType===10?-65504:-1e5,R,E,K,q)}},uf=(s,i)=>{to(s.inputs),s.compute(ll("MaxPool",s.inputs[0],!1,i))},lf=s=>{let i=s.storage_order,l=s.dilations,f=il(s);if(i!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(f.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let p={storageOrder:i,dilations:l,...f,cacheKey:""};return{...p,cacheKey:rf(p)}},cf=s=>{let i=s.format;return{format:i,...ul,cacheKey:i}},pm=(s,i)=>{to(s.inputs),s.compute(ll("GlobalMaxPool",s.inputs[0],!0,i))}}),df,hf,ff,pf,_m=c(()=>{Wt(),jt(),mr(),or(),df=(s,i)=>{if(s.length<2||s.length>3)throw new Error("DequantizeLinear requires 2 or 3 inputs.");if(s.length===3&&s[1].dims===s[2].dims)throw new Error("x-scale and x-zero-point must have the same shape.");if(s.length===3&&s[0].dataType!==s[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(s[0].dataType===6&&s.length>2)throw new Error("In the case of dequantizing int32 there is no zero point.");if(s[1].dims.length!==0&&s[1].dims.length!==1&&s[1].dims.length!==s[0].dims.length)throw new Error("scale input must be a scalar, a 1D tensor, or have the same rank as the input tensor.");if(s.length>2){if(s[0].dataType!==s[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(s[1].dims.length!==s[2].dims.length)throw new Error("scale and zero-point inputs must have the same rank.");if(!s[1].dims.map((l,f)=>l===s[2].dims[f]).reduce((l,f)=>l&&f,!0))throw new Error("scale and zero-point inputs must have the same shape.")}if(i.blockSize>0){if(s[1].dims.length===0||s[1].dims.length===1&&s[1].dims[0]===1)throw new Error("blockSize must be set only for block quantization.");if(!s[1].dims.map((p,g)=>g===i.axis||p===s[0].dims[g]).reduce((p,g)=>p&&g,!0))throw new Error("For block qunatization, scale input shape to match the input shape except for the axis");if(s[1].dims.length!==s[0].dims.length)throw new Error("For block qunatization the scale input rank must be the same as the x rank.");let l=s[0].dims[i.axis],f=s[1].dims[i.axis];if(i.blockSizeMath.ceil(l/(f-1)-1))throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].")}},hf=(s,i)=>{let l=ze.normalizeAxis(i.axis,s[0].dims.length),f=s[0].dataType,p=f===3,g=s[0].dims,m=s[1].dataType,v=ze.size(g),x=f===3||f===2,P=x?[Math.ceil(ze.size(s[0].dims)/4)]:s[0].dims,D=s[1].dims,R=s.length>2?s[2]:void 0,E=R?x?[Math.ceil(ze.size(R.dims)/4)]:R.dims:void 0,K=D.length===0||D.length===1&&D[0]===1,q=K===!1&&D.length===1,Y=sr(v),ne=K&&(!x||Y===4),se=ne?Y:1,te=ne&&!x?Y:1,ye=Qe("input",x?12:f,P.length,te),be=Qe("scale",m,D.length),Ce=R?Qe("zero_point",x?12:f,E.length):void 0,Be=Dt("output",m,g.length,se),je=[ye,be];Ce&&je.push(Ce);let tt=[P,D];R&&tt.push(E);let lt=[{type:12,data:v/se},{type:12,data:l},{type:12,data:i.blockSize},...xt(...tt,g)],kt=ir=>{let cr=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return` ${ir.registerUniforms(cr).declareVariables(...je,Be)} ${ir.mainStart()} ${ir.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let output_indices = ${Be.offsetToIndices("global_idx")}; // Set input x ${x?` let input = ${ye.getByOffset("global_idx / 4")}; let x_vec = ${p?"unpack4xI8(input)":"unpack4xU8(input)"}; let x_value = ${se===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${ye.getByOffset("global_idx")};`}; // Set scale input ${K?`let scale_value= ${be.getByOffset("0")}`:q?` let scale_index = ${Be.indicesGet("output_indices","uniforms.axis")}; let scale_value= ${be.getByOffset("scale_index")};`:` var scale_indices: ${be.type.indices} = output_indices; let index = ${be.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size; ${be.indicesSet("scale_indices","uniforms.axis","index")}; let scale_value= ${be.getByIndices("scale_indices")};`}; // Set zero-point input ${Ce?K?x?` let zero_point_input = ${Ce.getByOffset("0")}; let zero_point_vec = ${p?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${Ce.getByOffset("0")}`:q?x?` let zero_point_index = ${Be.indicesGet("output_indices","uniforms.axis")}; let zero_point_input = ${Ce.getByOffset("zero_point_index / 4")}; let zero_point_vec = ${p?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; let zero_point_value = zero_point_vec[zero_point_index % 4]`:` let zero_point_index = ${Be.indicesGet("output_indices","uniforms.axis")}; let zero_point_value = ${Ce.getByOffset("zero_point_index")};`:x?` let zero_point_offset = ${be.indicesToOffset("scale_indices")}; let zero_point_input = ${Ce.getByOffset("zero_point_offset / 4")}; let zero_point_vec = ${p?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${Ce.getByIndices("scale_indices")};`:`let zero_point_value = ${x?p?"i32":"u32":ye.type.value}(0);`}; // Compute and write output ${Be.setByOffset("global_idx",`${Be.type.value}(x_value - zero_point_value) * scale_value`)}; }`};return{name:"DequantizeLinear",shaderCache:{hint:i.cacheKey,inputDependencies:Ce?["rank","rank","rank"]:["rank","rank"]},getShaderSource:kt,getRunData:()=>({outputs:[{dims:g,dataType:m}],dispatchGroup:{x:Math.ceil(v/se/64),y:1,z:1},programUniforms:lt})}},ff=(s,i)=>{df(s.inputs,i),s.compute(hf(s.inputs,i))},pf=s=>Gt({axis:s.axis,blockSize:s.blockSize})}),gm,cl,mf,bm=c(()=>{Ze(),Wt(),or(),gm=(s,i,l)=>{let f=s===i,p=si&&l>0;if(f||p||g)throw new Error("Range these inputs' contents are invalid.")},cl=(s,i,l,f)=>{let p=Math.abs(Math.ceil((i-s)/l)),g=[p],m=p,v=[{type:12,data:m},{type:f,data:s},{type:f,data:l},...xt(g)],x=P=>{let D=Dt("output",f,g.length),R=D.type.value,E=[{name:"outputSize",type:"u32"},{name:"start",type:R},{name:"delta",type:R}];return` ${P.registerUniforms(E).declareVariables(D)} ${P.mainStart()} ${P.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} output[global_idx] = uniforms.start + ${R}(global_idx) * uniforms.delta; }`};return{name:"Range",shaderCache:{hint:`${f}`},getShaderSource:x,getRunData:()=>({outputs:[{dims:g,dataType:f}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:v})}},mf=s=>{let i=0,l=0,f=0;s.inputs[0].dataType===6?(i=s.inputs[0].getInt32Array()[0],l=s.inputs[1].getInt32Array()[0],f=s.inputs[2].getInt32Array()[0]):s.inputs[0].dataType===1&&(i=s.inputs[0].getFloat32Array()[0],l=s.inputs[1].getFloat32Array()[0],f=s.inputs[2].getFloat32Array()[0]),j.webgpu.validateInputContent&&gm(i,l,f),s.compute(cl(i,l,f,s.inputs[0].dataType),{inputs:[]})}}),_f,gf,bf,yf,ym=c(()=>{Wt(),jt(),mr(),or(),_f=(s,i,l,f)=>{if(s!=="none"&&f!=="i32"&&f!=="u32"&&f!=="f32")throw new Error(`Input ${f} is not supported with reduction ${s}.`);let p=`{ var oldValue = 0; loop { let newValueF32 =`,g=`; let newValue = bitcast(newValueF32); let res = atomicCompareExchangeWeak(&${i}, oldValue, newValue); if res.exchanged { break; } oldValue = res.old_value; } }`;switch(s){case"none":return`${i}=${l};`;case"add":return f==="i32"||f==="u32"?`atomicAdd(&${i}, bitcast<${f}>(${l}));`:` ${p}bitcast<${f}>(oldValue) + (${l})${g}`;case"max":return f==="i32"||f==="u32"?`atomicMax(&${i}, bitcast<${f}>(${l}));`:` ${p}max(bitcast(oldValue), (${l}))${g}`;case"min":return f==="i32"||f==="u32"?`atomicMin(&${i}, bitcast<${f}>(${l}));`:`${p}min(bitcast<${f}>(oldValue), (${l}))${g}`;case"mul":return`${p}(bitcast<${f}>(oldValue) * (${l}))${g}`;default:throw new Error(`Reduction ${s} is not supported.`)}},gf=(s,i)=>{let l=s[0].dims,f=s[1].dims,p=l,g=1,m=Math.ceil(ze.size(f)/g),v=f[f.length-1],x=ze.sizeFromDimension(l,v),P=[{type:12,data:m},{type:12,data:v},{type:12,data:x},...xt(s[1].dims,s[2].dims,p)],D=R=>{let E=Qe("indices",s[1].dataType,s[1].dims.length),K=Qe("updates",s[2].dataType,s[2].dims.length,g),q=i.reduction!=="none"&&i.reduction!==""?Hl("output",s[0].dataType,p.length):Dt("output",s[0].dataType,p.length,g);return` ${R.registerUniform("output_size","u32").registerUniform("last_index_dimension","u32").registerUniform("num_updates_elements","u32").declareVariables(E,K,q)} ${R.mainStart()} ${R.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} var data_offset = 0u; let indices_start = uniforms.last_index_dimension * global_idx; let indices_end = indices_start + uniforms.last_index_dimension; for (var i = indices_start; i < indices_end; i++) { var index = i32(indices[i].x); ${s[0].dims.length===1?` let element_count_dim = uniforms.output_strides; let dim_value = uniforms.output_shape;`:` let element_count_dim = uniforms.output_strides[i - indices_start]; let dim_value = uniforms.output_shape[i - indices_start + uniforms.last_index_dimension];`} if (index >= 0) { if (index >= i32(dim_value)) { index = i32(dim_value - 1); } } else { if (index < -i32(dim_value)) { index = 0; } else { index += i32(dim_value); } } data_offset += u32((u32(index) * element_count_dim)); } for (var i = 0u; i < uniforms.num_updates_elements; i++) { let value = updates[uniforms.num_updates_elements * global_idx + i]; ${_f(i.reduction,"output[data_offset + i]","value",q.type.value)} } }`};return{name:"ScatterND",shaderCache:{hint:`${i.cacheKey}_${i.reduction}`,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:p,dataType:s[0].dataType}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:P}),getShaderSource:D}},bf=s=>Gt({reduction:s.reduction}),yf=(s,i)=>{s.compute(gf(s.inputs,i),{inputs:[s.inputs[1],s.inputs[2]],outputs:[]})}}),wf,vf,Ef,Tf,xf,Mf,Pf,Cf,Sf,Af,kf,dl,If,$f,Of,Lf,Rf,Ff,Nf,wm=c(()=>{Wt(),jt(),mr(),or(),wf=(s,i)=>{if(s.every(l=>l>0||(()=>{throw new Error("Resize requires scales input values to be positive")})),s.length>0){if(i.mode==="linear"){if(!(s.length===2||s.length===3||s.length===4&&s[0]===1&&s[1]===1||s.length===4&&s[0]===1&&s[3]===1||s.length===5&&s[0]===1&&s[1]===1))throw new Error(`For linear mode, Resize requires scales to be 2D, 3D, 4D with either two outermost or one innermost and one outermost scale values equal to 1, or 5D with two outermost scale values equal to 1`)}else if(i.mode==="cubic"&&!(s.length===2||s.length===4&&s[0]===1&&s[1]===1||s.length===4&&s[0]===1&&s[3]===1))throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode")}},vf=(s,i,l)=>{i.every(p=>p>=0&&p{throw new Error("Resize requires axes input values to be positive and less than rank")}));let f=new Array(l).fill(1);return i.forEach((p,g)=>f[p]=s[g]),f},Ef=(s,i,l,f,p,g)=>{let[m,v,x]=l>10?[1,2,3]:[-1,s.length>1?1:-1,-1],P=s[0].dims.length;if(m>0&&s.length>m&&s[m].dims.length>0)s[m].getFloat32Array().forEach(D=>g.push(D));else if(i.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(v>0&&s.length>v&&s[v].dims.length===1&&s[v].dims[0]>0){if(s[v].getFloat32Array().forEach(D=>f.push(D)),f.length!==0&&f.length!==P&&l>=18&&f.length!==i.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");wf(f,i),i.axes.length>0&&vf(f,i.axes,P).forEach((D,R)=>f[R]=D)}if(x>0&&s.length>x&&s[x].dims.length===1&&s[x].dims[0]>0&&(s[x].getBigInt64Array().forEach(D=>p.push(Number(D))),p.length!==0&&p.length!==P&&l>=18&&p.length!==i.axes.length))throw new Error("Resize requires sizes input size to be same as input rank or axes size for opset 18 and up");if(i.axes.length>0){if(f.length!==0&&f.length!==i.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(p.length!==0&&p.length!==i.axes.length)throw new Error('Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified')}if(typeof f<"u"&&typeof p<"u"&&f.length>0&&p.length>P)throw new Error("Resize requires only of scales or sizes to be specified")},Tf=(s,i)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32, lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${i} { `+(()=>{switch(s){case"asymmetric":return`return ${i}(xResized) / ${i}(xScale);`;case"pytorch_half_pixel":return`if (lengthResized > 1) { return (${i}(xResized) + 0.5) / ${i}(xScale) - 0.5; } else { return 0.0; }`;case"tf_half_pixel_for_nn":return`return (${i}(xResized) + 0.5) / ${i}(xScale);`;case"align_corners":return`if (lengthResized == 1) { return 0.0; } else { // The whole part and the fractional part are calculated separately due to inaccuracy of floating // point division. As an example, f32(21) / f32(7) may evaluate to 2.99... instead of 3, causing an // offset-by-one error later in floor(). let whole = ${i}(xResized * (lengthOriginal - 1) / (lengthResized - 1)); let fract = ${i}(xResized * (lengthOriginal - 1) % (lengthResized - 1)) / ${i}(lengthResized - 1); return whole + fract; }`;case"tf_crop_and_resize":return`if (lengthResized > 1) { return ${i}(roiStart) * ${i}(lengthOriginal - 1) + (${i}(xResized) * ${i}(roiEnd - roiStart) * ${i}(lengthOriginal - 1)) / ${i}(lengthResized - 1); } else { return 0.5 * ${i}(roiStart + roiEnd) * ${i}(lengthOriginal - 1); }`;case"half_pixel_symmetric":return`const outputWidth = ${i}xScale * ${i}(lengthResized); const adjustment = ${i}(lengthResized) / outputWidth; const center = ${i}(lengthOriginal) / 2; const offset = center * (1 - adjustment); return offset + ((${i}(xResized) + 0.5) / ${i}(xScale)) - 0.5;`;case"half_pixel":return`return ((${i}(xResized) + 0.5) / ${i}(xScale)) - 0.5;`;default:throw new Error(`Coordinate transform mode ${s} is not supported`)}})()+"}",xf=(s,i,l)=>`fn getNearestPixelFromOriginal(xOriginal: ${l}, isDownSample: bool) -> ${l} {`+(()=>{switch(s){case"round_prefer_ceil":return"if (fract(xOriginal) == 0.5) { return ceil(xOriginal); } else { return round(xOriginal); }";case"floor":return"return floor(xOriginal);";case"ceil":return"return ceil(xOriginal);";case"round_prefer_floor":return"if (fract(xOriginal) == 0.5) { return floor(xOriginal); } else { return round(xOriginal); }";case"simple":default:if(i<11)return"if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }";throw new Error(`Nearest mode ${s} is not supported`)}})()+"}",Mf=(s,i,l)=>{let f=new Array(l).fill(0).concat(new Array(l).fill(1)),p=s.length===0?f:s.slice();return i.length>0?(i.forEach((g,m)=>{f[g]=p[m],f[m+l]=p[i.length+m]}),f):p},Pf=(s,i,l,f)=>{let p=[];if(l.length>0)if(f.length>0){if(s.forEach(g=>p.push(g)),Math.max(...f)>s.length)throw new Error("axes is out of bound");f.forEach((g,m)=>p[g]=l[m])}else l.forEach(g=>p.push(g));else{if(i.length===0)throw new Error("Resize requires either scales or sizes.");p=s.map((g,m)=>Math.round(g*i[m]))}return p},Cf=(s,i,l)=>{let f=(()=>{switch(l.keepAspectRatioPolicy){case"not_larger":return l.axes.length>0?Math.min(...l.axes.map(g=>i[g]),Number.MAX_VALUE):Math.min(...i,Number.MAX_VALUE);case"not_smaller":return l.axes.length>0?Math.max(...l.axes.map(g=>i[g]),Number.MIN_VALUE):Math.max(...i,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${l.keepAspectRatioPolicy} is not supported`)}})();i.fill(1,0,i.length);let p=s.slice();return l.axes.length>0?(l.axes.forEach(g=>i[g]=f),l.axes.forEach(g=>p[g]=Math.round(s[g]*i[g]))):(i.fill(f,0,i.length),p.forEach((g,m)=>p[m]=Math.round(g*i[m]))),p},Sf=(s,i,l,f,p)=>` fn calculateOriginalIndicesFromOutputIndices(output_indices: ${s.type.indices}) -> array<${s.type.value}, ${l.length}> { var original_indices: array<${s.type.value}, ${l.length}>; for (var i:u32 = 0; i < ${l.length}; i++) { var output_index = ${s.indicesGet("output_indices","i")}; var scale = ${Ft("uniforms.scales","i",f)}; var roi_low = ${Ft("uniforms.roi","i",p)}; var roi_hi = ${Ft("uniforms.roi",`i + ${i.length}`,p)}; if (scale == 1.0) { original_indices[i] = ${s.type.value}(output_index); } else { var input_shape_i = ${Ft("uniforms.input_shape","i",i.length)}; var output_shape_i = ${Ft("uniforms.output_shape","i",l.length)}; original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, input_shape_i, roi_low, roi_hi); } } return original_indices; }`,Af=(s,i,l,f,p,g,m)=>` fn calculateInputIndicesFromOutputIndices(output_indices: ${i.type.indices}) -> ${s.type.indices} { var input_indices: ${s.type.indices}; for (var i:u32 = 0; i < ${f.length}; i++) { var output_index = ${i.indicesGet("output_indices","i")}; var input_index: u32; var scale = ${Ft("uniforms.scales","i",p)}; if (scale == 1.0) { input_index = output_index; } else { var roi_low = ${Ft("uniforms.roi","i",g)}; var roi_hi = ${Ft("uniforms.roi",`i + ${l.length}`,g)}; var input_shape_i = ${Ft("uniforms.input_shape","i",l.length)}; var output_shape_i = ${Ft("uniforms.output_shape","i",f.length)}; var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, input_shape_i, roi_low, roi_hi); if (!${m} || (original_idx >= 0 && original_idx < ${i.type.value}(input_shape_i))) { if (original_idx < 0) { input_index = 0; } else if (original_idx > ${i.type.value}(input_shape_i - 1)) { input_index = input_shape_i - 1; } else { input_index = u32(getNearestPixelFromOriginal(original_idx, scale < 1)); } } else { input_index = u32(original_idx); } } ${s.indicesSet("input_indices","i"," input_index")} } return input_indices; }`,kf=(s,i)=>` fn checkInputIndices(input_indices: ${s.type.indices}) -> bool { for (var i:u32 = 0; i < ${i.length}; i++) { var input_index = ${s.indicesGet("input_indices","i")}; if (input_index < 0 || input_index >= ${Ft("uniforms.input_shape","i",i.length)}) { return false; } } return true; }`,dl=(s,i,l,f)=>s.rank>f?` ${s.indicesSet("input_indices",i,"channel")}; ${s.indicesSet("input_indices",l,"batch")}; `:"",If=(s,i,l,f,p)=>{let[g,m,v,x]=l.length===2?[-1,0,1,-1]:[0,2,3,1],P=s.type.value;return` fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${P} { var input_indices: ${s.type.indices}; ${s.indicesSet("input_indices",m,`max(0, min(row, ${l[m]} - 1))`)}; ${s.indicesSet("input_indices",v,`max(0, min(col, ${l[v]} - 1))`)}; ${dl(s,x,g,2)} return ${s.getByIndices("input_indices")}; } fn bilinearInterpolation(output_indices: ${i.type.indices}) -> ${P} { var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); var row:${P} = originalIndices[${m}]; var col:${P} = originalIndices[${v}]; ${f?`if (row < 0 || row > (${l[m]} - 1) || col < 0 || col > (${l[v]} - 1)) { return ${p}; }`:""}; row = max(0, min(row, ${l[m]} - 1)); col = max(0, min(col, ${l[v]} - 1)); var row1: u32 = u32(row); var col1: u32 = u32(col); var row2: u32 = u32(row + 1); var col2: u32 = u32(col + 1); var channel: u32 = ${l.length>2?`u32(originalIndices[${x}])`:"0"}; var batch: u32 = ${l.length>2?`u32(originalIndices[${g}])`:"0"}; var x11: ${P} = getInputValue(batch, channel, row1, col1); var x12: ${P} = getInputValue(batch, channel, row1, col2); var x21: ${P} = getInputValue(batch, channel, row2, col1); var x22: ${P} = getInputValue(batch, channel, row2, col2); var dx1: ${P} = abs(row - ${P}(row1)); var dx2: ${P} = abs(${P}(row2) - row); var dy1: ${P} = abs(col - ${P}(col1)); var dy2: ${P} = abs(${P}(col2) - col); if (row1 == row2) { dx1 = 0.5; dx2 = 0.5; } if (col1 == col2) { dy1 = 0.5; dy2 = 0.5; } return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1); }`},$f=(s,i,l,f,p,g,m,v,x,P)=>{let D=l.length===2,[R,E]=D?[0,1]:[2,3],K=s.type.value,q=Y=>{let ne=Y===R?"row":"col";return` fn ${ne}CubicInterpolation(input_indices: ${s.type.indices}, output_indices: ${i.type.indices}) -> ${K} { var output_index = ${i.indicesGet("output_indices",Y)}; var originalIdx: ${K} = getOriginalCoordinateFromResizedCoordinate(output_index, ${p[Y]}, ${f[Y]}, ${l[Y]}, ${g[Y]}, ${g[Y]} + ${l.length}); var fractOriginalIdx: ${K} = originalIdx - floor(originalIdx); var coefs = getCubicInterpolationCoefs(fractOriginalIdx); if (${v} && (originalIdx < 0 || originalIdx > (${l[Y]} - 1))) { return ${x}; } var data: array<${K}, 4> = array<${K}, 4>(0.0, 0.0, 0.0, 0.0); for (var i: i32 = -1; i < 3; i++) { var ${ne}: ${K} = originalIdx + ${K}(i); if (${ne} < 0 || ${ne} >= ${l[Y]}) { ${P?`coefs[i + 1] = 0.0; continue;`:v?`return ${x};`:`${ne} = max(0, min(${ne}, ${l[Y]} - 1));`}; } var input_indices_copy: ${s.type.indices} = input_indices; ${s.indicesSet("input_indices_copy",Y,`u32(${ne})`)}; data[i + 1] = ${Y===R?s.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; } return cubicInterpolation1D(data, coefs); }`};return` ${q(R)}; ${q(E)}; fn getCubicInterpolationCoefs(s: ${K}) -> array<${K}, 4> { var absS = abs(s); var coeffs: array<${K}, 4> = array<${K}, 4>(0.0, 0.0, 0.0, 0.0); var oneMinusAbsS: ${K} = 1.0 - absS; var twoMinusAbsS: ${K} = 2.0 - absS; var onePlusAbsS: ${K} = 1.0 + absS; coeffs[0] = ((${m} * onePlusAbsS - 5 * ${m}) * onePlusAbsS + 8 * ${m}) * onePlusAbsS - 4 * ${m}; coeffs[1] = ((${m} + 2) * absS - (${m} + 3)) * absS * absS + 1; coeffs[2] = ((${m} + 2) * oneMinusAbsS - (${m} + 3)) * oneMinusAbsS * oneMinusAbsS + 1; coeffs[3] = ((${m} * twoMinusAbsS - 5 * ${m}) * twoMinusAbsS + 8 * ${m}) * twoMinusAbsS - 4 * ${m}; return coeffs; } fn cubicInterpolation1D(x: array<${K}, 4>, coefs: array<${K}, 4>) -> ${K} { var coefsSum: ${K} = coefs[0] + coefs[1] + coefs[2] + coefs[3]; return (x[0] * coefs[0] + x[1] * coefs[1]+ x[2] * coefs[2]+ x[3] * coefs[3]) / coefsSum; } fn bicubicInterpolation(output_indices: ${i.type.indices}) -> ${K} { var input_indices: ${s.type.indices} = output_indices; return colCubicInterpolation(input_indices, output_indices); } `},Of=(s,i,l,f,p)=>{let[g,m,v,x,P]=l.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],D=s.type.value;return` fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${D} { var input_indices: ${s.type.indices}; ${s.indicesSet("input_indices",m,`max(0, min(depth, ${l[m]} - 1))`)}; ${s.indicesSet("input_indices",v,`max(0, min(height, ${l[v]} - 1))`)}; ${s.indicesSet("input_indices",x,`max(0, min(width, ${l[x]} - 1))`)}; ${dl(s,P,g,3)} return ${s.getByIndices("input_indices")}; } fn trilinearInterpolation(output_indices: ${i.type.indices}) -> ${D} { var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); var depth:${D} = originalIndices[${m}]; var height:${D} = originalIndices[${v}]; var width:${D} = originalIndices[${x}]; ${f?`if (depth < 0 || depth > (${l[m]} - 1) || height < 0 || height > (${l[v]} - 1) || width < 0 || (width > ${l[x]} - 1)) { return ${p}; }`:""}; depth = max(0, min(depth, ${l[m]} - 1)); height = max(0, min(height, ${l[v]} - 1)); width = max(0, min(width, ${l[x]} - 1)); var depth1: u32 = u32(depth); var height1: u32 = u32(height); var width1: u32 = u32(width); var depth2: u32 = u32(depth + 1); var height2: u32 = u32(height + 1); var width2: u32 = u32(width + 1); var channel: u32 = ${l.length>3?`u32(originalIndices[${P}])`:"0"}; var batch: u32 = ${l.length>3?`u32(originalIndices[${g}])`:"0"}; var x111: ${D} = getInputValue(batch, channel, depth1, height1, width1); var x112: ${D} = getInputValue(batch, channel, depth1, height1, width2); var x121: ${D} = getInputValue(batch, channel, depth1, height2, width1); var x122: ${D} = getInputValue(batch, channel, depth1, height2, width2); var x211: ${D} = getInputValue(batch, channel, depth2, height1, width1); var x212: ${D} = getInputValue(batch, channel, depth2, height1, width2); var x221: ${D} = getInputValue(batch, channel, depth2, height2, width1); var x222: ${D} = getInputValue(batch, channel, depth2, height2, width2); var dx1: ${D} = abs(depth - ${D}(depth1)); var dx2: ${D} = abs(${D}(depth2) - depth); var dy1: ${D} = abs(height - ${D}(height1)); var dy2: ${D} = abs(${D}(height2) - height); var dz1: ${D} = abs(width - ${D}(width1)); var dz2: ${D} = abs(${D}(width2) - width); if (depth1 == depth2) { dx1 = 0.5; dx2 = 0.5; } if (height1 == height2) { dy1 = 0.5; dy2 = 0.5; } if (width1 == width2) { dz1 = 0.5; dz2 = 0.5; } return (x111 * dx2 * dy2 * dz2 + x112 * dx2 * dy2 * dz1 + x121 * dx2 * dy1 *dz2 + x122 * dx2 * dy1 * dz1 + x211 * dx1 * dy2 * dz2 + x212 * dx1 * dy2 * dz1 + x221 * dx1 * dy1 *dz2 + x222 * dx1 * dy1 * dz1); }`},Lf=(s,i,l,f,p,g)=>{let m=s.dims,v=Mf(g,i.axes,m.length),x=Pf(m,f,p,i.axes),P=f.slice();f.length===0&&(P=m.map((te,ye)=>te===0?1:x[ye]/te),i.keepAspectRatioPolicy!=="stretch"&&(x=Cf(m,P,i)));let D=Dt("output",s.dataType,x.length),R=Qe("input",s.dataType,m.length),E=ze.size(x),K=m.length===x.length&&m.every((te,ye)=>te===x[ye]),q=i.coordinateTransformMode==="tf_crop_and_resize",Y=i.extrapolationValue,ne=R.type.value,se=te=>` ${K?"":` ${Tf(i.coordinateTransformMode,ne)}; ${(()=>{switch(i.mode){case"nearest":return` ${kf(R,m)}; ${xf(i.nearestMode,l,ne)}; ${Af(R,D,m,x,P.length,v.length,q)}; `;case"linear":return` ${Sf(D,m,x,P.length,v.length)}; ${(()=>{if(m.length===2||m.length===4)return`${If(R,D,m,q,Y)}`;if(m.length===3||m.length===5)return`${Of(R,D,m,q,Y)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()}; `;case"cubic":return` ${(()=>{if(m.length===2||m.length===4)return`${$f(R,D,m,x,P,v,i.cubicCoeffA,q,i.extrapolationValue,i.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()}; `;default:throw Error("Invalid resize mode")}})()}; `} ${te.registerUniform("output_size","u32").registerUniform("scales","f32",P.length).registerUniform("roi","f32",v.length).declareVariables(R,D)} ${te.mainStart()} ${te.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} ${K?"output[global_idx] = input[global_idx];":` let output_indices = ${D.offsetToIndices("global_idx")}; var input_indices: ${R.type.indices}; ${(()=>{switch(i.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); if (checkInputIndices(input_indices)) { output[global_idx] = ${R.getByIndices("input_indices")}; } else { output[global_idx] = ${i.extrapolationValue}; }`;case"linear":return`output[global_idx] = ${m.length===2||m.length===4?"bilinearInterpolation":"trilinearInterpolation"}(output_indices);`;case"cubic":return"output[global_idx] = bicubicInterpolation(output_indices);";default:throw Error(`Unsupported resize mode: ${i.mode}`)}})()}; `} }`;return{name:"Resize",shaderCache:{hint:`${i.cacheKey}|${l}|${P.length>0?P:""}|${p.length>0?p:""}|${v.length>0?v:""}|${K}|${m}`,inputDependencies:["rank"]},getShaderSource:se,getRunData:()=>({outputs:[{dims:x,dataType:s.dataType}],dispatchGroup:{x:Math.ceil(E/64)},programUniforms:[{type:12,data:E},{type:1,data:P},{type:1,data:v},...xt(m,x)]})}},Rf=s=>{let i=s.customDataBuffer;return new Uint32Array(i,i.byteOffset,1)[0]},Ff=(s,i)=>{let l=[],f=[],p=[],g=Rf(s);if(i.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");Ef(s.inputs,i,g,l,f,p),s.compute(Lf(s.inputs[0],i,g,l,f,p),{inputs:[0]})},Nf=s=>{let i=s.antialias,l=s.axes,f=s.coordinateTransformMode,p=s.cubicCoeffA,g=s.excludeOutside!==0,m=s.extrapolationValue,v=s.keepAspectRatioPolicy,x=s.mode,P=s.nearestMode===""?"simple":s.nearestMode;return Gt({antialias:i,axes:l,coordinateTransformMode:f,cubicCoeffA:p,excludeOutside:g,extrapolationValue:m,keepAspectRatioPolicy:v,mode:x,nearestMode:P})}}),Df,vm,ar,Em=c(()=>{Wt(),jt(),mr(),or(),Df=(s,i)=>{let[l,f,p,g]=s,{numHeads:m,rotaryEmbeddingDim:v}=i;if(l.dims.length!==3&&l.dims.length!==4)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${l.dims.length}`);if(!ze.areEqual(f.dims,[])&&!ze.areEqual(f.dims,[1])&&f.dims.length!==2)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${f.dims.length}`);if(p.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${p.dims.length}`);if(g.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${g.dims.length}`);if(!ze.areEqual(p.dims,g.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(v>0&&m===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let x=l.dims[0],P=l.dims[l.dims.length-2],D=p.dims[0],R=ze.sizeFromDimension(l.dims,1)/P,E=v===0?p.dims[1]*2:R/m;if(v>E)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(f.dims.length===2){if(x!==f.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${f.dims[0]}`);if(P!==f.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${f.dims[1]}`)}if(E/2!==p.dims[1]&&v/2!==p.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${p.dims[1]}`);if(P>D)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},vm=(s,i)=>{let{interleaved:l,numHeads:f,rotaryEmbeddingDim:p,scale:g}=i,m=s[0].dims[0],v=ze.sizeFromDimension(s[0].dims,1),x=s[0].dims[s[0].dims.length-2],P=v/x,D=s[2].dims[1],R=p===0?D*2:P/f,E=new Array(m,x,P/R,R-D),K=ze.computeStrides(E),q=[{type:1,data:g},{type:12,data:E},{type:12,data:K},...s[0].dims.length===3?new Array({type:12,data:[v,P,R,1]}):[],...s[0].dims.length===4?new Array({type:12,data:[v,R,x*R,1]}):[],...xt(s[0].dims,s[1].dims,s[2].dims,s[3].dims,s[0].dims)],Y=ne=>{let se=Qe("input",s[0].dataType,s[0].dims.length),te=Qe("position_ids",s[1].dataType,s[1].dims.length),ye=Qe("cos_cache",s[2].dataType,s[2].dims.length),be=Qe("sin_cache",s[3].dataType,s[3].dims.length),Ce=Dt("output",s[0].dataType,s[0].dims.length);return ne.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:E.length},{name:"global_strides",type:"u32",length:K.length},{name:"input_output_strides",type:"u32",length:K.length}]),` ${ne.declareVariables(se,te,ye,be,Ce)} ${ne.mainStart(Nn)} let half_rotary_emb_dim = uniforms.${ye.name}_shape[1]; let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape; let size = uniforms.global_shape[0] * uniforms.global_strides[0]; ${ne.guardAgainstOutOfBoundsWorkgroupSizes("size")} if (bsnh[3] < half_rotary_emb_dim) { let position_ids_idx = ${te.broadcastedIndicesToOffset("bsnh.xy",Dt("",te.type.tensor,2))}; let position_id = u32(${te.getByOffset("position_ids_idx")}) + select(0, bsnh[1], position_ids_idx == 0); let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${l}); let j = i + select(half_rotary_emb_dim, 1, ${l}); let re = ${se.getByOffset("i")} * ${ye.get("position_id","bsnh[3]")} - ${se.getByOffset("j")} * ${be.get("position_id","bsnh[3]")}; ${Ce.setByOffset("i","re")} let im = ${se.getByOffset("i")} * ${be.get("position_id","bsnh[3]")} + ${se.getByOffset("j")} * ${ye.get("position_id","bsnh[3]")}; ${Ce.setByOffset("j","im")} } else { let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; ${Ce.setByOffset("k",se.getByOffset("k"))} } }`};return{name:"RotaryEmbedding",shaderCache:{hint:Gt({interleaved:l}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:Y,getRunData:()=>({outputs:[{dims:s[0].dims,dataType:s[0].dataType}],dispatchGroup:{x:Math.ceil(ze.size(E)/Nn)},programUniforms:q})}},ar=(s,i)=>{Df(s.inputs,i),s.compute(vm(s.inputs,i))}}),gn,vn,Sn,Oa=c(()=>{Wt(),jt(),or(),gn=s=>{if(!s||s.length<3)throw new Error("layerNorm requires at least 3 inputs.");let i=s[0],l=s[1],f=s[2];if(i.dataType!==l.dataType||i.dataType!==f.dataType)throw new Error("All inputs must have the same data type");if(i.dims.length!==3&&i.dims.length!==2)throw new Error("Input must be 2D or 3D");if(l.dims.length!==3&&l.dims.length!==2)throw new Error("Skip must be 2D or 3D");let p=i.dims[i.dims.length-1],g=i.dims[i.dims.length-2];if(l.dims[l.dims.length-1]!==p)throw new Error("Skip must have the same hidden size as input");if(l.dims[l.dims.length-2]!==g)throw new Error("Skip must have the same sequence length as input");if(f.dims.length!==1)throw new Error("Gamma must be 1D");if(f.dims[f.dims.length-1]!==p)throw new Error("Gamma must have the same hidden size as input");if(s.length>3){let m=s[3];if(m.dims.length!==1)throw new Error("Beta must be 1D");if(m.dims[m.dims.length-1]!==p)throw new Error("Beta must have the same hidden size as input")}if(s.length>4){let m=s[4];if(m.dims.length!==1)throw new Error("Bias must be 1D");if(m.dims[m.dims.length-1]!==p)throw new Error("Bias must have the same hidden size as input")}},vn=(s,i,l,f)=>{let p=i.simplified,g=s[0].dims,m=ze.size(g),v=g,x=m,P=g.slice(-1)[0],D=f?g.slice(0,-1).concat(1):[],R=!p&&s.length>3,E=s.length>4,K=f&&l>1,q=f&&l>2,Y=l>3,ne=64,se=sr(P),te=[{type:12,data:x},{type:12,data:se},{type:12,data:P},{type:1,data:i.epsilon}],ye=Ce=>{let Be=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],je=[Qe("x",s[0].dataType,s[0].dims,se),Qe("skip",s[1].dataType,s[1].dims,se),Qe("gamma",s[2].dataType,s[2].dims,se)];R&&je.push(Qe("beta",s[3].dataType,s[3].dims,se)),E&&je.push(Qe("bias",s[4].dataType,s[4].dims,se)),je.push(Dt("output",s[0].dataType,v,se)),K&&je.push(Dt("mean_output",1,D)),q&&je.push(Dt("inv_std_output",1,D)),Y&&je.push(Dt("input_skip_bias_sum",s[0].dataType,v,se));let tt=Ir(s[0].dataType),lt=Ir(1,se);return` ${Ce.registerUniforms(Be).declareVariables(...je)} var sum_shared : array<${lt}, ${ne}>; var sum_squared_shared : array<${lt}, ${ne}>; ${Ce.mainStart([ne,1,1])} let ix = local_id.x; let iy = global_id.x / ${ne}; let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; var stride = hidden_size_vectorized / ${ne}; let offset = ix * stride + iy * hidden_size_vectorized; let offset1d = stride * ix; if (ix == ${ne-1}) { stride = hidden_size_vectorized - stride * ix; } for (var i: u32 = 0; i < stride; i++) { let skip_value = skip[offset + i]; let bias_value = ${E?"bias[offset1d + i]":tt+"(0.0)"}; let input_value = x[offset + i]; let value = input_value + skip_value + bias_value; ${Y?"input_skip_bias_sum[offset + i] = value;":""} output[offset + i] = value; let f32_value = ${Jr(tt,se,"value")}; sum_shared[ix] += f32_value; sum_squared_shared[ix] += f32_value * f32_value; } workgroupBarrier(); var reduce_size : u32 = ${ne}; for (var curr_size = reduce_size >> 1; curr_size > 0; curr_size = reduce_size >> 1) { reduce_size = curr_size + (reduce_size & 1); if (ix < curr_size) { sum_shared[ix] += sum_shared[ix + reduce_size]; sum_squared_shared[ix] += sum_squared_shared[ix + reduce_size]; } workgroupBarrier(); } let sum = sum_shared[0]; let square_sum = sum_squared_shared[0]; let mean = ${_n("sum",se)} / f32(uniforms.hidden_size); let inv_std_dev = inverseSqrt(${_n("square_sum",se)} / f32(uniforms.hidden_size) ${p?"":"- mean * mean"} + uniforms.epsilon); ${K?"mean_output[global_idx] = mean;":""} ${q?"inv_std_output[global_idx] = inv_std_dev;":""} for (var i: u32 = 0; i < stride; i++) { output[offset + i] = (output[offset + i] ${p?"":`- ${tt}(mean)`}) * ${tt}(inv_std_dev) * gamma[offset1d + i] ${R?"+ beta[offset1d + i]":""}; } }`},be=[{dims:v,dataType:s[0].dataType}];return l>1&&be.push({dims:D,dataType:1}),l>2&&be.push({dims:D,dataType:1}),l>3&&be.push({dims:g,dataType:s[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${se};${K};${q};${Y}`,inputDependencies:s.map((Ce,Be)=>"type")},getShaderSource:ye,getRunData:()=>({outputs:be,dispatchGroup:{x:Math.ceil(x/P)},programUniforms:te})}},Sn=(s,i)=>{gn(s.inputs);let l=[0];s.outputCount>1&&l.push(-3),s.outputCount>2&&l.push(-3),s.outputCount>3&&l.push(3),s.compute(vn(s.inputs,i,s.outputCount,!1),{outputs:l})}}),Tm,ui,Bf,A,O,Z,xe,Ne,De=c(()=>{Wt(),jt(),mr(),or(),Tm=(s,i)=>{if(!s||s.length<1)throw new Error("too few inputs");if(i.axes.length!==0){if(i.axes.length!==i.starts.length||i.axes.length!==i.ends.length)throw new Error("axes, starts and ends must have the same length")}else if(i.starts.length!==i.ends.length)throw new Error("starts and ends must have the same length");s.slice(1).forEach((l,f)=>{if(s[f+1].dataType!==6&&s[f+1].dataType!==7)throw new Error(`Input ${f} must be an array of int32 or int64`)})},ui=(s,i)=>{let l=[];if(s.length>i)if(s[i].dataType===7)s[i].getBigInt64Array().forEach(f=>l.push(Number(f)));else if(s[i].dataType===6)s[i].getInt32Array().forEach(f=>l.push(Number(f)));else throw new Error(`Input ${i} must be an array of int32 or int64`);return l},Bf=(s,i)=>{if(s.length>1){let l=ui(s,1),f=ui(s,2),p=ui(s,3);return p.length===0&&(p=[...Array(s[0].dims.length).keys()]),Gt({starts:l,ends:f,axes:p})}else return i},A=(s,i,l,f,p)=>{let g=s;return s<0&&(g+=l[f[i]]),p[i]<0?Math.max(0,Math.min(g,l[f[i]]-1)):Math.max(0,Math.min(g,l[f[i]]))},O=(s,i,l)=>`fn calculateInputIndices(output_indices: ${i.type.indices}) -> ${s.type.indices} { var input_indices: ${s.type.indices}; var carry = 0u; for (var i = ${l.length}; i >= 0; i--) { let input_shape_i = ${Ft("uniforms.input_shape","i",l.length)}; let steps_i = ${Ft("uniforms.steps","i",l.length)}; let signs_i = ${Ft("uniforms.signs","i",l.length)}; let starts_i = ${Ft("uniforms.starts","i",l.length)}; var output_index = ${i.indicesGet("output_indices","i")}; var input_index = output_index * steps_i + starts_i + carry; carry = input_index / input_shape_i; input_index = input_index % input_shape_i; if (signs_i < 0) { input_index = input_shape_i - input_index - 1u + starts_i; } ${s.indicesSet("input_indices","i","input_index")}; } return input_indices; }`,Z=(s,i)=>{let l=s[0].dims,f=ze.size(l),p=i.axes.length>0?ze.normalizeAxes(i.axes,l.length):[...Array(l.length).keys()],g=ui(s,4);g.forEach(se=>se!==0||(()=>{throw new Error("step cannot be 0")})),g.length===0&&(g=Array(p.length).fill(1));let m=i.starts.map((se,te)=>A(se,te,l,p,g)),v=i.ends.map((se,te)=>A(se,te,l,p,g));if(p.length!==m.length||p.length!==v.length)throw new Error("start, ends and axes should have the same number of elements");if(p.length!==l.length)for(let se=0;seMath.sign(se));g.forEach((se,te,ye)=>{if(se<0){let be=(v[te]-m[te])/se,Ce=m[te],Be=Ce+be*g[te];m[te]=Be,v[te]=Ce,ye[te]=-se}});let P=l.slice(0);p.forEach((se,te)=>{P[se]=Math.ceil((v[se]-m[se])/g[se])});let D={dims:P,dataType:s[0].dataType},R=Dt("output",s[0].dataType,P.length),E=Qe("input",s[0].dataType,s[0].dims.length),K=ze.size(P),q=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:m.length},{name:"signs",type:"i32",length:x.length},{name:"steps",type:"u32",length:g.length}],Y=[{type:12,data:K},{type:12,data:m},{type:6,data:x},{type:12,data:g},...xt(s[0].dims,P)],ne=se=>` ${se.registerUniforms(q).declareVariables(E,R)} ${O(E,R,l)} ${se.mainStart()} ${se.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let output_indices = ${R.offsetToIndices("global_idx")}; let input_indices = calculateInputIndices(output_indices); ${R.setByOffset("global_idx",E.getByIndices("input_indices"))} }`;return{name:"Slice",shaderCache:{hint:`${x.length}_${m.length}_${g.length}`,inputDependencies:["rank"]},getShaderSource:ne,getRunData:()=>({outputs:[D],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:Y})}},xe=(s,i)=>{Tm(s.inputs,i);let l=Bf(s.inputs,i);s.compute(Z(s.inputs,l),{inputs:[0]})},Ne=s=>{let i=s.starts,l=s.ends,f=s.axes;return Gt({starts:i,ends:l,axes:f})}}),nt,at,wt,Mt,Zt=c(()=>{Wt(),jt(),mr(),Vs(),or(),nt=s=>{if(!s||s.length!==1)throw new Error("Softmax op requires 1 input.")},at=(s,i)=>{let l=s.inputs[0],f=l.dims,p=ze.size(f),g=f.length,m=ze.normalizeAxis(i.axis,g),v=mtt),P[m]=g-1,P[g-1]=m,x=s.compute(qn(l,P),{inputs:[l],outputs:[-1]})[0]):x=l;let D=x.dims,R=D[g-1],E=p/R,K=sr(R),q=R/K,Y=64;E===1&&(Y=256);let ne=(je,tt)=>tt===4?`max(max(${je}.x, ${je}.y), max(${je}.z, ${je}.w))`:tt===2?`max(${je}.x, ${je}.y)`:tt===3?`max(max(${je}.x, ${je}.y), ${je}.z)`:je,se=Qe("x",x.dataType,x.dims,K),te=Dt("result",x.dataType,x.dims,K),ye=se.type.value,be=Ir(x.dataType)==="f32"?`var threadMax = ${ye}(-3.402823e+38f);`:`var threadMax = ${ye}(-65504.0h);`,Ce=je=>` var rowMaxShared : ${ye}; var rowSumShared : ${ye}; var threadShared : array<${ye}, ${Y}>; fn getValue(row: i32, col: i32, row_stride: i32) -> ${ye} { let index = row * row_stride + col; return x[index]; } fn setValue(row: i32, col: i32, row_stride: i32, value: ${ye}) { let index = row * row_stride + col; result[index] = value; } ${je.registerUniform("packedCols","i32").declareVariables(se,te)} ${je.mainStart(Y)} let gindex = i32(global_idx); let lindex = i32(local_idx); const wg = ${Y}; let row = gindex / wg; let cols = uniforms.packedCols; let row_stride : i32 = uniforms.packedCols; // find the rows max ${be} for (var col = lindex; col < cols; col += wg) { let value = getValue(row, col, row_stride); threadMax = max(threadMax, value); } if (lindex < cols) { threadShared[lindex] = threadMax; } workgroupBarrier(); var reduceSize = min(cols, wg); for (var currSize = reduceSize >> 1; currSize > 0; currSize = reduceSize >> 1) { reduceSize = currSize + (reduceSize & 1); if (lindex < currSize) { threadShared[lindex] = max(threadShared[lindex], threadShared[lindex + reduceSize]); } workgroupBarrier(); } if (lindex == 0) { rowMaxShared = ${ye}(${ne("threadShared[0]",K)}); } workgroupBarrier(); // find the rows sum var threadSum = ${ye}(0.0); for (var col = lindex; col < cols; col += wg) { let subExp = exp(getValue(row, col, row_stride) - rowMaxShared); threadSum += subExp; } threadShared[lindex] = threadSum; workgroupBarrier(); for (var currSize = wg >> 1; currSize > 0; currSize = currSize >> 1) { if (lindex < currSize) { threadShared[lindex] = threadShared[lindex] + threadShared[lindex + currSize]; } workgroupBarrier(); } if (lindex == 0) { rowSumShared = ${ye}(${_n("threadShared[0]",K)}); } workgroupBarrier(); // calculate final value for each element in the row for (var col = lindex; col < cols; col += wg) { let value = exp(getValue(row, col, row_stride) - rowMaxShared) / rowSumShared; setValue(row, col, row_stride, value); } }`,Be=s.compute({name:"Softmax",shaderCache:{hint:`${K};${Y}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:D,dataType:x.dataType}],dispatchGroup:{x:E},programUniforms:[{type:6,data:q}]}),getShaderSource:Ce},{inputs:[x],outputs:[v?-1:0]})[0];v&&s.compute(qn(Be,P),{inputs:[Be]})},wt=(s,i)=>{nt(s.inputs),at(s,i)},Mt=s=>Gt({axis:s.axis})}),Xt,Vt,er,hr,_r,ur=c(()=>{Wt(),jt(),or(),Xt=s=>Array.from(s.getBigInt64Array(),Number),Vt=s=>{if(!s||s.length!==2)throw new Error("Tile requires 2 inputs.");if(s[0].dataType!==1&&s[0].dataType!==10&&s[0].dataType!==6&&s[0].dataType!==12)throw new Error("Tile only support float, float16, int32, and uint32 data types");if(s[1].dataType!==7)throw new Error("Tile `repeats` input should be of int64 data type");if(s[1].dims.length!==1)throw new Error("Tile `repeats` input should be 1-D");if(Xt(s[1]).length!==s[0].dims.length)throw new Error("Tile `repeats` input should have same number of elements as rank of input data tensor")},er=(s,i)=>{let l=[];for(let f=0;f{let l=s[0].dims,f=i??Xt(s[1]),p=er(l,f),g=ze.size(p),m=s[0].dataType,v=Qe("input",m,l.length),x=Dt("output",m,p.length),P=D=>` const inputShape = ${v.indices(...l)}; ${D.registerUniform("output_size","u32").declareVariables(v,x)} ${D.mainStart()} ${D.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let output_indices = ${x.offsetToIndices("global_idx")}; var input_indices: ${v.type.indices}; for (var i = 0; i < ${l.length}; i++) { let input_dim_i = ${v.indicesGet("uniforms.input_shape","i")}; let input_dim_value = ${x.indicesGet("output_indices","i")} % input_dim_i; ${v.indicesSet("input_indices","i","input_dim_value")} } ${x.setByOffset("global_idx",v.getByIndices("input_indices"))} }`;return{name:"Tile",shaderCache:{hint:`${f}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:p,dataType:s[0].dataType}],dispatchGroup:{x:Math.ceil(g/64)},programUniforms:[{type:12,data:g},...xt(s[0].dims,p)]}),getShaderSource:P}},_r=s=>{Vt(s.inputs),s.compute(hr(s.inputs),{inputs:[0]})}}),vr,Kr,Ur,$r=c(()=>{Wt(),jt(),or(),vr=(s,i,l,f,p)=>{let g=Dt("output_data",p,l.length,4),m=Qe("a_data",i[1].dataType,i[1].dims.length,4),v=Qe("b_data",i[2].dataType,i[2].dims.length,4),x=Qe("c_data",i[0].dataType,i[0].dims.length,4),P,D=(R,E,K)=>`select(${E}, ${R}, ${K})`;if(!f)P=g.setByOffset("global_idx",D(m.getByOffset("global_idx"),v.getByOffset("global_idx"),x.getByOffset("global_idx")));else{let R=(E,K,q="")=>{let Y=`a_data[index_a${K}][component_a${K}]`,ne=`b_data[index_b${K}][component_b${K}]`,se=`bool(c_data[index_c${K}] & (0xffu << (component_c${K} * 8)))`;return` let output_indices${K} = ${g.offsetToIndices(`global_idx * 4u + ${K}u`)}; let offset_a${K} = ${m.broadcastedIndicesToOffset(`output_indices${K}`,g)}; let offset_b${K} = ${v.broadcastedIndicesToOffset(`output_indices${K}`,g)}; let offset_c${K} = ${x.broadcastedIndicesToOffset(`output_indices${K}`,g)}; let index_a${K} = offset_a${K} / 4u; let index_b${K} = offset_b${K} / 4u; let index_c${K} = offset_c${K} / 4u; let component_a${K} = offset_a${K} % 4u; let component_b${K} = offset_b${K} % 4u; let component_c${K} = offset_c${K} % 4u; ${E}[${K}] = ${q}(${D(Y,ne,se)}); `};p===9?P=` var data = vec4(0); ${R("data",0,"u32")} ${R("data",1,"u32")} ${R("data",2,"u32")} ${R("data",3,"u32")} output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:P=` ${R("output_data[global_idx]",0)} ${R("output_data[global_idx]",1)} ${R("output_data[global_idx]",2)} ${R("output_data[global_idx]",3)} `}return` ${s.registerUniform("vec_size","u32").declareVariables(x,m,v,g)} ${s.mainStart()} ${s.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${P} }`},Kr=s=>{let i=s[1].dims,l=s[2].dims,f=s[0].dims,p=s[1].dataType,g=!(ze.areEqual(i,l)&&ze.areEqual(l,f)),m=i,v=ze.size(i);if(g){let P=mn.calcShape(mn.calcShape(i,l,!1),f,!1);if(!P)throw new Error("Can't perform where op on the given tensors");m=P,v=ze.size(m)}let x=Math.ceil(v/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:P=>vr(P,s,m,g,p),getRunData:()=>({outputs:[{dims:m,dataType:p}],dispatchGroup:{x:Math.ceil(v/64/4)},programUniforms:[{type:12,data:x},...xt(f,i,l,m)]})}},Ur=s=>{s.compute(Kr(s.inputs))}}),Gr,tn=c(()=>{Up(),qo(),Vp(),Wp(),Gp(),Hp(),Ed(),Yp(),jd(),Qp(),qd(),Jp(),em(),tm(),W_(),ii(),rm(),sm(),Eh(),Hu(),om(),um(),lm(),Gh(),Fr(),Oh(),ef(),mm(),_m(),bm(),ym(),Ni(),wm(),Em(),Oa(),De(),Zt(),Fh(),ur(),Vs(),hu(),$r(),Gr=new Map([["Abs",[Lc]],["Acos",[Jo]],["Acosh",[Rc]],["Add",[dd]],["ArgMax",[Vo,Wo]],["ArgMin",[Pc,Wo]],["Asin",[Fc]],["Asinh",[eu]],["Atan",[Nc]],["Atanh",[Dc]],["Attention",[Ac]],["AveragePool",[sf,nf]],["BatchNormalization",[Yo]],["BiasAdd",[Oc]],["BiasSplitGelu",[ud]],["Cast",[Bc,tu]],["Ceil",[Uc]],["Clip",[zc]],["Concat",[wd,vd]],["Conv",[Fu,Ou]],["ConvTranspose",[Bd,ju]],["Cos",[ru]],["Cosh",[Vc]],["CumSum",[Ud,Vd]],["DepthToSpace",[Hd,Kd]],["DequantizeLinear",[ff,pf]],["Div",[hd]],["Einsum",[eh,th]],["Elu",[nu,ri]],["Equal",[pu]],["Erf",[Wc]],["Exp",[su]],["Expand",[ai]],["FastGelu",[ah]],["Floor",[Gc]],["FusedConv",[Fu,Ou]],["Gather",[uh,oh]],["GatherElements",[nm,Xi]],["GatherBlockQuantized",[ph,mh]],["GatherND",[ch,dh]],["Gelu",[Hc]],["Gemm",[vh,wh]],["GlobalAveragePool",[of,af]],["GlobalMaxPool",[pm,cf]],["Greater",[md]],["GreaterOrEqual",[_u]],["GridSample",[Ah,Gu]],["GroupQueryAttention",[Qu]],["HardSigmoid",[Xc,ou]],["InstanceNormalization",[Bh]],["LayerNormalization",[Uh]],["LeakyRelu",[au,ri]],["Less",[_d]],["LessOrEqual",[gd]],["Log",[sd]],["MatMul",[Wh]],["MatMulNBits",[qh,Zh]],["MaxPool",[uf,lf]],["Mul",[fd]],["MultiHeadAttention",[Ku,Ih]],["Neg",[qc]],["Not",[Kc]],["Pad",[nl]],["Pow",[pd]],["QuickGelu",[id,ri]],["Range",[mf]],["Reciprocal",[iu]],["ReduceMin",[Ec]],["ReduceMean",[yc]],["ReduceMax",[jo]],["ReduceSum",[zo]],["ReduceProd",[Tc]],["ReduceL1",[Bo]],["ReduceL2",[wc]],["ReduceLogSum",[Mc]],["ReduceLogSumExp",[vc]],["ReduceSumSquare",[xc]],["Relu",[Zc]],["Resize",[Ff,Nf]],["RotaryEmbedding",[ar]],["ScatterND",[yf,bf]],["Sigmoid",[Yc]],["Sin",[Qc]],["Sinh",[uu]],["Slice",[xe,Ne]],["SkipLayerNormalization",[Sn]],["Split",[Zu,Rh]],["Sqrt",[Jc]],["Softmax",[wt,Mt]],["Sub",[mu]],["Tan",[ed]],["Tanh",[td]],["ThresholdedRelu",[nd,ri]],["Tile",[_r]],["Transpose",[Ql,Io]],["Where",[Ur]]])}),Mn,En=c(()=>{Ze(),Ie(),or(),Mn=class{constructor(s){this.backend=s,this.repo=new Map,this.attributesBound=!1}getArtifact(s){return this.repo.get(s)}setArtifact(s,i){this.repo.set(s,i)}run(s,i,l,f,p){Ge(s.programInfo.name);let g=this.backend.device,m=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let v=[];for(let P of i)v.push({binding:v.length,resource:{buffer:P.buffer}});for(let P of l)v.push({binding:v.length,resource:{buffer:P.buffer}});p&&v.push({binding:v.length,resource:p});let x=g.createBindGroup({layout:s.computePipeline.getBindGroupLayout(0),entries:v,label:s.programInfo.name});if(this.backend.sessionStatus==="capturing"){let P={kernelId:this.backend.currentKernelId,computePipeline:s.computePipeline,bindGroup:x,dispatchGroup:f};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(P)}m.setPipeline(s.computePipeline),m.setBindGroup(0,x),m.dispatchWorkgroups(...f),this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||this.backend.queryType==="at-passes")&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),We(s.programInfo.name)}dispose(){}build(s,i){Ge(s.name);let l=this.backend.device,f=[];[{feature:"shader-f16",extension:"f16"},{feature:"subgroups",extension:"subgroups"},{feature:"subgroups-f16",extension:"subgroups_f16"}].forEach(P=>{l.features.has(P.feature)&&f.push(`enable ${P.extension};`)});let p=ql(i,this.backend.device.limits),g=s.getShaderSource(p),m=`${f.join(` `)} ${p.additionalImplementations} ${g}`,v=l.createShaderModule({code:m,label:s.name});Tr("verbose",()=>`[WebGPU] ${s.name} shader code: ${m}`);let x=l.createComputePipeline({compute:{module:v,entryPoint:"main"},layout:"auto",label:s.name});return We(s.name),{programInfo:s,computePipeline:x,uniformVariablesInfo:p.variablesInfo}}normalizeDispatchGroupSize(s){let i=typeof s=="number"?s:s.x,l=typeof s=="number"?1:s.y||1,f=typeof s=="number"?1:s.z||1,p=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(i<=p&&l<=p&&f<=p)return[i,l,f];let g=i*l*f,m=Math.ceil(Math.sqrt(g));if(m>p){if(m=Math.ceil(Math.cbrt(g)),m>p)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[m,m,m]}else return[m,m,1]}}}),os,La,hl,Vn,_s,jf=c(()=>{Ze(),Wt(),Ie(),ee(),Pr(),tn(),En(),os=(s,i)=>{if(i.length!==s.length)throw new Error(`inputDependencies length ${i.length} is not equal to inputTensors length ${s.length}.`);let l=[];for(let f=0;f{var p,g;let f=s.name;return(p=s.shaderCache)!=null&&p.hint&&(f+="["+s.shaderCache.hint+"]"),f+=":"+l+`:${os(i,((g=s.shaderCache)==null?void 0:g.inputDependencies)??new Array(i.length).fill("dims"))}`,f},hl=class{constructor(s){s&&(this.architecture=s.architecture,this.vendor=s.vendor)}isArchitecture(s){return this.architecture===s}isVendor(s){return this.vendor===s}},Vn=class{constructor(s){this.subgroupsSupported=s.features.has("subgroups"),this.subgroupsF16Supported=s.features.has("subgroups");let i=s.limits;!this.subgroupsSupported||!i.minSubgroupSize||!i.maxSubgroupSize?this.subgroupSizeRange=void 0:this.subgroupSizeRange=[i.minSubgroupSize,i.maxSubgroupSize]}},_s=class{constructor(){this.currentSessionId=null,this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionStatus="default",this.capturedCommandList=new Map,this.capturedPendingKernels=new Map,this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let s=this.kernelCustomData.get(this.currentKernelId);return s||(s={},this.kernelCustomData.set(this.currentKernelId,s)),s}async initialize(s,i){this.env=s;let l=[],f={requiredLimits:{maxComputeWorkgroupStorageSize:i.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:i.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:i.limits.maxStorageBufferBindingSize,maxBufferSize:i.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:i.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:i.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:i.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:i.limits.maxComputeWorkgroupSizeZ},requiredFeatures:l},p=g=>i.features.has(g)&&l.push(g)&&!0;p("chromium-experimental-timestamp-query-inside-passes")||p("timestamp-query"),p("shader-f16"),p("subgroups")&&p("subgroups-f16"),this.device=await i.requestDevice(f),this.deviceInfo=new Vn(this.device),this.adapterInfo=new hl(i.info||await i.requestAdapterInfo()),this.gpuDataManager=kr(this),this.programManager=new Mn(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,Ia(s.logLevel,!!s.debug),this.device.onuncapturederror=g=>{g.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${g.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:i,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let s=this.getCommandEncoder(),i={};this.queryType==="at-passes"&&(i.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=s.beginComputePass(i)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;Ge(),this.endComputePass();let s;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),s=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(s,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,s,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&s.mapAsync(GPUMapMode.READ).then(()=>{var f;let i=new BigUint64Array(s.getMappedRange()),l=this.pendingQueries.get(s);for(let p=0;p"u"&&(this.queryTimeBase=K);let Y=Number(K-this.queryTimeBase),ne=Number(q-this.queryTimeBase);if(!Number.isSafeInteger(Y)||!Number.isSafeInteger(ne))throw new RangeError("incorrect timestamp range");if((f=this.env.webgpu.profiling)!=null&&f.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:R.map(se=>({dims:se.dims,dataType:rs(se.dataType)})),outputsMetadata:E.map(se=>({dims:se.dims,dataType:rs(se.dataType)})),kernelId:m,kernelType:x,kernelName:P,programName:D,startTime:Y,endTime:ne});else{let se="";R.forEach((ye,be)=>{se+=`input[${be}]: [${ye.dims}] | ${rs(ye.dataType)}, `});let te="";E.forEach((ye,be)=>{te+=`output[${be}]: [${ye.dims}] | ${rs(ye.dataType)}, `}),console.log(`[profiling] kernel "${m}|${x}|${P}|${D}" ${se}${te}execution time: ${ne-Y} ns`)}Ke("GPU",`${D}::${K}::${q}`)}s.unmap(),this.pendingQueries.delete(s)}),We()}run(s,i,l,f,p,g){Ge(s.name);let m=[];for(let te=0;teye):l;if(D.length!==v.length)throw new Error(`Output size ${D.length} must be equal to ${v.length}.`);let R=[],E=[];for(let te=0;te=g)throw new Error(`Invalid output index: ${D[te]}`);if(D[te]===-3)continue;let ye=D[te]===-1,be=D[te]===-2,Ce=ye||be?p(v[te].dataType,v[te].dims):f(D[te],v[te].dataType,v[te].dims);if(R.push(Ce),Ce.data===0)continue;let Be=this.gpuDataManager.get(Ce.data);if(!Be)throw new Error(`no GPU data for output: ${Ce.data}`);if(ye&&this.temporaryData.push(Be),be){let je=this.kernelPersistentData.get(this.currentKernelId);je||(je=[],this.kernelPersistentData.set(this.currentKernelId,je)),je.push(Be)}E.push(Be)}if(m.length!==i.length||E.length!==R.length){if(E.length===0)return We(s.name),R;throw new Error(`Program ${s.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let K;if(P){let te=0,ye=[];P.forEach(je=>{let tt=typeof je.data=="number"?[je.data]:je.data;if(tt.length===0)return;let lt=je.type===10?2:4,kt,ir;je.type===10?(ir=tt.length>4?16:tt.length>2?8:tt.length*lt,kt=tt.length>4?16:lt*tt.length):(ir=tt.length<=2?tt.length*lt:16,kt=16),te=Math.ceil(te/ir)*ir,ye.push(te);let cr=je.type===10?8:4;te+=tt.length>4?Math.ceil(tt.length/cr)*kt:tt.length*lt});let be=16;te=Math.ceil(te/be)*be;let Ce=new ArrayBuffer(te);P.forEach((je,tt)=>{let lt=ye[tt],kt=typeof je.data=="number"?[je.data]:je.data;if(je.type===6)new Int32Array(Ce,lt,kt.length).set(kt);else if(je.type===12)new Uint32Array(Ce,lt,kt.length).set(kt);else if(je.type===10)new Uint16Array(Ce,lt,kt.length).set(kt);else if(je.type===1)new Float32Array(Ce,lt,kt.length).set(kt);else throw new Error(`Unsupported uniform type: ${rs(je.type)}`)});let Be=this.gpuDataManager.create(te,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(Be.buffer,0,Ce,0,te),this.gpuDataManager.release(Be.id),K={offset:0,size:te,buffer:Be.buffer}}let q=this.programManager.normalizeDispatchGroupSize(x),Y=q[1]===1&&q[2]===1,ne=La(s,i,Y),se=this.programManager.getArtifact(ne);if(se||(se=this.programManager.build(s,q),this.programManager.setArtifact(ne,se),Tr("info",()=>`[artifact] key: ${ne}, programName: ${s.name}`)),P&&se.uniformVariablesInfo){if(P.length!==se.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${se.uniformVariablesInfo.length}, got ${P.length} in program "${se.programInfo.name}".`);for(let te=0;te`[ProgramManager] run "${s.name}" (key=${ne}) with ${q[0]}x${q[1]}x${q[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let te={kernelId:this.currentKernelId,programName:se.programInfo.name,inputTensorViews:i,outputTensorViews:R};this.pendingKernels.push(te),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(te)}return this.programManager.run(se,m,E,q,K),We(s.name),R}upload(s,i){this.gpuDataManager.upload(s,i)}memcpy(s,i){this.gpuDataManager.memcpy(s,i)}async download(s,i){await this.gpuDataManager.download(s,i)}alloc(s){return this.gpuDataManager.create(s).id}free(s){return this.gpuDataManager.release(s)}createKernel(s,i,l,f){let p=Gr.get(s);if(!p)throw new Error(`kernel not implemented: ${s}`);let g={kernelType:s,kernelName:f,kernelEntry:p[0],attributes:[p[1],l]};this.kernels.set(i,g)}releaseKernel(s){let i=this.kernelPersistentData.get(s);if(i){for(let l of i)this.gpuDataManager.release(l.id);this.kernelPersistentData.delete(s)}this.kernelCustomData.delete(s),this.kernels.delete(s)}computeKernel(s,i,l){let f=this.kernels.get(s);if(!f)throw new Error(`kernel not created: ${s}`);let p=f.kernelType,g=f.kernelName,m=f.kernelEntry,v=f.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${p}] ${g}" is not allowed to be called recursively`);this.currentKernelId=s,v[0]&&(v[1]=v[0](v[1]),v[0]=void 0),Tr("info",()=>`[WebGPU] Start to run kernel "[${p}] ${g}"...`);let x=this.env.debug;this.temporaryData=[];try{return x&&this.device.pushErrorScope("validation"),m(i,v[1]),0}catch(P){return l.push(Promise.resolve(`[WebGPU] Kernel "[${p}] ${g}" failed. ${P}`)),1}finally{x&&l.push(this.device.popErrorScope().then(P=>P?`GPU validation error for kernel "[${p}] ${g}": ${P.message}`:null));for(let P of this.temporaryData)this.gpuDataManager.release(P.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(s,i,l,f){let p=this.sessionExternalDataMapping.get(s);p||(p=new Map,this.sessionExternalDataMapping.set(s,p));let g=p.get(i),m=this.gpuDataManager.registerExternalBuffer(l,f,g);return p.set(i,[m,l]),m}unregisterBuffers(s){let i=this.sessionExternalDataMapping.get(s);i&&(i.forEach(l=>this.gpuDataManager.unregisterExternalBuffer(l[0])),this.sessionExternalDataMapping.delete(s))}getBuffer(s){let i=this.gpuDataManager.get(s);if(!i)throw new Error(`no GPU data for buffer: ${s}`);return i.buffer}createDownloader(s,i,l){return async()=>{let f=await St(this,s,i);return N(f.buffer,l)}}writeTimestamp(s){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,s)}setQueryType(){var s;this.queryType="none",(((s=this.env.webgpu.profiling)==null?void 0:s.mode)==="default"||(typeof this.env.trace>"u"?this.env.wasm.trace:this.env.trace))&&(this.device.features.has("chromium-experimental-timestamp-query-inside-passes")?this.queryType="inside-passes":this.device.features.has("timestamp-query")&&(this.queryType="at-passes"),this.queryType!=="none"&&typeof this.querySet>"u"&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){Tr("info","captureBegin"),this.capturedCommandList.get(this.currentSessionId)||this.capturedCommandList.set(this.currentSessionId,[]),this.capturedPendingKernels.get(this.currentSessionId)||this.capturedPendingKernels.set(this.currentSessionId,[]),this.flush(),this.sessionStatus="capturing"}captureEnd(){Tr("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){Tr("info","replay"),this.sessionStatus="replaying";let s=this.capturedCommandList.get(this.currentSessionId),i=this.capturedPendingKernels.get(this.currentSessionId),l=s.length;this.pendingKernels=[];for(let f=0;f=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onCreateSession(){this.gpuDataManager.onCreateSession()}onReleaseSession(s){this.unregisterBuffers(s),this.capturedCommandList.has(s)&&this.capturedCommandList.delete(s),this.capturedPendingKernels.has(s)&&this.capturedPendingKernels.delete(s),this.gpuDataManager.onReleaseSession(s)}onRunStart(s){this.currentSessionId=s,this.setQueryType()}}}),no,li,so,Vr,an,ks,fa,Ra,fl=c(()=>{Ie(),no=1,li=()=>no++,so=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),Vr=(s,i)=>{let l=so.get(s);if(!l)throw new Error("Unsupported data type.");return i.length>0?Math.ceil(i.reduce((f,p)=>f*p)*l/8):0},an=class{constructor(s){this.sessionId=s.sessionId,this.mlContext=s.context,this.mlTensor=s.tensor,this.dataType=s.dataType,this.tensorShape=s.shape}get tensor(){return this.mlTensor}get type(){return this.dataType}get shape(){return this.tensorShape}get byteLength(){return Vr(this.dataType,this.tensorShape)}destroy(){Tr("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(s){this.mlContext.writeTensor(this.mlTensor,s)}async read(s){return s?this.mlContext.readTensor(this.mlTensor,s):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(s,i,l){return this.mlContext===s&&this.dataType===i&&this.tensorShape.length===l.length&&this.tensorShape.every((f,p)=>f===l[p])}},ks=class{constructor(s,i){this.tensorManager=s,this.wrapper=i}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(s,i,l,f){if(this.wrapper){if(this.wrapper.canReuseTensor(s,i,l))return this.wrapper.tensor;if(f){if(this.wrapper.byteLength!==Vr(i,l))throw new Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let p=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(i,l,p,!0,!0),f&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(s){if(this.wrapper)if(s.byteLength===this.wrapper.byteLength){this.wrapper.write(s);return}else Tr("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor();this.activeUpload?this.activeUpload.set(s):this.activeUpload=new Uint8Array(s)}async download(s){if(this.activeUpload)if(s){s instanceof ArrayBuffer?new Uint8Array(s).set(this.activeUpload):new Uint8Array(s.buffer,s.byteOffset,s.byteLength).set(this.activeUpload);return}else return this.activeUpload.buffer;if(!this.wrapper)throw new Error("Tensor has not been created.");return s?this.wrapper.read(s):this.wrapper.read()}},fa=class{constructor(s){this.backend=s,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}reserveTensorId(){let s=li();return this.tensorTrackersById.set(s,new ks(this)),s}releaseTensorId(s){let i=this.tensorTrackersById.get(s);i&&(this.tensorTrackersById.delete(s),i.tensorWrapper&&this.releaseTensor(i.tensorWrapper))}async ensureTensor(s,i,l,f){Tr("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${s}, dataType: ${i}, shape: ${l}, copyOld: ${f}}`);let p=this.tensorTrackersById.get(s);if(!p)throw new Error("Tensor not found.");return p.ensureTensor(this.backend.currentContext,i,l,f)}upload(s,i){let l=this.tensorTrackersById.get(s);if(!l)throw new Error("Tensor not found.");l.upload(i)}async download(s,i){Tr("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${s}, dstBuffer: ${i==null?void 0:i.byteLength}}`);let l=this.tensorTrackersById.get(s);if(!l)throw new Error("Tensor not found.");return l.download(i)}releaseTensorsForSession(s){for(let i of this.freeTensors)i.sessionId===s&&i.destroy();this.freeTensors=this.freeTensors.filter(i=>i.sessionId!==s)}registerTensor(s,i,l,f){let p=li(),g=new an({sessionId:this.backend.currentSessionId,context:s,tensor:i,dataType:l,shape:f});return this.tensorTrackersById.set(p,new ks(this,g)),this.externalTensors.add(g),p}async getCachedTensor(s,i,l,f,p){let g=this.backend.currentSessionId,m=this.backend.currentContext;for(let[x,P]of this.freeTensors.entries())if(P.canReuseTensor(m,s,i)){Tr("verbose",()=>`[WebNN] Reusing tensor {dataType: ${s}, shape: ${i}}`);let D=this.freeTensors.splice(x,1)[0];return D.sessionId=g,D}Tr("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${s}, shape: ${i}}`);let v=await m.createTensor({dataType:s,shape:i,dimensions:i,usage:l,writable:f,readable:p});return new an({sessionId:g,context:m,tensor:v,dataType:s,shape:i})}releaseTensor(s){this.externalTensors.has(s)&&this.externalTensors.delete(s),this.freeTensors.push(s)}},Ra=(...s)=>new fa(...s)}),ao,pl,ml,G_=c(()=>{Wt(),zn(),ee(),fl(),Ie(),ao=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),pl=(s,i)=>{if(s===i)return!0;if(s===void 0||i===void 0)return!1;let l=Object.keys(s).sort(),f=Object.keys(i).sort();return l.length===f.length&&l.every((p,g)=>p===f[g]&&s[p]===i[p])},ml=class{constructor(s){this.tensorManager=Ra(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],Ia(s.logLevel,!!s.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(s){this.activeSessionId=s}async createMLContext(s){if(s instanceof GPUDevice){let l=this.mlContextCache.findIndex(f=>f.gpuDevice===s);if(l!==-1)return this.mlContextCache[l].mlContext;{let f=await navigator.ml.createContext(s);return this.mlContextCache.push({gpuDevice:s,mlContext:f}),f}}else if(s===void 0){let l=this.mlContextCache.findIndex(f=>f.options===void 0&&f.gpuDevice===void 0);if(l!==-1)return this.mlContextCache[l].mlContext;{let f=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:f}),f}}let i=this.mlContextCache.findIndex(l=>pl(l.options,s));if(i!==-1)return this.mlContextCache[i].mlContext;{let l=await navigator.ml.createContext(s);return this.mlContextCache.push({options:s,mlContext:l}),l}}get currentContext(){let s=this.getMLContext(this.currentSessionId);if(!s)throw new Error(`No MLContext found for session ${this.currentSessionId}`);return s}registerMLContext(s,i){this.mlContextBySessionId.set(s,i);let l=this.sessionIdsByMLContext.get(i);l||(l=new Set,this.sessionIdsByMLContext.set(i,l)),l.add(s)}onReleaseSession(s){let i=this.mlContextBySessionId.get(s);if(!i)return;this.tensorManager.releaseTensorsForSession(s),this.mlContextBySessionId.delete(s);let l=this.sessionIdsByMLContext.get(i);if(l.delete(s),l.size===0){this.sessionIdsByMLContext.delete(i);let f=this.mlContextCache.findIndex(p=>p.mlContext===i);f!==-1&&this.mlContextCache.splice(f,1)}}getMLContext(s){return this.mlContextBySessionId.get(s)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(s){Tr("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${s}}`),this.tensorManager.releaseTensorId(s)}async ensureTensor(s,i,l,f){let p=ao.get(i);if(!p)throw new Error(`Unsupported ONNX data type: ${i}`);return this.tensorManager.ensureTensor(s,p,l,f)}uploadTensor(s,i){if(!Dr().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");Tr("verbose",()=>`[WebNN] uploadTensor {tensorId: ${s}, data: ${i.byteLength}}`),this.tensorManager.upload(s,i)}async downloadTensor(s,i){return this.tensorManager.download(s,i)}createMLTensorDownloader(s,i){return async()=>{let l=await this.tensorManager.download(s);return N(l,i)}}registerMLTensor(s,i,l){let f=ao.get(i);if(!f)throw new Error(`Unsupported ONNX data type: ${i}`);let p=this.tensorManager.registerTensor(this.currentContext,s,f,l);return Tr("verbose",()=>`[WebNN] registerMLTensor {tensor: ${s}, dataType: ${f}, dimensions: ${l}} -> {tensorId: ${p}}`),p}registerMLConstant(s,i,l,f,p,g){if(!g)throw new Error("External mounted files are not available.");let m=s;s.startsWith("./")&&(m=s.substring(2));let v=g.get(m);if(!v)throw new Error(`File with name ${m} not found in preloaded files.`);if(i+l>v.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let x=v.slice(i,i+l).buffer,P;switch(p.dataType){case"float32":P=new Float32Array(x);break;case"float16":P=new Uint16Array(x);break;case"int32":P=new Int32Array(x);break;case"uint32":P=new Uint32Array(x);break;case"int64":P=new BigInt64Array(x);break;case"uint64":P=new BigUint64Array(x);break;case"int8":P=new Int8Array(x);break;case"int4":case"uint4":case"uint8":P=new Uint8Array(x);break;default:throw new Error(`Unsupported data type: ${p.dataType} in creating WebNN Constant from external data.`)}return Tr("verbose",()=>`[WebNN] registerMLConstant {dataType: ${p.dataType}, shape: ${p.shape}}}`),f.constant(p,P)}flush(){}}}),_l={};h(_l,{init:()=>zf});var Fa,gl,zf,Uf=c(()=>{Wt(),jf(),Ie(),jt(),G_(),Fa=class nw{constructor(i,l,f,p){this.module=i,this.dataType=l,this.data=f,this.dims=p}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let i=ze.size(this.dims);return i===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,i)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let i=ze.size(this.dims);return i===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,i)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let i=ze.size(this.dims);return i===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,i)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw new Error("Invalid data type");let i=ze.size(this.dims);return i===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,i)}reshape(i){if(ze.size(i)!==ze.size(this.dims))throw new Error("Invalid new shape");return new nw(this.module,this.dataType,this.data,i)}},gl=class{constructor(s,i,l){this.module=s,this.backend=i,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=i.adapterInfo,this.deviceInfo=i.deviceInfo;let f=s.PTR_SIZE,p=l/s.PTR_SIZE,g=f===4?"i32":"i64";this.opKernelContext=Number(s.getValue(f*p++,g));let m=Number(s.getValue(f*p++,g));this.outputCount=Number(s.getValue(f*p++,g)),this.customDataOffset=Number(s.getValue(f*p++,"*")),this.customDataSize=Number(s.getValue(f*p++,g));let v=[];for(let x=0;xtypeof v=="number"?this.inputs[v]:v))??this.inputs,f=(i==null?void 0:i.outputs)??[],p=(v,x,P)=>new Fa(this.module,x,this.output(v,P),P),g=(v,x)=>{let P=Un(v,x);if(!P)throw new Error(`Unsupported data type: ${v}`);let D=P>0?this.backend.gpuDataManager.create(P).id:0;return new Fa(this.module,v,D,x)};return this.backend.run(s,l,f,p,g,this.outputCount)}output(s,i){let l=this.module.stackSave();try{let f=this.module.PTR_SIZE,p=f===4?"i32":"i64",g=this.module.stackAlloc((1+i.length)*f);this.module.setValue(g,i.length,p);for(let m=0;m{let p=i.jsepInit;if(!p)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(s==="webgpu"){let g=new _s;await g.initialize(l,f),p("webgpu",[g,m=>g.alloc(Number(m)),m=>g.free(m),(m,v,x,P=!1)=>{if(P)Tr("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(m)}, dst=${Number(v)}, size=${Number(x)}`),g.memcpy(Number(m),Number(v));else{Tr("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(m)}, gpuDataId=${Number(v)}, size=${Number(x)}`);let D=i.HEAPU8.subarray(Number(m>>>0),Number(m>>>0)+Number(x));g.upload(Number(v),D)}},async(m,v,x)=>{Tr("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${m}, dataOffset=${v}, size=${x}`),await g.download(Number(m),()=>i.HEAPU8.subarray(Number(v)>>>0,Number(v+x)>>>0))},(m,v,x)=>g.createKernel(m,Number(v),x,i.UTF8ToString(i._JsepGetNodeName(Number(v)))),m=>g.releaseKernel(m),(m,v,x,P)=>{Tr("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${x}, kernel=${m}, contextDataOffset=${v}`);let D=new gl(i,g,Number(v));return g.computeKernel(Number(m),D,P)},()=>g.captureBegin(),()=>g.captureEnd(),()=>g.replay()])}else{let g=new ml(l);p("webnn",[g,()=>g.reserveTensorId(),m=>g.releaseTensorId(m),async(m,v,x,P)=>g.ensureTensor(m,v,x,P),(m,v)=>{g.uploadTensor(m,v)},async(m,v)=>g.downloadTensor(m,v)])}}}),io,Vf,Wf,pa,ma,Wn,H_,K_,q_,Z_,Y_,X_,ab=c(()=>{$i(),Oi(),Wt(),zn(),Ma(),Ya(),io=(s,i)=>{Dr()._OrtInit(s,i)!==0&&fr("Can't initialize onnxruntime.")},Vf=async s=>{io(s.wasm.numThreads,oa(s.logLevel))},Wf=async(s,i)=>{{let l=(Uf(),y(_l)).init;if(i==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let f=s.webgpu.adapter;if(f){if(typeof f.limits!="object"||typeof f.features!="object"||typeof f.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let p=s.webgpu.powerPreference;if(p!==void 0&&p!=="low-power"&&p!=="high-performance")throw new Error(`Invalid powerPreference setting: "${p}"`);let g=s.webgpu.forceFallbackAdapter;if(g!==void 0&&typeof g!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${g}"`);if(f=await navigator.gpu.requestAdapter({powerPreference:p,forceFallbackAdapter:g}),!f)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}await l("webgpu",Dr(),s,f)}if(i==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await l("webnn",Dr(),s)}}},pa=new Map,ma=s=>{let i=Dr(),l=i.stackSave();try{let f=i.PTR_SIZE,p=i.stackAlloc(2*f);i._OrtGetInputOutputCount(s,p,p+f)!==0&&fr("Can't get session input/output count.");let g=f===4?"i32":"i64";return[Number(i.getValue(p,g)),Number(i.getValue(p+f,g))]}finally{i.stackRestore(l)}},Wn=s=>{let i=Dr(),l=i._malloc(s.byteLength);if(l===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${s.byteLength}.`);return i.HEAPU8.set(s,l),[l,s.byteLength]},H_=async(s,i)=>{var R,E,K;let l,f,p=Dr();Array.isArray(s)?[l,f]=s:s.buffer===p.HEAPU8.buffer?[l,f]=[s.byteOffset,s.byteLength]:[l,f]=Wn(s);let g=0,m=0,v=0,x=[],P=[],D=[];try{if([m,x]=Za(i),(i==null?void 0:i.externalData)&&p.mountExternalData){let Ce=[];for(let Be of i.externalData){let je=typeof Be=="string"?Be:Be.path;Ce.push(ka(typeof Be=="string"?Be:Be.data).then(tt=>{p.mountExternalData(je,tt)}))}await Promise.all(Ce)}for(let Ce of(i==null?void 0:i.executionProviders)??[])if((typeof Ce=="string"?Ce:Ce.name)==="webnn"){if(p.shouldTransferToMLTensor=!1,typeof Ce!="string"){let Be=Ce,je=Be==null?void 0:Be.context,tt=Be==null?void 0:Be.gpuDevice,lt=Be==null?void 0:Be.deviceType,kt=Be==null?void 0:Be.powerPreference;je?p.currentContext=je:tt?p.currentContext=await p.jsepCreateMLContext(tt):p.currentContext=await p.jsepCreateMLContext({deviceType:lt,powerPreference:kt})}else p.currentContext=await p.jsepCreateMLContext();break}g=await p._OrtCreateSession(l,f,m),g===0&&fr("Can't create a session."),(R=p.jsepOnCreateSession)==null||R.call(p),p.currentContext&&(p.jsepRegisterMLContext(g,p.currentContext),p.currentContext=void 0,p.shouldTransferToMLTensor=!0);let[q,Y]=ma(g),ne=!!(i!=null&&i.enableGraphCapture),se=[],te=[],ye=[];for(let Ce=0;CeCe==="gpu-buffer"||Ce==="ml-tensor")&&(v=p._OrtCreateBinding(g),v===0&&fr("Can't create IO binding."),be={handle:v,outputPreferredLocations:ye,outputPreferredLocationsEncoded:ye.map(Ce=>Aa(Ce))}),pa.set(g,[g,P,D,be,ne,!1]),[g,se,te]}catch(q){throw P.forEach(Y=>p._OrtFree(Y)),D.forEach(Y=>p._OrtFree(Y)),v!==0&&p._OrtReleaseBinding(v)!==0&&fr("Can't release IO binding."),g!==0&&p._OrtReleaseSession(g)!==0&&fr("Can't release session."),q}finally{p._free(l),m!==0&&p._OrtReleaseSessionOptions(m)!==0&&fr("Can't release session options."),x.forEach(q=>p._free(q)),(K=p.unmountExternalData)==null||K.call(p)}},K_=s=>{var x;let i=Dr(),l=pa.get(s);if(!l)throw new Error(`cannot release session. invalid session id: ${s}`);let[f,p,g,m,v]=l;m&&(v&&i._OrtClearBoundOutputs(m.handle)!==0&&fr("Can't clear bound outputs."),i._OrtReleaseBinding(m.handle)!==0&&fr("Can't release IO binding.")),(x=i.jsepOnReleaseSession)==null||x.call(i,s),p.forEach(P=>i._OrtFree(P)),g.forEach(P=>i._OrtFree(P)),i._OrtReleaseSession(f)!==0&&fr("Can't release session."),pa.delete(s)},q_=(s,i,l,f,p,g=!1)=>{if(!s){i.push(0);return}let m=Dr(),v=m.PTR_SIZE,x=s[0],P=s[1],D=s[3],R,E;if(x==="string"&&(D==="gpu-buffer"||D==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(g&&D!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${p} when enableGraphCapture is true.`);if(D==="gpu-buffer"){let Y=s[2].gpuBuffer;E=Un(zs(x),P);let ne=m.jsepRegisterBuffer;if(!ne)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');R=ne(f,p,Y,E)}else if(D==="ml-tensor"){let Y=s[2].mlTensor;E=Un(zs(x),P);let ne=m.jsepRegisterMLTensor;if(!ne)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');R=ne(Y,zs(x),P)}else{let Y=s[2];if(Array.isArray(Y)){E=v*Y.length,R=m._malloc(E),l.push(R);for(let ne=0;nem.setValue(q+se*v,ne,v===4?"i32":"i64"));let Y=m._OrtCreateTensor(zs(x),R,E,q,P.length,Aa(D));Y===0&&fr(`Can't create tensor for input/output. session=${f}, index=${p}.`),i.push(Y)}finally{m.stackRestore(K)}},Z_=async(s,i,l,f,p,g)=>{var ir,cr;let m=Dr(),v=m.PTR_SIZE,x=pa.get(s);if(!x)throw new Error(`cannot run inference. invalid session id: ${s}`);let P=x[0],D=x[1],R=x[2],E=x[3],K=x[4],q=x[5],Y=i.length,ne=f.length,se=0,te=[],ye=[],be=[],Ce=[],Be=m.stackSave(),je=m.stackAlloc(Y*v),tt=m.stackAlloc(Y*v),lt=m.stackAlloc(ne*v),kt=m.stackAlloc(ne*v);try{(ir=m.jsepOnRunStart)==null||ir.call(m,P),[se,te]=Bs(g);for(let Rt=0;Rton*Wr,1);Or=rs(Sr);let lo=E==null?void 0:E.outputPreferredLocations[f[Rt]];if(Or==="string"){if(lo==="gpu-buffer"||lo==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let on=[];for(let Wr=0;Wr<_a;Wr++){let di=m.getValue(ut+Wr*v,"*"),Kf=m.getValue(ut+(Wr+1)*v,"*"),rg=Wr===_a-1?void 0:Kf-di;on.push(m.UTF8ToString(di,rg))}pr.push([Or,Pn,on,"cpu"])}else if(lo==="gpu-buffer"&&_a>0){let on=m.jsepGetBuffer;if(!on)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Wr=on(ut),di=Un(Sr,_a);if(di===void 0||!Ca(Or))throw new Error(`Unsupported data type: ${Or}`);Kt=!0,pr.push([Or,Pn,{gpuBuffer:Wr,download:m.jsepCreateDownloader(Wr,di,Or),dispose:()=>{m._OrtReleaseTensor(zt)!==0&&fr("Can't release tensor.")}},"gpu-buffer"])}else if(lo==="ml-tensor"&&_a>0){let on=m.jsepEnsureTensor;if(!on)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Un(Sr,_a)===void 0||!Sa(Or))throw new Error(`Unsupported data type: ${Or}`);let Wr=await on(ut,Sr,Pn,!1);Kt=!0,pr.push([Or,Pn,{mlTensor:Wr,download:m.jsepCreateMLTensorDownloader(ut,Or),dispose:()=>{m.jsepReleaseTensorId(ut),m._OrtReleaseTensor(zt)}},"ml-tensor"])}else{let on=Pa(Or),Wr=new on(_a);new Uint8Array(Wr.buffer,Wr.byteOffset,Wr.byteLength).set(m.HEAPU8.subarray(ut,ut+Wr.byteLength)),pr.push([Or,Pn,Wr,"cpu"])}}finally{m.stackRestore(Br),Or==="string"&&ut&&m._free(ut),Kt||m._OrtReleaseTensor(zt)}}return E&&!K&&(m._OrtClearBoundOutputs(E.handle)!==0&&fr("Can't clear bound outputs."),pa.set(s,[P,D,R,E,K,!1])),pr}finally{m.stackRestore(Be),ye.forEach(Pt=>m._OrtReleaseTensor(Pt)),be.forEach(Pt=>m._OrtReleaseTensor(Pt)),Ce.forEach(Pt=>m._free(Pt)),se!==0&&m._OrtReleaseRunOptions(se),te.forEach(Pt=>m._free(Pt))}},Y_=s=>{let i=Dr(),l=pa.get(s);if(!l)throw new Error("invalid session id");let f=l[0],p=i._OrtEndProfiling(f);p===0&&fr("Can't get an profile file name."),i._OrtFree(p)},X_=s=>{let i=[];for(let l of s){let f=l[2];!Array.isArray(f)&&"buffer"in f&&i.push(f.buffer)}return i}}),ci,us,bl,Gf,Hf,xm,Q_,Mm,oo,uo,ib,ob,ub,lb,cb,db,hb,fb,pb=c(()=>{Ze(),ab(),zn(),Ns(),ci=()=>!!j.wasm.proxy&&typeof document<"u",bl=!1,Gf=!1,Hf=!1,Mm=new Map,oo=(s,i)=>{let l=Mm.get(s);l?l.push(i):Mm.set(s,[i])},uo=()=>{if(bl||!Gf||Hf||!us)throw new Error("worker not ready")},ib=s=>{switch(s.data.type){case"init-wasm":bl=!1,s.data.err?(Hf=!0,Q_[1](s.data.err)):(Gf=!0,Q_[0]()),xm&&(URL.revokeObjectURL(xm),xm=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let i=Mm.get(s.data.type);s.data.err?i.shift()[1](s.data.err):i.shift()[0](s.data.out);break}}},ob=async()=>{if(!Gf){if(bl)throw new Error("multiple calls to 'initWasm()' detected.");if(Hf)throw new Error("previous call to 'initWasm()' failed.");if(bl=!0,ci())return new Promise((s,i)=>{us==null||us.terminate(),ia().then(([l,f])=>{var p;try{us=f,us.onerror=m=>i(m),us.onmessage=ib,Q_=[s,i];let g={type:"init-wasm",in:j};!g.in.wasm.wasmPaths&&(l||(p=import.meta.url)!=null&&p.startsWith("file:"))&&(g.in.wasm.wasmPaths={wasm:new URL(t("./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm"),t.b).href}),us.postMessage(g),xm=l}catch(g){i(g)}},i)});try{await Ps(j.wasm),await Vf(j),Gf=!0}catch(s){throw Hf=!0,s}finally{bl=!1}}},ub=async s=>{if(ci())return uo(),new Promise((i,l)=>{oo("init-ep",[i,l]);let f={type:"init-ep",in:{epName:s,env:j}};us.postMessage(f)});await Wf(j,s)},lb=async s=>ci()?(uo(),new Promise((i,l)=>{oo("copy-from",[i,l]);let f={type:"copy-from",in:{buffer:s}};us.postMessage(f,[s.buffer])})):Wn(s),cb=async(s,i)=>{if(ci()){if(i!=null&&i.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return uo(),new Promise((l,f)=>{oo("create",[l,f]);let p={type:"create",in:{model:s,options:{...i}}},g=[];s instanceof Uint8Array&&g.push(s.buffer),us.postMessage(p,g)})}else return H_(s,i)},db=async s=>{if(ci())return uo(),new Promise((i,l)=>{oo("release",[i,l]);let f={type:"release",in:s};us.postMessage(f)});K_(s)},hb=async(s,i,l,f,p,g)=>{if(ci()){if(l.some(m=>m[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(p.some(m=>m))throw new Error("pre-allocated output tensor is not supported for proxy.");return uo(),new Promise((m,v)=>{oo("run",[m,v]);let x=l,P={type:"run",in:{sessionId:s,inputIndices:i,inputs:x,outputIndices:f,options:g}};us.postMessage(P,X_(x))})}else return Z_(s,i,l,f,p,g)},fb=async s=>{if(ci())return uo(),new Promise((i,l)=>{oo("end-profiling",[i,l]);let f={type:"end-profiling",in:s};us.postMessage(f)});Y_(s)}}),J_,mb,_b,jv=c(()=>{Ze(),pb(),Wt(),rt(),Ya(),J_=(s,i)=>{switch(s.location){case"cpu":return[s.type,s.dims,s.data,"cpu"];case"gpu-buffer":return[s.type,s.dims,{gpuBuffer:s.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[s.type,s.dims,{mlTensor:s.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${s.location} for ${i()}`)}},mb=s=>{switch(s[3]){case"cpu":return new he(s[0],s[2],s[1]);case"gpu-buffer":{let i=s[0];if(!Ca(i))throw new Error(`not supported data type: ${i} for deserializing GPU tensor`);let{gpuBuffer:l,download:f,dispose:p}=s[2];return he.fromGpuBuffer(l,{dataType:i,dims:s[1],download:f,dispose:p})}case"ml-tensor":{let i=s[0];if(!Sa(i))throw new Error(`not supported data type: ${i} for deserializing MLTensor tensor`);let{mlTensor:l,download:f,dispose:p}=s[2];return he.fromMLTensor(l,{dataType:i,dims:s[1],download:f,dispose:p})}default:throw new Error(`invalid data location: ${s[3]}`)}},_b=class{async fetchModelAndCopyToWasmMemory(s){return lb(await ka(s))}async loadModel(s,i){Ge();let l;typeof s=="string"?l=await this.fetchModelAndCopyToWasmMemory(s):l=s,[this.sessionId,this.inputNames,this.outputNames]=await cb(l,i),We()}async dispose(){return db(this.sessionId)}async run(s,i,l){Ge();let f=[],p=[];Object.entries(s).forEach(R=>{let E=R[0],K=R[1],q=this.inputNames.indexOf(E);if(q===-1)throw new Error(`invalid input '${E}'`);f.push(K),p.push(q)});let g=[],m=[];Object.entries(i).forEach(R=>{let E=R[0],K=R[1],q=this.outputNames.indexOf(E);if(q===-1)throw new Error(`invalid output '${E}'`);g.push(K),m.push(q)});let v=f.map((R,E)=>J_(R,()=>`input "${this.inputNames[p[E]]}"`)),x=g.map((R,E)=>R?J_(R,()=>`output "${this.outputNames[m[E]]}"`):null),P=await hb(this.sessionId,p,v,m,x,l),D={};for(let R=0;Rtg,initializeFlags:()=>eg,wasmBackend:()=>bb});var eg,tg,bb,zv=c(()=>{Ze(),pb(),jv(),eg=()=>{if((typeof j.wasm.initTimeout!="number"||j.wasm.initTimeout<0)&&(j.wasm.initTimeout=0),j.wasm.simd===!1&&console.warn('Deprecated property "env.wasm.simd" is set to false. non-SIMD build is no longer provided, and this setting will be ignored.'),typeof j.wasm.proxy!="boolean"&&(j.wasm.proxy=!1),typeof j.wasm.trace!="boolean"&&(j.wasm.trace=!1),typeof j.wasm.numThreads!="number"||!Number.isInteger(j.wasm.numThreads)||j.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)j.wasm.numThreads=1;else{let s=typeof navigator>"u"?d("node:os").cpus().length:navigator.hardwareConcurrency;j.wasm.numThreads=Math.min(4,Math.ceil((s||1)/2))}},tg=class{async init(s){eg(),await ob(),await ub(s)}async createInferenceSessionHandler(s,i){let l=new _b;return await l.loadModel(s,i),Promise.resolve(l)}},bb=new tg});Ze(),Ze(),Ze();var Uv="1.21.0-dev.20250114-228dd16893",Vv=Fe;{let s=(zv(),y(gb)).wasmBackend;S("webgpu",s,5),S("webnn",s,5),S("cpu",s,10),S("wasm",s,10)}Object.defineProperty(j.versions,"web",{value:Uv,enumerable:!0});/** * @license * Copyright 2021 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= *//** * @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= *//** * @license * Copyright 2019 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */},"./src/backends/onnx.js":(r,e,t)=>{var n;t.r(e),t.d(e,{Tensor:()=>d.Tensor,createInferenceSession:()=>H,deviceToExecutionProviders:()=>S,isONNXProxy:()=>U,isONNXTensor:()=>B});var a=t("./src/env.js"),o=t("?2ce3"),u=t("./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs?3a96"),d=t("./node_modules/onnxruntime-common/dist/esm/index.js");const c=Object.freeze({auto:null,gpu:null,cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",webnn:{name:"webnn",deviceType:"cpu"},"webnn-npu":{name:"webnn",deviceType:"npu"},"webnn-gpu":{name:"webnn",deviceType:"gpu"},"webnn-cpu":{name:"webnn",deviceType:"cpu"}}),h=[];let _,y;const w=Symbol.for("onnxruntime");if(w in globalThis)y=globalThis[w];else if(a.apis.IS_NODE_ENV){switch(y=o??(n||(n=t.t(o,2))),process.platform){case"win32":h.push("dml");break;case"linux":process.arch==="x64"&&h.push("cuda");break}h.push("cpu"),_=["cpu"]}else y=u,a.apis.IS_WEBNN_AVAILABLE&&h.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),a.apis.IS_WEBGPU_AVAILABLE&&h.push("webgpu"),h.push("wasm"),_=["wasm"];const M=y.InferenceSession;function S(F=null){if(!F)return _;switch(F){case"auto":return h;case"gpu":return h.filter(I=>["webgpu","cuda","dml","webnn-gpu"].includes(I))}if(h.includes(F))return[c[F]??F];throw new Error(`Unsupported device: "${F}". Should be one of: ${h.join(", ")}.`)}let G=null;async function H(F,I,k){G&&await G;const $=M.create(F,I);G??(G=$);const j=await $;return j.config=k,j}function B(F){return F instanceof y.Tensor}const z=y==null?void 0:y.env;z!=null&&z.wasm&&(z.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${a.env.version}/dist/`,z.wasm.proxy=!1,(typeof crossOriginIsolated>"u"||!crossOriginIsolated)&&(z.wasm.numThreads=1)),z!=null&&z.webgpu&&(z.webgpu.powerPreference="high-performance");function U(){var F;return(F=z==null?void 0:z.wasm)==null?void 0:F.proxy}a.env.backends.onnx=z},"./src/base/feature_extraction_utils.js":(r,e,t)=>{t.r(e),t.d(e,{FeatureExtractor:()=>u,validate_audio_inputs:()=>d});var n=t("./src/utils/constants.js"),a=t("./src/utils/generic.js"),o=t("./src/utils/hub.js");class u extends a.Callable{constructor(h){super(),this.config=h}static async from_pretrained(h,_){const y=await(0,o.getModelJSON)(h,n.FEATURE_EXTRACTOR_NAME,!0,_);return new this(y)}}function d(c,h){var _;if(!(c instanceof Float32Array||c instanceof Float64Array))throw new Error(`${h} expects input to be a Float32Array or a Float64Array, but got ${((_=c==null?void 0:c.constructor)==null?void 0:_.name)??typeof c} instead. If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}},"./src/base/image_processors_utils.js":(r,e,t)=>{t.r(e),t.d(e,{ImageProcessor:()=>F,center_to_corners_format:()=>y,post_process_instance_segmentation:()=>U,post_process_object_detection:()=>w,post_process_panoptic_segmentation:()=>z,post_process_semantic_segmentation:()=>M});var n=t("./src/utils/generic.js"),a=t("./src/utils/tensor.js"),o=t("./src/utils/maths.js");t("./src/utils/image.js");var u=t("./src/utils/core.js"),d=t("./src/utils/hub.js"),c=t("./src/utils/constants.js");function h(I,k,$=0,j=null){const ce=I/k;let ue=(0,o.bankers_round)(ce)*k;return j!==null&&ue>j&&(ue=Math.floor(ce)*k),ue<$&&(ue=Math.ceil(ce)*k),ue}function _([I,k],$){return[Math.max(Math.floor(I/$),1)*$,Math.max(Math.floor(k/$),1)*$]}function y([I,k,$,j]){return[I-$/2,k-j/2,I+$/2,k+j/2]}function w(I,k=.5,$=null,j=!1){const ce=I.logits,ue=I.pred_boxes,[Pe,Te,ie]=ce.dims;if($!==null&&$.length!==Pe)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let oe=[];for(let re=0;rek&&X.push(ke)}else{let ke=(0,o.max)(pe.data)[1];if(ke===ie-1||(le=(0,o.softmax)(pe.data),le[ke]Xe*ge[(ae+1)%2])),ve.boxes.push(Re),ve.classes.push(ke),ve.scores.push(le[ke])}}oe.push(ve)}return oe}function M(I,k=null){const $=I.logits,j=$.dims[0];if(k!==null&&k.length!==j)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const ce=[];for(let ue=0;uege[X]&&(ge[X]=pe[X],ve[X]=$e)}const me=new Array(Te.dims[0]);for(let $e=0;$e$e!==void 0);ce.push({segmentation:re,labels:Le})}return ce}function S(I,k,$,j){const ce=[],ue=[],Pe=[];for(let Te=0;Te$&&(ce.push(oe),ue.push(ve),Pe.push(re))}return[ce,ue,Pe]}function G(I,k,$,j=.5,ce=.8){const ue=[];let Pe=0,Te=0;const ie=k[$].data;for(let re=0;re=j&&++Te;let oe=Pe>0&&Te>0;return oe&&(oe=Pe/Te>ce),[oe,ue]}function H(I,k,$,j,ce,ue=null,Pe=null){const[Te,ie]=Pe??I[0].dims,oe=new a.Tensor("int32",new Int32Array(Te*ie),[Te,ie]),re=[];if(Pe!==null)for(let $e=0;$eve[le]&&(ge[le]=$e,ve[le]=X[le])}let me=0;const Le=oe.data;for(let $e=0;$e<$.length;++$e){const pe=$[$e],[X,le]=G(ge,I,$e,j,ce);if(X){++me;for(const ke of le)Le[ke]=me;re.push({id:me,label_id:pe,score:k[$e]})}}return[oe,re]}function B(I,k,$=28,j=56*56,ce=14*14*4*1280){if(I<$||k<$)throw new Error(`height:${I} or width:${k} must be larger than factor:${$}`);if(Math.max(I,k)/Math.min(I,k)>200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(I,k)/Math.min(I,k)}`);let ue=Math.round(I/$)*$,Pe=Math.round(k/$)*$;if(ue*Pe>ce){const Te=Math.sqrt(I*k/ce);ue=Math.floor(I/Te/$)*$,Pe=Math.floor(k/Te/$)*$}else if(ue*Peue?oe=Math.floor(ue*ie/ce):ue>ce&&(ie=Math.floor(ce*oe/ue)),await k.resize(oe,ie,{resample:j}))}async crop_margin(k,$=200){const j=k.clone().grayscale(),ce=(0,o.min)(j.data)[0],Pe=(0,o.max)(j.data)[0]-ce;if(Pe===0)return k;const Te=$/255;let ie=j.width,oe=j.height,re=0,ge=0;const ve=j.data;for(let me=0;methis.preprocess(ue)));return{pixel_values:(0,a.stack)(j.map(ue=>ue.pixel_values),0),original_sizes:j.map(ue=>ue.original_size),reshaped_input_sizes:j.map(ue=>ue.reshaped_input_size)}}static async from_pretrained(k,$){const j=await(0,d.getModelJSON)(k,c.IMAGE_PROCESSOR_NAME,!0,$);return new this(j)}}},"./src/base/processing_utils.js":(r,e,t)=>{t.r(e),t.d(e,{Processor:()=>u});var n=t("./src/utils/constants.js"),a=t("./src/utils/generic.js"),o=t("./src/utils/hub.js");class u extends a.Callable{constructor(c,h){super(),this.config=c,this.components=h}get image_processor(){return this.components.image_processor}get tokenizer(){return this.components.tokenizer}get feature_extractor(){return this.components.feature_extractor}apply_chat_template(c,h={}){if(!this.tokenizer)throw new Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(c,{tokenize:!1,...h})}batch_decode(...c){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.batch_decode(...c)}decode(...c){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.decode(...c)}async _call(c,...h){for(const _ of[this.image_processor,this.feature_extractor,this.tokenizer])if(_)return _(c,...h);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(c,h){const[_,y]=await Promise.all([this.uses_processor_config?(0,o.getModelJSON)(c,n.PROCESSOR_NAME,!0,h):{},Promise.all(this.classes.filter(w=>w in this).map(async w=>{const M=await this[w].from_pretrained(c,h);return[w.replace(/_class$/,""),M]})).then(Object.fromEntries)]);return new this(_,y)}}we(u,"classes",["image_processor_class","tokenizer_class","feature_extractor_class"]),we(u,"uses_processor_config",!1)},"./src/configs.js":(r,e,t)=>{t.r(e),t.d(e,{AutoConfig:()=>h,PretrainedConfig:()=>c,getKeyValueShapes:()=>d});var n=t("./src/utils/core.js"),a=t("./src/utils/hub.js");async function o(_,y){return await(0,a.getModelJSON)(_,"config.json",!0,y)}function u(_){const y={};let w={};switch(_.model_type){case"llava":case"paligemma":case"florence2":case"llava_onevision":case"idefics3":w=u(_.text_config);break;case"moondream1":w=u(_.phi_config);break;case"musicgen":w=u(_.decoder);break;case"multi_modality":w=u(_.language_config);break;case"gpt2":case"gptj":case"jais":case"codegen":case"gpt_bigcode":y.num_heads="n_head",y.num_layers="n_layer",y.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"falcon":y.num_heads="num_attention_heads",y.num_layers="num_hidden_layers",y.hidden_size="hidden_size";break;case"llama":case"olmo":case"olmo2":case"mobilellm":case"granite":case"cohere":case"mistral":case"starcoder2":case"qwen2":case"qwen2_vl":case"phi":case"phi3":case"phi3_v":y.num_heads="num_key_value_heads",y.num_layers="num_hidden_layers",y.hidden_size="hidden_size",y.num_attention_heads="num_attention_heads";break;case"gemma":case"gemma2":y.num_heads="num_key_value_heads",y.num_layers="num_hidden_layers",y.dim_kv="head_dim";break;case"openelm":y.num_heads="num_kv_heads",y.num_layers="num_transformer_layers",y.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":y.num_heads="num_heads",y.num_layers="num_layers",y.hidden_size="hidden_size";break;case"bloom":y.num_heads="n_head",y.num_layers="n_layer",y.hidden_size="hidden_size";break;case"mpt":y.num_heads="n_heads",y.num_layers="n_layers",y.hidden_size="d_model";break;case"exaone":y.num_heads="num_key_value_heads",y.num_layers="num_layers",y.dim_kv="head_dim",y.num_attention_heads="num_attention_heads";break;case"t5":case"mt5":case"longt5":y.num_decoder_layers="num_decoder_layers",y.num_decoder_heads="num_heads",y.decoder_dim_kv="d_kv",y.num_encoder_layers="num_layers",y.num_encoder_heads="num_heads",y.encoder_dim_kv="d_kv";break;case"bart":case"mbart":case"marian":case"whisper":case"m2m_100":case"blenderbot":case"blenderbot-small":case"florence2_language":y.num_decoder_layers="decoder_layers",y.num_decoder_heads="decoder_attention_heads",y.decoder_hidden_size="d_model",y.num_encoder_layers="encoder_layers",y.num_encoder_heads="encoder_attention_heads",y.encoder_hidden_size="d_model";break;case"speecht5":y.num_decoder_layers="decoder_layers",y.num_decoder_heads="decoder_attention_heads",y.decoder_hidden_size="hidden_size",y.num_encoder_layers="encoder_layers",y.num_encoder_heads="encoder_attention_heads",y.encoder_hidden_size="hidden_size";break;case"trocr":y.num_encoder_layers=y.num_decoder_layers="decoder_layers",y.num_encoder_heads=y.num_decoder_heads="decoder_attention_heads",y.encoder_hidden_size=y.decoder_hidden_size="d_model";break;case"musicgen_decoder":case"moonshine":y.num_encoder_layers=y.num_decoder_layers="num_hidden_layers",y.num_encoder_heads=y.num_decoder_heads="num_attention_heads",y.encoder_hidden_size=y.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":const S=u(_.decoder),G="num_decoder_layers"in S,H=(0,n.pick)(_,["model_type","is_encoder_decoder"]);return G?(H.num_decoder_layers=S.num_decoder_layers,H.num_decoder_heads=S.num_decoder_heads,H.decoder_hidden_size=S.decoder_hidden_size,H.num_encoder_layers=S.num_encoder_layers,H.num_encoder_heads=S.num_encoder_heads,H.encoder_hidden_size=S.encoder_hidden_size):(H.num_layers=S.num_layers,H.num_heads=S.num_heads,H.hidden_size=S.hidden_size),H}const M={...w,...(0,n.pick)(_,["model_type","multi_query","is_encoder_decoder"])};for(const S in y)M[S]=_[y[S]];return M}function d(_,{prefix:y="past_key_values",batch_size:w=1}={}){const M={},S=_.normalized_config;if(S.is_encoder_decoder&&"num_encoder_heads"in S&&"num_decoder_heads"in S){const G=S.encoder_dim_kv??S.encoder_hidden_size/S.num_encoder_heads,H=S.decoder_dim_kv??S.decoder_hidden_size/S.num_decoder_heads,B=[w,S.num_encoder_heads,0,G],z=[w,S.num_decoder_heads,0,H];for(let U=0;U{var j,ce;t.r(e),t.d(e,{apis:()=>H,env:()=>k});var n=t("?569f"),a=t("?3f59"),o=t("?154a");const u="3.3.1",d=typeof window<"u"&&typeof window.document<"u",c=typeof self<"u"&&((j=self.constructor)==null?void 0:j.name)==="DedicatedWorkerGlobalScope",h=typeof self<"u"&&"caches"in self,_=typeof navigator<"u"&&"gpu"in navigator,y=typeof navigator<"u"&&"ml"in navigator,w=typeof process<"u",M=w&&((ce=process==null?void 0:process.release)==null?void 0:ce.name)==="node",S=!$(n),G=!$(a),H=Object.freeze({IS_BROWSER_ENV:d,IS_WEBWORKER_ENV:c,IS_WEB_CACHE_AVAILABLE:h,IS_WEBGPU_AVAILABLE:_,IS_WEBNN_AVAILABLE:y,IS_PROCESS_AVAILABLE:w,IS_NODE_ENV:M,IS_FS_AVAILABLE:S,IS_PATH_AVAILABLE:G}),B=S&&G;let z="./";if(B){const ue=Object(import.meta).url;ue?z=a.dirname(a.dirname(o.fileURLToPath(ue))):typeof __dirname<"u"&&(z=a.dirname(__dirname))}const U=B?a.join(z,"/.cache/"):null,F="/models/",I=B?a.join(z,F):F,k={version:u,backends:{onnx:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(d||c),localModelPath:I,useFS:S,useBrowserCache:h,useFSCache:S,cacheDir:U,useCustomCache:!1,customCache:null};function $(ue){return Object.keys(ue).length===0}},"./src/generation/configuration_utils.js":(r,e,t)=>{t.r(e),t.d(e,{GenerationConfig:()=>a});var n=t("./src/utils/core.js");class a{constructor(u){we(this,"max_length",20);we(this,"max_new_tokens",null);we(this,"min_length",0);we(this,"min_new_tokens",null);we(this,"early_stopping",!1);we(this,"max_time",null);we(this,"do_sample",!1);we(this,"num_beams",1);we(this,"num_beam_groups",1);we(this,"penalty_alpha",null);we(this,"use_cache",!0);we(this,"temperature",1);we(this,"top_k",50);we(this,"top_p",1);we(this,"typical_p",1);we(this,"epsilon_cutoff",0);we(this,"eta_cutoff",0);we(this,"diversity_penalty",0);we(this,"repetition_penalty",1);we(this,"encoder_repetition_penalty",1);we(this,"length_penalty",1);we(this,"no_repeat_ngram_size",0);we(this,"bad_words_ids",null);we(this,"force_words_ids",null);we(this,"renormalize_logits",!1);we(this,"constraints",null);we(this,"forced_bos_token_id",null);we(this,"forced_eos_token_id",null);we(this,"remove_invalid_values",!1);we(this,"exponential_decay_length_penalty",null);we(this,"suppress_tokens",null);we(this,"streamer",null);we(this,"begin_suppress_tokens",null);we(this,"forced_decoder_ids",null);we(this,"guidance_scale",null);we(this,"num_return_sequences",1);we(this,"output_attentions",!1);we(this,"output_hidden_states",!1);we(this,"output_scores",!1);we(this,"return_dict_in_generate",!1);we(this,"pad_token_id",null);we(this,"bos_token_id",null);we(this,"eos_token_id",null);we(this,"encoder_no_repeat_ngram_size",0);we(this,"decoder_start_token_id",null);we(this,"generation_kwargs",{});Object.assign(this,(0,n.pick)(u,Object.getOwnPropertyNames(this)))}}},"./src/generation/logits_process.js":(r,e,t)=>{t.r(e),t.d(e,{ClassifierFreeGuidanceLogitsProcessor:()=>B,ForcedBOSTokenLogitsProcessor:()=>c,ForcedEOSTokenLogitsProcessor:()=>h,LogitsProcessor:()=>o,LogitsProcessorList:()=>d,LogitsWarper:()=>u,MinLengthLogitsProcessor:()=>S,MinNewTokensLengthLogitsProcessor:()=>G,NoBadWordsLogitsProcessor:()=>H,NoRepeatNGramLogitsProcessor:()=>w,RepetitionPenaltyLogitsProcessor:()=>M,SuppressTokensAtBeginLogitsProcessor:()=>_,TemperatureLogitsWarper:()=>z,TopKLogitsWarper:()=>F,TopPLogitsWarper:()=>U,WhisperTimeStampLogitsProcessor:()=>y});var n=t("./src/utils/generic.js");t("./src/utils/tensor.js");var a=t("./src/utils/maths.js");class o extends n.Callable{_call(k,$){throw Error("`_call` should be implemented in a subclass")}}class u extends n.Callable{_call(k,$){throw Error("`_call` should be implemented in a subclass")}}class d extends n.Callable{constructor(){super(),this.processors=[]}push(k){this.processors.push(k)}extend(k){this.processors.push(...k)}_call(k,$){let j=$;for(const ce of this.processors)j=ce(k,j);return j}[Symbol.iterator](){return this.processors.values()}}class c extends o{constructor(k){super(),this.bos_token_id=k}_call(k,$){for(let j=0;j=1&&ue[ue.length-1]>=this.timestamp_begin,Te=ue.length<2||ue[ue.length-2]>=this.timestamp_begin;if(Pe&&(Te?ce.subarray(this.timestamp_begin).fill(-1/0):ce.subarray(0,this.eos_token_id).fill(-1/0)),k[j].length===this.begin_index&&this.max_initial_timestamp_index!==null){const ge=this.timestamp_begin+this.max_initial_timestamp_index;ce.subarray(ge+1).fill(-1/0)}const ie=(0,a.log_softmax)(ce),oe=Math.log(ie.subarray(this.timestamp_begin).map(Math.exp).reduce((ge,ve)=>ge+ve)),re=(0,a.max)(ie.subarray(0,this.timestamp_begin))[0];oe>re&&ce.subarray(0,this.timestamp_begin).fill(-1/0)}return $}}class w extends o{constructor(k){super(),this.no_repeat_ngram_size=k}getNgrams(k){const $=k.length,j=[];for(let ue=0;ue<$+1-this.no_repeat_ngram_size;++ue){const Pe=[];for(let Te=0;Te1 to use the classifier free guidance processor, got guidance scale ${k}.`);this.guidance_scale=k}_call(k,$){if($.dims[0]!==2*k.length)throw new Error(`Logits should have twice the batch size of the input ids, the first half of batches corresponding to the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got batch size ${$.dims[0]} for the logits and ${k.length} for the input ids.`);const j=k.length,ce=$.slice([0,j],null),ue=$.slice([j,$.dims[0]],null);for(let Pe=0;Pe1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${k}`);if(!Number.isInteger(j)||j<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${j}`);this.top_p=k,this.filter_value=$,this.min_tokens_to_keep=j}}class F extends u{constructor(k,{filter_value:$=-1/0,min_tokens_to_keep:j=1}={}){if(super(),!Number.isInteger(k)||k<0)throw new Error(`\`top_k\` must be a positive integer, but is ${k}`);this.top_k=Math.max(k,j),this.filter_value=$}}},"./src/generation/logits_sampler.js":(r,e,t)=>{t.r(e),t.d(e,{LogitsSampler:()=>u});var n=t("./src/utils/generic.js"),a=t("./src/utils/tensor.js"),o=t("./src/utils/maths.js");t("./src/generation/configuration_utils.js");class u extends n.Callable{constructor(y){super(),this.generation_config=y}async _call(y){return this.sample(y)}async sample(y){throw Error("sample should be implemented in subclasses.")}getLogits(y,w){let M=y.dims.at(-1),S=y.data;if(w===-1)S=S.slice(-M);else{let G=w*M;S=S.slice(G,G+M)}return S}randomSelect(y){let w=0;for(let S=0;S1)return new h(y);if(y.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${y.num_return_sequences}.`);return new d(y)}}class d extends u{async sample(y){const w=(0,o.max)(y.data)[1];return[[BigInt(w),0]]}}class c extends u{async sample(y){let w=y.dims.at(-1);this.generation_config.top_k>0&&(w=Math.min(this.generation_config.top_k,w));const[M,S]=await(0,a.topk)(y,w),G=(0,o.softmax)(M.data);return Array.from({length:this.generation_config.num_beams},()=>{const H=this.randomSelect(G);return[S.data[H],Math.log(G[H])]})}}class h extends u{async sample(y){let w=y.dims.at(-1);this.generation_config.top_k>0&&(w=Math.min(this.generation_config.top_k,w));const[M,S]=await(0,a.topk)(y,w),G=(0,o.softmax)(M.data);return Array.from({length:this.generation_config.num_beams},(H,B)=>[S.data[B],Math.log(G[B])])}}},"./src/generation/stopping_criteria.js":(r,e,t)=>{t.r(e),t.d(e,{EosTokenCriteria:()=>d,InterruptableStoppingCriteria:()=>c,MaxLengthCriteria:()=>u,StoppingCriteria:()=>a,StoppingCriteriaList:()=>o});var n=t("./src/utils/generic.js");class a extends n.Callable{_call(_,y){throw Error("StoppingCriteria needs to be subclassed")}}class o extends n.Callable{constructor(){super(),this.criteria=[]}push(_){this.criteria.push(_)}extend(_){_ instanceof o?_=_.criteria:_ instanceof a&&(_=[_]),this.criteria.push(..._)}_call(_,y){const w=new Array(_.length).fill(!1);for(const M of this.criteria){const S=M(_,y);for(let G=0;Gy.length>=this.max_length)}}class d extends a{constructor(_){super(),Array.isArray(_)||(_=[_]),this.eos_token_id=_}_call(_,y){return _.map(w=>{const M=w.at(-1);return this.eos_token_id.some(S=>M==S)})}}class c extends a{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(_,y){return new Array(_.length).fill(this.interrupted)}}},"./src/generation/streamers.js":(r,e,t)=>{t.r(e),t.d(e,{BaseStreamer:()=>u,TextStreamer:()=>c,WhisperTextStreamer:()=>h});var n=t("./src/utils/core.js"),a=t("./src/tokenizers.js"),o=t("./src/env.js");class u{put(y){throw Error("Not implemented")}end(){throw Error("Not implemented")}}const d=o.apis.IS_PROCESS_AVAILABLE?_=>process.stdout.write(_):_=>console.log(_);class c extends u{constructor(y,{skip_prompt:w=!1,callback_function:M=null,token_callback_function:S=null,skip_special_tokens:G=!0,decode_kwargs:H={},...B}={}){super(),this.tokenizer=y,this.skip_prompt=w,this.callback_function=M??d,this.token_callback_function=S,this.decode_kwargs={skip_special_tokens:G,...H,...B},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put(y){var G;if(y.length>1)throw Error("TextStreamer only supports batch size of 1");if(this.skip_prompt&&this.next_tokens_are_prompt){this.next_tokens_are_prompt=!1;return}const w=y[0];(G=this.token_callback_function)==null||G.call(this,w),this.token_cache=(0,n.mergeArrays)(this.token_cache,w);const M=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let S;M.endsWith(` `)?(S=M.slice(this.print_len),this.token_cache=[],this.print_len=0):M.length>0&&(0,a.is_chinese_char)(M.charCodeAt(M.length-1))?(S=M.slice(this.print_len),this.print_len+=S.length):(S=M.slice(this.print_len,M.lastIndexOf(" ")+1),this.print_len+=S.length),this.on_finalized_text(S,!1)}end(){let y;this.token_cache.length>0?(y=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):y="",this.next_tokens_are_prompt=!0,this.on_finalized_text(y,!0)}on_finalized_text(y,w){var M,S;y.length>0&&((M=this.callback_function)==null||M.call(this,y)),w&&this.callback_function===d&&o.apis.IS_PROCESS_AVAILABLE&&((S=this.callback_function)==null||S.call(this,` `))}}class h extends c{constructor(y,{skip_prompt:w=!1,callback_function:M=null,token_callback_function:S=null,on_chunk_start:G=null,on_chunk_end:H=null,on_finalize:B=null,time_precision:z=.02,skip_special_tokens:U=!0,decode_kwargs:F={}}={}){super(y,{skip_prompt:w,skip_special_tokens:U,callback_function:M,token_callback_function:S,decode_kwargs:F}),this.timestamp_begin=y.timestamp_begin,this.on_chunk_start=G,this.on_chunk_end=H,this.on_finalize=B,this.time_precision=z,this.waiting_for_timestamp=!1}put(y){var M,S;if(y.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const w=y[0];if(w.length===1){const G=Number(w[0])-this.timestamp_begin;if(G>=0){const H=G*this.time_precision;this.waiting_for_timestamp?(M=this.on_chunk_end)==null||M.call(this,H):(S=this.on_chunk_start)==null||S.call(this,H),this.waiting_for_timestamp=!this.waiting_for_timestamp,y=[[]]}}return super.put(y)}end(){var y;super.end(),(y=this.on_finalize)==null||y.call(this)}}},"./src/models.js":(r,e,t)=>{t.r(e),t.d(e,{ASTForAudioClassification:()=>So,ASTModel:()=>Zl,ASTPreTrainedModel:()=>or,AlbertForMaskedLM:()=>Tr,AlbertForQuestionAnswering:()=>ei,AlbertForSequenceClassification:()=>Ia,AlbertModel:()=>Ja,AlbertPreTrainedModel:()=>Us,AutoModel:()=>cl,AutoModelForAudioClassification:()=>dl,AutoModelForAudioFrameClassification:()=>$f,AutoModelForCTC:()=>kf,AutoModelForCausalLM:()=>ym,AutoModelForDepthEstimation:()=>Ff,AutoModelForDocumentQuestionAnswering:()=>Of,AutoModelForImageClassification:()=>Tf,AutoModelForImageFeatureExtraction:()=>Df,AutoModelForImageMatting:()=>Lf,AutoModelForImageSegmentation:()=>xf,AutoModelForImageToImage:()=>Rf,AutoModelForMaskGeneration:()=>Af,AutoModelForMaskedLM:()=>wf,AutoModelForNormalEstimation:()=>Nf,AutoModelForObjectDetection:()=>Cf,AutoModelForPoseEstimation:()=>wm,AutoModelForQuestionAnswering:()=>vf,AutoModelForSemanticSegmentation:()=>Mf,AutoModelForSeq2SeqLM:()=>_f,AutoModelForSequenceClassification:()=>mf,AutoModelForSpeechSeq2Seq:()=>gf,AutoModelForTextToSpectrogram:()=>bf,AutoModelForTextToWaveform:()=>yf,AutoModelForTokenClassification:()=>bm,AutoModelForUniversalSegmentation:()=>Pf,AutoModelForVision2Seq:()=>Ef,AutoModelForXVector:()=>If,AutoModelForZeroShotObjectDetection:()=>Sf,BartForConditionalGeneration:()=>tr,BartForSequenceClassification:()=>kr,BartModel:()=>St,BartPretrainedModel:()=>yt,BaseModelOutput:()=>Ve,BeitForImageClassification:()=>yd,BeitModel:()=>bd,BeitPreTrainedModel:()=>gu,BertForMaskedLM:()=>Ke,BertForQuestionAnswering:()=>We,BertForSequenceClassification:()=>qe,BertForTokenClassification:()=>Ge,BertModel:()=>Se,BertPreTrainedModel:()=>he,BlenderbotForConditionalGeneration:()=>xn,BlenderbotModel:()=>ze,BlenderbotPreTrainedModel:()=>mn,BlenderbotSmallForConditionalGeneration:()=>yn,BlenderbotSmallModel:()=>Xr,BlenderbotSmallPreTrainedModel:()=>Cs,BloomForCausalLM:()=>Hc,BloomModel:()=>Gc,BloomPreTrainedModel:()=>su,CLIPModel:()=>oc,CLIPPreTrainedModel:()=>la,CLIPSegForImageSegmentation:()=>pc,CLIPSegModel:()=>fc,CLIPSegPreTrainedModel:()=>Ro,CLIPTextModel:()=>Bp,CLIPTextModelWithProjection:()=>uc,CLIPVisionModel:()=>jp,CLIPVisionModelWithProjection:()=>lc,CamembertForMaskedLM:()=>sa,CamembertForQuestionAnswering:()=>aa,CamembertForSequenceClassification:()=>Ts,CamembertForTokenClassification:()=>xs,CamembertModel:()=>qt,CamembertPreTrainedModel:()=>fs,CausalLMOutput:()=>Oa,CausalLMOutputWithPast:()=>Tm,ChineseCLIPModel:()=>ss,ChineseCLIPPreTrainedModel:()=>zp,ClapAudioModelWithProjection:()=>Sh,ClapModel:()=>Ph,ClapPreTrainedModel:()=>Qi,ClapTextModelWithProjection:()=>Ch,CodeGenForCausalLM:()=>Pc,CodeGenModel:()=>Uo,CodeGenPreTrainedModel:()=>Ni,CohereForCausalLM:()=>Wp,CohereModel:()=>Oc,CoherePreTrainedModel:()=>Xo,ConvBertForMaskedLM:()=>Lt,ConvBertForQuestionAnswering:()=>Rr,ConvBertForSequenceClassification:()=>Nt,ConvBertForTokenClassification:()=>br,ConvBertModel:()=>Ct,ConvBertPreTrainedModel:()=>bt,ConvNextForImageClassification:()=>Yp,ConvNextModel:()=>Fu,ConvNextPreTrainedModel:()=>Ru,ConvNextV2ForImageClassification:()=>Rd,ConvNextV2Model:()=>Xp,ConvNextV2PreTrainedModel:()=>Nu,DPTForDepthEstimation:()=>ni,DPTModel:()=>ku,DPTPreTrainedModel:()=>Au,DebertaForMaskedLM:()=>Ms,DebertaForQuestionAnswering:()=>jn,DebertaForSequenceClassification:()=>Fs,DebertaForTokenClassification:()=>Ns,DebertaModel:()=>ia,DebertaPreTrainedModel:()=>Kn,DebertaV2ForMaskedLM:()=>Ut,DebertaV2ForQuestionAnswering:()=>Ps,DebertaV2ForSequenceClassification:()=>pn,DebertaV2ForTokenClassification:()=>Ds,DebertaV2Model:()=>At,DebertaV2PreTrainedModel:()=>ot,DecisionTransformerModel:()=>jh,DecisionTransformerPreTrainedModel:()=>um,DeiTForImageClassification:()=>Eu,DeiTModel:()=>vu,DeiTPreTrainedModel:()=>$a,DepthAnythingForDepthEstimation:()=>Iu,DepthAnythingPreTrainedModel:()=>Cd,DepthProForDepthEstimation:()=>Id,DepthProPreTrainedModel:()=>kd,DetrForObjectDetection:()=>vd,DetrForSegmentation:()=>Ed,DetrModel:()=>wd,DetrObjectDetectionOutput:()=>Ws,DetrPreTrainedModel:()=>zi,DetrSegmentationOutput:()=>ca,Dinov2ForImageClassification:()=>Bu,Dinov2Model:()=>Fd,Dinov2PreTrainedModel:()=>Du,Dinov2WithRegistersForImageClassification:()=>zu,Dinov2WithRegistersModel:()=>Nd,Dinov2WithRegistersPreTrainedModel:()=>ju,DistilBertForMaskedLM:()=>Ma,DistilBertForQuestionAnswering:()=>fr,DistilBertForSequenceClassification:()=>en,DistilBertForTokenClassification:()=>ps,DistilBertModel:()=>zn,DistilBertPreTrainedModel:()=>Dr,DonutSwinModel:()=>Ld,DonutSwinPreTrainedModel:()=>Lu,EfficientNetForImageClassification:()=>Lh,EfficientNetModel:()=>Oh,EfficientNetPreTrainedModel:()=>Ku,ElectraForMaskedLM:()=>$n,ElectraForQuestionAnswering:()=>fn,ElectraForSequenceClassification:()=>Es,ElectraForTokenClassification:()=>na,ElectraModel:()=>nn,ElectraPreTrainedModel:()=>Yr,EsmForMaskedLM:()=>Ha,EsmForSequenceClassification:()=>Ka,EsmForTokenClassification:()=>qa,EsmModel:()=>$i,EsmPreTrainedModel:()=>Bs,ExaoneForCausalLM:()=>Cc,ExaoneModel:()=>Di,ExaonePreTrainedModel:()=>Go,FalconForCausalLM:()=>Mh,FalconModel:()=>xh,FalconPreTrainedModel:()=>Wu,FastViTForImageClassification:()=>Gp,FastViTModel:()=>ud,FastViTPreTrainedModel:()=>fu,Florence2ForConditionalGeneration:()=>rc,Florence2PreTrainedModel:()=>tc,GLPNForDepthEstimation:()=>Ou,GLPNModel:()=>Hi,GLPNPreTrainedModel:()=>$u,GPT2LMHeadModel:()=>_c,GPT2Model:()=>mc,GPT2PreTrainedModel:()=>Fo,GPTBigCodeForCausalLM:()=>Mc,GPTBigCodeModel:()=>xc,GPTBigCodePreTrainedModel:()=>zo,GPTJForCausalLM:()=>Tc,GPTJModel:()=>Ec,GPTJPreTrainedModel:()=>jo,GPTNeoForCausalLM:()=>yc,GPTNeoModel:()=>is,GPTNeoPreTrainedModel:()=>Do,GPTNeoXForCausalLM:()=>vc,GPTNeoXModel:()=>wc,GPTNeoXPreTrainedModel:()=>Bo,Gemma2ForCausalLM:()=>Fc,Gemma2Model:()=>Rc,Gemma2PreTrainedModel:()=>Jo,GemmaForCausalLM:()=>Lc,GemmaModel:()=>Cr,GemmaPreTrainedModel:()=>Qo,GraniteForCausalLM:()=>$c,GraniteModel:()=>Vp,GranitePreTrainedModel:()=>Yo,GroundingDinoForObjectDetection:()=>Bd,GroundingDinoPreTrainedModel:()=>Dd,GroupViTModel:()=>od,GroupViTPreTrainedModel:()=>hu,HieraForImageClassification:()=>xu,HieraModel:()=>xd,HieraPreTrainedModel:()=>Tu,HubertForCTC:()=>ch,HubertForSequenceClassification:()=>dh,HubertModel:()=>lh,HubertPreTrainedModel:()=>W_,IJepaForImageClassification:()=>ed,IJepaModel:()=>Jc,IJepaPreTrainedModel:()=>uu,Idefics3ForConditionalGeneration:()=>$o,Idefics3PreTrainedModel:()=>ac,ImageMattingOutput:()=>ui,JAISLMHeadModel:()=>bc,JAISModel:()=>gc,JAISPreTrainedModel:()=>No,JinaCLIPModel:()=>Fi,JinaCLIPPreTrainedModel:()=>Ri,JinaCLIPTextModel:()=>Lo,JinaCLIPVisionModel:()=>as,LlamaForCausalLM:()=>Up,LlamaModel:()=>Wo,LlamaPreTrainedModel:()=>Vo,LlavaForConditionalGeneration:()=>Li,LlavaOnevisionForConditionalGeneration:()=>Jl,LlavaPreTrainedModel:()=>Vs,LongT5ForConditionalGeneration:()=>Oe,LongT5Model:()=>Ae,LongT5PreTrainedModel:()=>fe,M2M100ForConditionalGeneration:()=>si,M2M100Model:()=>Ki,M2M100PreTrainedModel:()=>qd,MBartForCausalLM:()=>On,MBartForConditionalGeneration:()=>Gt,MBartForSequenceClassification:()=>mr,MBartModel:()=>rn,MBartPreTrainedModel:()=>Pr,MPNetForMaskedLM:()=>oa,MPNetForQuestionAnswering:()=>Aa,MPNetForSequenceClassification:()=>Ca,MPNetForTokenClassification:()=>Sa,MPNetModel:()=>Pa,MPNetPreTrainedModel:()=>Un,MT5ForConditionalGeneration:()=>Et,MT5Model:()=>_t,MT5PreTrainedModel:()=>Je,MarianMTModel:()=>Kd,MarianModel:()=>Hd,MarianPreTrainedModel:()=>Uu,MaskFormerForInstanceSegmentation:()=>Gi,MaskFormerModel:()=>Od,MaskFormerPreTrainedModel:()=>$d,MaskedLMOutput:()=>vn,MgpstrForSceneTextRecognition:()=>Wh,MgpstrModelOutput:()=>lm,MgpstrPreTrainedModel:()=>Vh,MistralForCausalLM:()=>As,MistralModel:()=>ms,MistralPreTrainedModel:()=>Eh,MobileBertForMaskedLM:()=>Oi,MobileBertForQuestionAnswering:()=>rs,MobileBertForSequenceClassification:()=>zs,MobileBertModel:()=>Za,MobileBertPreTrainedModel:()=>js,MobileLLMForCausalLM:()=>ti,MobileLLMModel:()=>Sc,MobileLLMPreTrainedModel:()=>Ho,MobileNetV1ForImageClassification:()=>Fh,MobileNetV1Model:()=>Rh,MobileNetV1PreTrainedModel:()=>Zu,MobileNetV2ForImageClassification:()=>Xu,MobileNetV2Model:()=>Nh,MobileNetV2PreTrainedModel:()=>Yu,MobileNetV3ForImageClassification:()=>Ju,MobileNetV3Model:()=>om,MobileNetV3PreTrainedModel:()=>Qu,MobileNetV4ForImageClassification:()=>Bh,MobileNetV4Model:()=>Dh,MobileNetV4PreTrainedModel:()=>el,MobileViTForImageClassification:()=>hd,MobileViTModel:()=>dd,MobileViTPreTrainedModel:()=>Yn,MobileViTV2ForImageClassification:()=>pd,MobileViTV2Model:()=>fd,MobileViTV2PreTrainedModel:()=>pu,ModelOutput:()=>He,ModernBertForMaskedLM:()=>mt,ModernBertForSequenceClassification:()=>ct,ModernBertForTokenClassification:()=>gt,ModernBertModel:()=>ht,ModernBertPreTrainedModel:()=>st,Moondream1ForConditionalGeneration:()=>ec,MoonshineForConditionalGeneration:()=>Ql,MoonshineModel:()=>qn,MoonshinePreTrainedModel:()=>ko,MptForCausalLM:()=>qc,MptModel:()=>Kc,MptPreTrainedModel:()=>au,MultiModalityCausalLM:()=>Uh,MultiModalityPreTrainedModel:()=>zh,MusicgenForCausalLM:()=>im,MusicgenForConditionalGeneration:()=>eo,MusicgenModel:()=>am,MusicgenPreTrainedModel:()=>qu,NomicBertModel:()=>de,NomicBertPreTrainedModel:()=>W,OPTForCausalLM:()=>Yc,OPTModel:()=>Zc,OPTPreTrainedModel:()=>iu,Olmo2ForCausalLM:()=>Ic,Olmo2Model:()=>kc,Olmo2PreTrainedModel:()=>Zo,OlmoForCausalLM:()=>qo,OlmoModel:()=>Ac,OlmoPreTrainedModel:()=>Ko,OpenELMForCausalLM:()=>Dc,OpenELMModel:()=>Nc,OpenELMPreTrainedModel:()=>eu,OwlViTForObjectDetection:()=>_d,OwlViTModel:()=>md,OwlViTPreTrainedModel:()=>mu,Owlv2ForObjectDetection:()=>Hp,Owlv2Model:()=>gd,Owlv2PreTrainedModel:()=>_u,PaliGemmaForConditionalGeneration:()=>sc,PaliGemmaPreTrainedModel:()=>nc,PatchTSMixerForPrediction:()=>Zh,PatchTSMixerModel:()=>qh,PatchTSMixerPreTrainedModel:()=>tl,PatchTSTForPrediction:()=>Kh,PatchTSTModel:()=>Hh,PatchTSTPreTrainedModel:()=>Gh,Phi3ForCausalLM:()=>Wc,Phi3Model:()=>Bi,Phi3PreTrainedModel:()=>nu,Phi3VForCausalLM:()=>Zn,Phi3VPreTrainedModel:()=>ic,PhiForCausalLM:()=>ri,PhiModel:()=>Vc,PhiPreTrainedModel:()=>ru,PreTrainedModel:()=>ae,PretrainedMixin:()=>Fr,PvtForImageClassification:()=>rd,PvtModel:()=>cu,PvtPreTrainedModel:()=>ji,PyAnnoteForAudioFrameClassification:()=>eh,PyAnnoteModel:()=>Jd,PyAnnotePreTrainedModel:()=>qi,QuestionAnsweringModelOutput:()=>Sn,Qwen2ForCausalLM:()=>jc,Qwen2Model:()=>Bc,Qwen2PreTrainedModel:()=>tu,Qwen2VLForConditionalGeneration:()=>Uc,Qwen2VLPreTrainedModel:()=>zc,RTDetrForObjectDetection:()=>da,RTDetrModel:()=>bu,RTDetrObjectDetectionOutput:()=>wn,RTDetrPreTrainedModel:()=>Gs,ResNetForImageClassification:()=>Mu,ResNetModel:()=>Md,ResNetPreTrainedModel:()=>Ui,RoFormerForMaskedLM:()=>Fe,RoFormerForQuestionAnswering:()=>dt,RoFormerForSequenceClassification:()=>Ze,RoFormerForTokenClassification:()=>rt,RoFormerModel:()=>Ee,RoFormerPreTrainedModel:()=>J,RobertaForMaskedLM:()=>ns,RobertaForQuestionAnswering:()=>xt,RobertaForSequenceClassification:()=>Ir,RobertaForTokenClassification:()=>Qr,RobertaModel:()=>Nn,RobertaPreTrainedModel:()=>jt,SamImageSegmentationOutput:()=>Gd,SamModel:()=>Wd,SamPreTrainedModel:()=>Qp,SapiensForDepthEstimation:()=>Ad,SapiensForNormalEstimation:()=>Zp,SapiensForSemanticSegmentation:()=>Sd,SapiensPreTrainedModel:()=>Wi,SegformerForImageClassification:()=>kh,SegformerForSemanticSegmentation:()=>Ih,SegformerModel:()=>Dn,SegformerPreTrainedModel:()=>Hu,Seq2SeqLMOutput:()=>vm,SequenceClassifierOutput:()=>ar,SiglipModel:()=>cc,SiglipPreTrainedModel:()=>Oo,SiglipTextModel:()=>dc,SiglipVisionModel:()=>hc,SpeechT5ForSpeechToText:()=>sm,SpeechT5ForTextToSpeech:()=>bh,SpeechT5HifiGan:()=>yh,SpeechT5Model:()=>nm,SpeechT5PreTrainedModel:()=>Xi,SqueezeBertForMaskedLM:()=>Ya,SqueezeBertForQuestionAnswering:()=>Qa,SqueezeBertForSequenceClassification:()=>Xa,SqueezeBertModel:()=>ka,SqueezeBertPreTrainedModel:()=>Wt,StableLmForCausalLM:()=>oi,StableLmModel:()=>$h,StableLmPreTrainedModel:()=>Ji,Starcoder2ForCausalLM:()=>Th,Starcoder2Model:()=>ha,Starcoder2PreTrainedModel:()=>Hs,StyleTextToSpeech2Model:()=>gh,StyleTextToSpeech2PreTrainedModel:()=>_h,Swin2SRForImageSuperResolution:()=>qp,Swin2SRModel:()=>Pd,Swin2SRPreTrainedModel:()=>Su,SwinForImageClassification:()=>Cu,SwinModel:()=>Vi,SwinPreTrainedModel:()=>Pu,T5ForConditionalGeneration:()=>ee,T5Model:()=>N,T5PreTrainedModel:()=>Ie,TableTransformerForObjectDetection:()=>Td,TableTransformerModel:()=>wu,TableTransformerObjectDetectionOutput:()=>Kp,TableTransformerPreTrainedModel:()=>yu,TokenClassifierOutput:()=>gn,TrOCRForCausalLM:()=>vh,TrOCRPreTrainedModel:()=>wh,UniSpeechForCTC:()=>rh,UniSpeechForSequenceClassification:()=>nh,UniSpeechModel:()=>Vu,UniSpeechPreTrainedModel:()=>Zi,UniSpeechSatForAudioFrameClassification:()=>tm,UniSpeechSatForCTC:()=>sh,UniSpeechSatForSequenceClassification:()=>ah,UniSpeechSatModel:()=>em,UniSpeechSatPreTrainedModel:()=>ai,ViTForImageClassification:()=>Qc,ViTMAEModel:()=>sd,ViTMAEPreTrainedModel:()=>nd,ViTMSNForImageClassification:()=>id,ViTMSNModel:()=>ad,ViTMSNPreTrainedModel:()=>du,ViTModel:()=>Xc,ViTPreTrainedModel:()=>ou,VisionEncoderDecoderModel:()=>Io,VitMatteForImageMatting:()=>cd,VitMattePreTrainedModel:()=>ld,VitPoseForPoseEstimation:()=>td,VitPosePreTrainedModel:()=>lu,VitsModel:()=>Gu,VitsModelOutput:()=>Bf,VitsPreTrainedModel:()=>Ah,Wav2Vec2BertForCTC:()=>oh,Wav2Vec2BertForSequenceClassification:()=>uh,Wav2Vec2BertModel:()=>ih,Wav2Vec2BertPreTrainedModel:()=>Yi,Wav2Vec2ForAudioFrameClassification:()=>Qd,Wav2Vec2ForCTC:()=>Yd,Wav2Vec2ForSequenceClassification:()=>Xd,Wav2Vec2Model:()=>Zd,Wav2Vec2PreTrainedModel:()=>Ss,WavLMForAudioFrameClassification:()=>rm,WavLMForCTC:()=>fh,WavLMForSequenceClassification:()=>ph,WavLMForXVector:()=>mh,WavLMModel:()=>hh,WavLMPreTrainedModel:()=>ii,WeSpeakerResNetModel:()=>Jp,WeSpeakerResNetPreTrainedModel:()=>th,WhisperForConditionalGeneration:()=>Xl,WhisperModel:()=>Yl,WhisperPreTrainedModel:()=>Ao,XLMForQuestionAnswering:()=>ua,XLMForSequenceClassification:()=>_n,XLMForTokenClassification:()=>Ft,XLMModel:()=>sn,XLMPreTrainedModel:()=>sr,XLMRobertaForMaskedLM:()=>Hl,XLMRobertaForQuestionAnswering:()=>ql,XLMRobertaForSequenceClassification:()=>Co,XLMRobertaForTokenClassification:()=>Kl,XLMRobertaModel:()=>Dt,XLMRobertaPreTrainedModel:()=>Qe,XLMWithLMHeadModel:()=>Jr,XVectorOutput:()=>Em,YolosForObjectDetection:()=>Ud,YolosModel:()=>zd,YolosObjectDetectionOutput:()=>Vd,YolosPreTrainedModel:()=>jd});var n=t("./src/configs.js"),a=t("./src/backends/onnx.js"),o=t("./src/utils/dtypes.js"),u=t("./src/utils/generic.js"),d=t("./src/utils/core.js"),c=t("./src/utils/hub.js"),h=t("./src/utils/constants.js"),_=t("./src/generation/logits_process.js"),y=t("./src/generation/configuration_utils.js"),w=t("./src/utils/tensor.js"),M=t("./src/utils/image.js"),S=t("./src/utils/maths.js"),G=t("./src/generation/stopping_criteria.js"),H=t("./src/generation/logits_sampler.js"),B=t("./src/env.js"),z=t("./src/models/whisper/generation_whisper.js"),U=t("./src/models/whisper/common_whisper.js");const F={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5,ImageTextToText:6,Musicgen:7,MultiModality:8,Phi3V:9},I=new Map,k=new Map,$=new Map;async function j(A,O,Z){var Ur;const xe=((Ur=Z.config)==null?void 0:Ur["transformers.js_config"])??{};let Ne=Z.device??xe.device;Ne&&typeof Ne!="string"&&(Ne.hasOwnProperty(O)?Ne=Ne[O]:(console.warn(`device not specified for "${O}". Using the default device.`),Ne=null));const De=Ne??(B.apis.IS_NODE_ENV?"cpu":"wasm"),nt=(0,a.deviceToExecutionProviders)(De);let at=Z.dtype??xe.dtype;if(typeof at!="string"&&(at&&at.hasOwnProperty(O)?at=at[O]:(at=o.DEFAULT_DEVICE_DTYPE_MAPPING[De]??o.DATA_TYPES.fp32,console.warn(`dtype not specified for "${O}". Using the default dtype (${at}) for this device (${De}).`))),at===o.DATA_TYPES.auto){let $r=xe.dtype;typeof $r!="string"&&($r=$r[O]),$r&&$r!==o.DATA_TYPES.auto&&o.DATA_TYPES.hasOwnProperty($r)?at=$r:at=o.DEFAULT_DEVICE_DTYPE_MAPPING[De]??o.DATA_TYPES.fp32}const wt=at;if(o.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(wt)){if(wt===o.DATA_TYPES.fp16&&De==="webgpu"&&!await(0,o.isWebGpuFp16Supported)())throw new Error(`The device (${De}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${wt}. Should be one of: ${Object.keys(o.DATA_TYPES).join(", ")}`);const Mt=xe.kv_cache_dtype?typeof xe.kv_cache_dtype=="string"?xe.kv_cache_dtype:xe.kv_cache_dtype[wt]??"float32":void 0;if(Mt&&!["float32","float16"].includes(Mt))throw new Error(`Invalid kv_cache_dtype: ${Mt}. Should be one of: float32, float16`);const Zt={dtype:wt,kv_cache_dtype:Mt},Xt=o.DEFAULT_DTYPE_SUFFIX_MAPPING[wt],Vt=`${Z.subfolder??""}/${O}${Xt}.onnx`,er={...Z.session_options};er.executionProviders??(er.executionProviders=nt);const hr=xe.free_dimension_overrides;hr?er.freeDimensionOverrides??(er.freeDimensionOverrides=hr):De.startsWith("webnn")&&!er.freeDimensionOverrides&&console.warn('WebNN does not currently support dynamic shapes and requires `free_dimension_overrides` to be set in config.json as a field within "transformers.js_config". When `free_dimension_overrides` is not set, you may experience significant performance degradation.');const _r=(0,c.getModelFile)(A,Vt,!0,Z),ur=Z.use_external_data_format??xe.use_external_data_format;let vr=[];if(ur&&(ur===!0||typeof ur=="object"&&ur.hasOwnProperty(O)&&ur[O]===!0)){if(B.apis.IS_NODE_ENV)throw new Error("External data format is not yet supported in Node.js");const $r=`${O}${Xt}.onnx_data`,Gr=`${Z.subfolder??""}/${$r}`;vr.push(new Promise(async(tn,Mn)=>{const En=await(0,c.getModelFile)(A,Gr,!0,Z);tn({path:$r,data:En})}))}else er.externalData!==void 0&&(vr=er.externalData.map(async $r=>{if(typeof $r.data=="string"){const Gr=await(0,c.getModelFile)(A,$r.data,!0,Z);return{...$r,data:Gr}}return $r}));if(vr.length>0&&(er.externalData=await Promise.all(vr)),De==="webgpu"){const $r=(0,n.getKeyValueShapes)(Z.config,{prefix:"present"});if(Object.keys($r).length>0&&!(0,a.isONNXProxy)()){const Gr={};for(const tn in $r)Gr[tn]="gpu-buffer";er.preferredOutputLocation=Gr}}return{buffer:await _r,session_options:er,session_config:Zt}}async function ce(A,O,Z){return Object.fromEntries(await Promise.all(Object.keys(O).map(async xe=>{const{buffer:Ne,session_options:De,session_config:nt}=await j(A,O[xe],Z),at=await(0,a.createInferenceSession)(Ne,De,nt);return[xe,at]})))}async function ue(A,O,Z){return Object.fromEntries(await Promise.all(Object.keys(O).map(async xe=>{const Ne=await(0,c.getModelJSON)(A,O[xe],!1,Z);return[xe,Ne]})))}function Pe(A,O){const Z=Object.create(null),xe=[];for(const nt of A.inputNames){const at=O[nt];if(!(at instanceof w.Tensor)){xe.push(nt);continue}Z[nt]=(0,a.isONNXProxy)()?at.clone():at}if(xe.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${xe.join(", ")}.`);const Ne=Object.keys(O).length,De=A.inputNames.length;if(Ne>De){let nt=Object.keys(O).filter(at=>!A.inputNames.includes(at));console.warn(`WARNING: Too many inputs were provided (${Ne} > ${De}). The following inputs will be ignored: "${nt.join(", ")}".`)}return Z}async function Te(A,O){const Z=Pe(A,O);try{const xe=Object.fromEntries(Object.entries(Z).map(([De,nt])=>[De,nt.ort_tensor]));let Ne=await A.run(xe);return Ne=ie(Ne),Ne}catch(xe){const Ne=Object.fromEntries(Object.entries(Z).map(([De,{type:nt,dims:at,data:wt}])=>[De,{type:nt,dims:at,data:wt}]));throw console.error(`An error occurred during model execution: "${xe}".`),console.error("Inputs given to model:",Ne),xe}}function ie(A){for(let O in A)(0,a.isONNXTensor)(A[O])?A[O]=new w.Tensor(A[O]):typeof A[O]=="object"&&ie(A[O]);return A}function oe(A){if(A instanceof w.Tensor)return A;if(A.length===0)throw Error("items must be non-empty");if(Array.isArray(A[0])){if(A.some(O=>O.length!==A[0].length))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length.");return new w.Tensor("int64",BigInt64Array.from(A.flat().map(O=>BigInt(O))),[A.length,A[0].length])}else return new w.Tensor("int64",BigInt64Array.from(A.map(O=>BigInt(O))),[1,A.length])}function re(A){return new w.Tensor("bool",[A],[1])}async function ge(A,O){let{encoder_outputs:Z,input_ids:xe,decoder_input_ids:Ne,...De}=O;if(!Z){const at=(0,d.pick)(O,A.sessions.model.inputNames);Z=(await ve(A,at)).last_hidden_state}return De.input_ids=Ne,De.encoder_hidden_states=Z,A.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(De.encoder_attention_mask=O.attention_mask),await me(A,De,!0)}async function ve(A,O){const Z=A.sessions.model,xe=(0,d.pick)(O,Z.inputNames);if(Z.inputNames.includes("inputs_embeds")&&!xe.inputs_embeds){if(!O.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");xe.inputs_embeds=await A.encode_text({input_ids:O.input_ids})}if(Z.inputNames.includes("token_type_ids")&&!xe.token_type_ids){if(!xe.input_ids)throw new Error("Both `input_ids` and `token_type_ids` are missing in the model inputs.");xe.token_type_ids=(0,w.zeros_like)(xe.input_ids)}if(Z.inputNames.includes("pixel_mask")&&!xe.pixel_mask){if(!xe.pixel_values)throw new Error("Both `pixel_values` and `pixel_mask` are missing in the model inputs.");const Ne=xe.pixel_values.dims;xe.pixel_mask=(0,w.ones)([Ne[0],Ne[2],Ne[3]])}return await Te(Z,xe)}async function me(A,O,Z=!1){const xe=A.sessions[Z?"decoder_model_merged":"model"],{past_key_values:Ne,...De}=O;if(xe.inputNames.includes("use_cache_branch")&&(De.use_cache_branch=re(!!Ne)),xe.inputNames.includes("position_ids")&&De.attention_mask&&!De.position_ids){const at=A.config.model_type==="paligemma"?1:0;De.position_ids=X(De,Ne,at)}A.addPastKeyValues(De,Ne);const nt=(0,d.pick)(De,xe.inputNames);return await Te(xe,nt)}function Le({image_token_id:A,inputs_embeds:O,image_features:Z,input_ids:xe,attention_mask:Ne}){const De=xe.tolist().map(Mt=>Mt.reduce((Zt,Xt,Vt)=>(Xt==A&&Zt.push(Vt),Zt),[])),nt=De.reduce((Mt,Zt)=>Mt+Zt.length,0),at=Z.dims[0];if(nt!==at)throw new Error(`Image features and image tokens do not match: tokens: ${nt}, features ${at}`);let wt=0;for(let Mt=0;MtDe.dims[1])){if(Neat==A.config.image_token_index)){const at=A.config.num_image_tokens;if(!at)throw new Error("`num_image_tokens` is missing in the model configuration.");const wt=De.dims[1]-(Ne-at);Z.input_ids=De.slice(null,[-wt,null]),Z.attention_mask=(0,w.ones)([1,Ne+wt])}}}return Z}function ke(A,O,Z,xe){return Z.past_key_values&&(O=O.map(Ne=>[Ne.at(-1)])),{...Z,decoder_input_ids:oe(O)}}function Re(A,...O){return A.config.is_encoder_decoder?ke(A,...O):le(A,...O)}function Xe(A,O,Z,xe){const Ne=!!Z.past_key_values;return xe.guidance_scale!==null&&xe.guidance_scale>1&&(Ne?Z.input_ids=(0,w.cat)([Z.input_ids,Z.input_ids],0):(Z.input_ids=(0,w.cat)([Z.input_ids,(0,w.full_like)(Z.input_ids,BigInt(xe.pad_token_id))],0),Z.attention_mask=(0,w.cat)([Z.attention_mask,(0,w.full_like)(Z.attention_mask,0n)],0))),(Ne||!Z.pixel_values)&&(Z.pixel_values=(0,w.full)([0,0,3,384,384],1)),Ne&&(Z.images_seq_mask=new w.Tensor("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),Z.images_emb_mask=new w.Tensor("bool",new Array(0).fill(!1),[1,1,0])),Z}class ae extends u.Callable{constructor(Z,xe,Ne){super();we(this,"main_input_name","input_ids");we(this,"forward_params",["input_ids","attention_mask"]);this.config=Z,this.sessions=xe,this.configs=Ne;const De=$.get(this.constructor),nt=I.get(De);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,nt){case F.DecoderOnly:this.can_generate=!0,this._forward=me,this._prepare_inputs_for_generation=le;break;case F.Seq2Seq:case F.Vision2Seq:case F.Musicgen:this.can_generate=!0,this._forward=ge,this._prepare_inputs_for_generation=ke;break;case F.EncoderDecoder:this._forward=ge;break;case F.ImageTextToText:this.can_generate=!0,this._forward=$e,this._prepare_inputs_for_generation=Re;break;case F.Phi3V:this.can_generate=!0,this._prepare_inputs_for_generation=Re;break;case F.MultiModality:this.can_generate=!0,this._prepare_inputs_for_generation=Xe;break;default:this._forward=ve;break}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){var xe;const Z=[];for(const Ne of Object.values(this.sessions))(xe=Ne==null?void 0:Ne.handler)!=null&&xe.dispose&&Z.push(Ne.handler.dispose());return await Promise.all(Z)}static async from_pretrained(Z,{progress_callback:xe=null,config:Ne=null,cache_dir:De=null,local_files_only:nt=!1,revision:at="main",model_file_name:wt=null,subfolder:Mt="onnx",device:Zt=null,dtype:Xt=null,use_external_data_format:Vt=null,session_options:er={}}={}){let hr={progress_callback:xe,config:Ne,cache_dir:De,local_files_only:nt,revision:at,model_file_name:wt,subfolder:Mt,device:Zt,dtype:Xt,use_external_data_format:Vt,session_options:er};const _r=$.get(this),ur=I.get(_r);Ne=hr.config=await n.AutoConfig.from_pretrained(Z,hr);let vr;if(ur===F.DecoderOnly)vr=await Promise.all([ce(Z,{model:hr.model_file_name??"model"},hr),ue(Z,{generation_config:"generation_config.json"},hr)]);else if(ur===F.Seq2Seq||ur===F.Vision2Seq)vr=await Promise.all([ce(Z,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},hr),ue(Z,{generation_config:"generation_config.json"},hr)]);else if(ur===F.MaskGeneration)vr=await Promise.all([ce(Z,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},hr)]);else if(ur===F.EncoderDecoder)vr=await Promise.all([ce(Z,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},hr)]);else if(ur===F.ImageTextToText){const Kr={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};Ne.is_encoder_decoder&&(Kr.model="encoder_model"),vr=await Promise.all([ce(Z,Kr,hr),ue(Z,{generation_config:"generation_config.json"},hr)])}else if(ur===F.Musicgen)vr=await Promise.all([ce(Z,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},hr),ue(Z,{generation_config:"generation_config.json"},hr)]);else if(ur===F.MultiModality)vr=await Promise.all([ce(Z,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"language_model",lm_head:"lm_head",gen_head:"gen_head",gen_img_embeds:"gen_img_embeds",image_decode:"image_decode"},hr),ue(Z,{generation_config:"generation_config.json"},hr)]);else if(ur===F.Phi3V)vr=await Promise.all([ce(Z,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"},hr),ue(Z,{generation_config:"generation_config.json"},hr)]);else{if(ur!==F.EncoderOnly){const Kr=_r??(Ne==null?void 0:Ne.model_type);Kr!=="custom"&&console.warn(`Model type for '${Kr}' not found, assuming encoder-only architecture. Please report this at ${h.GITHUB_ISSUE_URL}.`)}vr=await Promise.all([ce(Z,{model:hr.model_file_name??"model"},hr)])}return new this(Ne,...vr)}async _call(Z){return await this.forward(Z)}async forward(Z){return await this._forward(this,Z)}get generation_config(){var Z;return((Z=this.configs)==null?void 0:Z.generation_config)??null}_get_logits_warper(Z){const xe=new _.LogitsProcessorList;return Z.temperature!==null&&Z.temperature!==1&&xe.push(new _.TemperatureLogitsWarper(Z.temperature)),Z.top_k!==null&&Z.top_k!==0&&xe.push(new _.TopKLogitsWarper(Z.top_k)),Z.top_p!==null&&Z.top_p<1&&xe.push(new _.TopPLogitsWarper(Z.top_p)),xe}_get_logits_processor(Z,xe,Ne=null){const De=new _.LogitsProcessorList;if(Z.repetition_penalty!==null&&Z.repetition_penalty!==1&&De.push(new _.RepetitionPenaltyLogitsProcessor(Z.repetition_penalty)),Z.no_repeat_ngram_size!==null&&Z.no_repeat_ngram_size>0&&De.push(new _.NoRepeatNGramLogitsProcessor(Z.no_repeat_ngram_size)),Z.bad_words_ids!==null&&De.push(new _.NoBadWordsLogitsProcessor(Z.bad_words_ids,Z.eos_token_id)),Z.min_length!==null&&Z.eos_token_id!==null&&Z.min_length>0&&De.push(new _.MinLengthLogitsProcessor(Z.min_length,Z.eos_token_id)),Z.min_new_tokens!==null&&Z.eos_token_id!==null&&Z.min_new_tokens>0&&De.push(new _.MinNewTokensLengthLogitsProcessor(xe,Z.min_new_tokens,Z.eos_token_id)),Z.forced_bos_token_id!==null&&De.push(new _.ForcedBOSTokenLogitsProcessor(Z.forced_bos_token_id)),Z.forced_eos_token_id!==null&&De.push(new _.ForcedEOSTokenLogitsProcessor(Z.max_length,Z.forced_eos_token_id)),Z.begin_suppress_tokens!==null){const nt=xe>1||Z.forced_bos_token_id===null?xe:xe+1;De.push(new _.SuppressTokensAtBeginLogitsProcessor(Z.begin_suppress_tokens,nt))}return Z.guidance_scale!==null&&Z.guidance_scale>1&&De.push(new _.ClassifierFreeGuidanceLogitsProcessor(Z.guidance_scale)),Ne!==null&&De.extend(Ne),De}_prepare_generation_config(Z,xe,Ne=y.GenerationConfig){const De={...this.config};for(const at of["decoder","generator","text_config"])at in De&&Object.assign(De,De[at]);const nt=new Ne(De);return Object.assign(nt,this.generation_config??{}),Z&&Object.assign(nt,Z),xe&&Object.assign(nt,(0,d.pick)(xe,Object.getOwnPropertyNames(nt))),nt}_get_stopping_criteria(Z,xe=null){const Ne=new G.StoppingCriteriaList;return Z.max_length!==null&&Ne.push(new G.MaxLengthCriteria(Z.max_length,this.config.max_position_embeddings??null)),Z.eos_token_id!==null&&Ne.push(new G.EosTokenCriteria(Z.eos_token_id)),xe&&Ne.extend(xe),Ne}_validate_model_class(){if(!this.can_generate){const Z=[ef,ro,nl,rl],xe=$.get(this.constructor),Ne=new Set,De=this.config.model_type;for(const at of Z){const wt=at.get(De);wt&&Ne.add(wt[0])}let nt=`The current model class (${xe}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw Ne.size>0&&(nt+=` Please use the following class instead: ${[...Ne].join(", ")}`),Error(nt)}}prepare_inputs_for_generation(...Z){return this._prepare_inputs_for_generation(this,...Z)}_update_model_kwargs_for_generation({generated_input_ids:Z,outputs:xe,model_inputs:Ne,is_encoder_decoder:De}){return Ne.past_key_values=this.getPastKeyValues(xe,Ne.past_key_values),Ne.input_ids=new w.Tensor("int64",Z.flat(),[Z.length,1]),De||(Ne.attention_mask=(0,w.cat)([Ne.attention_mask,(0,w.ones)([Ne.attention_mask.dims[0],1])],1)),Ne.position_ids=null,Ne}_prepare_model_inputs({inputs:Z,bos_token_id:xe,model_kwargs:Ne}){const De=(0,d.pick)(Ne,this.forward_params),nt=this.main_input_name;if(nt in De){if(Z)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else De[nt]=Z;return{inputs_tensor:De[nt],model_inputs:De,model_input_name:nt}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:Z,model_inputs:xe,model_input_name:Ne,generation_config:De}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!xe.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:at,pixel_values:wt,attention_mask:Mt,...Zt}=xe,Xt=await this._prepare_inputs_embeds(xe);xe={...Zt,...(0,d.pick)(Xt,["inputs_embeds","attention_mask"])}}let{last_hidden_state:nt}=await ve(this,xe);if(De.guidance_scale!==null&&De.guidance_scale>1)nt=(0,w.cat)([nt,(0,w.full_like)(nt,0)],0),"attention_mask"in xe&&(xe.attention_mask=(0,w.cat)([xe.attention_mask,(0,w.zeros_like)(xe.attention_mask)],0));else if(xe.decoder_input_ids){const at=oe(xe.decoder_input_ids).dims[0];if(at!==nt.dims[0]){if(nt.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${nt.dims[0]}) than the decoder inputs (${at}).`);nt=(0,w.cat)(Array.from({length:at},()=>nt),0)}}return xe.encoder_outputs=nt,xe}_prepare_decoder_input_ids_for_generation({batch_size:Z,model_input_name:xe,model_kwargs:Ne,decoder_start_token_id:De,bos_token_id:nt,generation_config:at}){let{decoder_input_ids:wt,...Mt}=Ne;if(!(wt instanceof w.Tensor)){if(wt)Array.isArray(wt[0])||(wt=Array.from({length:Z},()=>wt));else if(De??(De=nt),this.config.model_type==="musicgen")wt=Array.from({length:Z*this.config.decoder.num_codebooks},()=>[De]);else if(Array.isArray(De)){if(De.length!==Z)throw new Error(`\`decoder_start_token_id\` expcted to have length ${Z} but got ${De.length}`);wt=De}else wt=Array.from({length:Z},()=>[De]);wt=oe(wt)}return Ne.decoder_attention_mask=(0,w.ones_like)(wt),{input_ids:wt,model_inputs:Mt}}async generate({inputs:Z=null,generation_config:xe=null,logits_processor:Ne=null,stopping_criteria:De=null,streamer:nt=null,...at}){this._validate_model_class(),xe=this._prepare_generation_config(xe,at);let{inputs_tensor:wt,model_inputs:Mt,model_input_name:Zt}=this._prepare_model_inputs({inputs:Z,model_kwargs:at});const Xt=this.config.is_encoder_decoder;Xt&&("encoder_outputs"in Mt||(Mt=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:wt,model_inputs:Mt,model_input_name:Zt,generation_config:xe})));let Vt;Xt?{input_ids:Vt,model_inputs:Mt}=this._prepare_decoder_input_ids_for_generation({batch_size:Mt[Zt].dims.at(0),model_input_name:Zt,model_kwargs:Mt,decoder_start_token_id:xe.decoder_start_token_id,bos_token_id:xe.bos_token_id,generation_config:xe}):Vt=Mt[Zt];let er=Vt.dims.at(-1);xe.max_new_tokens!==null&&(xe.max_length=er+xe.max_new_tokens);const hr=this._get_logits_processor(xe,er,Ne),_r=this._get_stopping_criteria(xe,De),ur=Mt[Zt].dims.at(0),vr=H.LogitsSampler.getSampler(xe),Kr=new Array(ur).fill(0),Ur=Vt.tolist();nt&&nt.put(Ur);let $r,Gr={};for(;;){if(Mt=this.prepare_inputs_for_generation(Ur,Mt,xe),$r=await this.forward(Mt),xe.output_attentions&&xe.return_dict_in_generate){const Vn=this.getAttentions($r);for(const _s in Vn)_s in Gr||(Gr[_s]=[]),Gr[_s].push(Vn[_s])}const En=$r.logits.slice(null,-1,null),os=hr(Ur,En),La=[];for(let Vn=0;VnVn))break;Mt=this._update_model_kwargs_for_generation({generated_input_ids:La,outputs:$r,model_inputs:Mt,is_encoder_decoder:Xt})}nt&&nt.end();const tn=this.getPastKeyValues($r,Mt.past_key_values,!0),Mn=new w.Tensor("int64",Ur.flat(),[Ur.length,Ur[0].length]);if(xe.return_dict_in_generate)return{sequences:Mn,past_key_values:tn,...Gr};for(const En of Object.values($r))En.location==="gpu-buffer"&&En.dispose();return Mn}getPastKeyValues(Z,xe,Ne=!1){const De=Object.create(null);for(const nt in Z)if(nt.startsWith("present")){const at=nt.replace("present","past_key_values"),wt=nt.includes("encoder");if(wt&&xe?De[at]=xe[at]:De[at]=Z[nt],xe&&(!wt||Ne)){const Mt=xe[at];Mt.location==="gpu-buffer"&&Mt.dispose()}}return De}getAttentions(Z){const xe={};for(const Ne of["cross_attentions","encoder_attentions","decoder_attentions"])for(const De in Z)De.startsWith(Ne)&&(Ne in xe||(xe[Ne]=[]),xe[Ne].push(Z[De]));return xe}addPastKeyValues(Z,xe){var Ne,De,nt;if(xe)Object.assign(Z,xe);else{const at=this.sessions.decoder_model_merged??this.sessions.model,wt=((Ne=at==null?void 0:at.config)==null?void 0:Ne.kv_cache_dtype)??"float32",Mt=wt==="float16"?new Uint16Array:[],Zt=((nt=(De=Z[this.main_input_name]??Z.attention_mask)==null?void 0:De.dims)==null?void 0:nt[0])??1,Xt=(0,n.getKeyValueShapes)(this.config,{batch_size:Zt});for(const Vt in Xt)Z[Vt]=new w.Tensor(wt,Mt,Xt[Vt])}}async encode_image({pixel_values:Z}){const xe=(await Te(this.sessions.vision_encoder,{pixel_values:Z})).image_features;return this.config.num_image_tokens||(console.warn(`The number of image tokens was not set in the model configuration. Setting it to the number of features detected by the vision encoder (${xe.dims[1]}).`),this.config.num_image_tokens=xe.dims[1]),xe}async encode_text({input_ids:Z}){return(await Te(this.sessions.embed_tokens,{input_ids:Z})).inputs_embeds}}class He{}class Ve extends He{constructor({last_hidden_state:O,hidden_states:Z=null,attentions:xe=null}){super(),this.last_hidden_state=O,this.hidden_states=Z,this.attentions=xe}}class he extends ae{}class Se extends he{}class Ke extends he{async _call(O){return new vn(await super._call(O))}}class qe extends he{async _call(O){return new ar(await super._call(O))}}class Ge extends he{async _call(O){return new gn(await super._call(O))}}class We extends he{async _call(O){return new Sn(await super._call(O))}}class st extends ae{}class ht extends st{}class mt extends st{async _call(O){return new vn(await super._call(O))}}class ct extends st{async _call(O){return new ar(await super._call(O))}}class gt extends st{async _call(O){return new gn(await super._call(O))}}class W extends ae{}class de extends W{}class J extends ae{}class Ee extends J{}class Fe extends J{async _call(O){return new vn(await super._call(O))}}class Ze extends J{async _call(O){return new ar(await super._call(O))}}class rt extends J{async _call(O){return new gn(await super._call(O))}}class dt extends J{async _call(O){return new Sn(await super._call(O))}}class bt extends ae{}class Ct extends bt{}class Lt extends bt{async _call(O){return new vn(await super._call(O))}}class Nt extends bt{async _call(O){return new ar(await super._call(O))}}class br extends bt{async _call(O){return new gn(await super._call(O))}}class Rr extends bt{async _call(O){return new Sn(await super._call(O))}}class Yr extends ae{}class nn extends Yr{}class $n extends Yr{async _call(O){return new vn(await super._call(O))}}class Es extends Yr{async _call(O){return new ar(await super._call(O))}}class na extends Yr{async _call(O){return new gn(await super._call(O))}}class fn extends Yr{async _call(O){return new Sn(await super._call(O))}}class fs extends ae{}class qt extends fs{}class sa extends fs{async _call(O){return new vn(await super._call(O))}}class Ts extends fs{async _call(O){return new ar(await super._call(O))}}class xs extends fs{async _call(O){return new gn(await super._call(O))}}class aa extends fs{async _call(O){return new Sn(await super._call(O))}}class Kn extends ae{}class ia extends Kn{}class Ms extends Kn{async _call(O){return new vn(await super._call(O))}}class Fs extends Kn{async _call(O){return new ar(await super._call(O))}}class Ns extends Kn{async _call(O){return new gn(await super._call(O))}}class jn extends Kn{async _call(O){return new Sn(await super._call(O))}}class ot extends ae{}class At extends ot{}class Ut extends ot{async _call(O){return new vn(await super._call(O))}}class pn extends ot{async _call(O){return new ar(await super._call(O))}}class Ds extends ot{async _call(O){return new gn(await super._call(O))}}class Ps extends ot{async _call(O){return new Sn(await super._call(O))}}class Dr extends ae{}class zn extends Dr{}class en extends Dr{async _call(O){return new ar(await super._call(O))}}class ps extends Dr{async _call(O){return new gn(await super._call(O))}}class fr extends Dr{async _call(O){return new Sn(await super._call(O))}}class Ma extends Dr{async _call(O){return new vn(await super._call(O))}}class Bs extends ae{}class $i extends Bs{}class Ha extends Bs{async _call(O){return new vn(await super._call(O))}}class Ka extends Bs{async _call(O){return new ar(await super._call(O))}}class qa extends Bs{async _call(O){return new gn(await super._call(O))}}class js extends ae{}class Za extends js{}class Oi extends js{async _call(O){return new vn(await super._call(O))}}class zs extends js{async _call(O){return new ar(await super._call(O))}}class rs extends js{async _call(O){return new Sn(await super._call(O))}}class Un extends ae{}class Pa extends Un{}class oa extends Un{async _call(O){return new vn(await super._call(O))}}class Ca extends Un{async _call(O){return new ar(await super._call(O))}}class Sa extends Un{async _call(O){return new gn(await super._call(O))}}class Aa extends Un{async _call(O){return new Sn(await super._call(O))}}class Wt extends ae{}class ka extends Wt{}class Ya extends Wt{async _call(O){return new vn(await super._call(O))}}class Xa extends Wt{async _call(O){return new ar(await super._call(O))}}class Qa extends Wt{async _call(O){return new Sn(await super._call(O))}}class Us extends ae{}class Ja extends Us{}class Ia extends Us{async _call(O){return new ar(await super._call(O))}}class ei extends Us{async _call(O){return new Sn(await super._call(O))}}class Tr extends Us{async _call(O){return new vn(await super._call(O))}}class Ie extends ae{constructor(){super(...arguments);we(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class N extends Ie{}class ee extends Ie{}class fe extends ae{}class Ae extends fe{}class Oe extends fe{}class Je extends ae{}class _t extends Je{}class Et extends Je{}class yt extends ae{}class St extends yt{}class tr extends yt{}class kr extends yt{async _call(O){return new ar(await super._call(O))}}class Pr extends ae{}class rn extends Pr{}class Gt extends Pr{}class mr extends Pr{async _call(O){return new ar(await super._call(O))}}class On extends Pr{}class mn extends ae{}class ze extends mn{}class xn extends mn{}class Cs extends ae{}class Xr extends Cs{}class yn extends Cs{}class jt extends ae{}class Nn extends jt{}class ns extends jt{async _call(O){return new vn(await super._call(O))}}class Ir extends jt{async _call(O){return new ar(await super._call(O))}}class Qr extends jt{async _call(O){return new gn(await super._call(O))}}class xt extends jt{async _call(O){return new Sn(await super._call(O))}}class sr extends ae{}class sn extends sr{}class Jr extends sr{async _call(O){return new vn(await super._call(O))}}class _n extends sr{async _call(O){return new ar(await super._call(O))}}class Ft extends sr{async _call(O){return new gn(await super._call(O))}}class ua extends sr{async _call(O){return new Sn(await super._call(O))}}class Qe extends ae{}class Dt extends Qe{}class Hl extends Qe{async _call(O){return new vn(await super._call(O))}}class Co extends Qe{async _call(O){return new ar(await super._call(O))}}class Kl extends Qe{async _call(O){return new gn(await super._call(O))}}class ql extends Qe{async _call(O){return new Sn(await super._call(O))}}class or extends ae{}class Zl extends or{}class So extends or{}class Ao extends ae{constructor(){super(...arguments);we(this,"requires_attention_mask",!1);we(this,"main_input_name","input_features");we(this,"forward_params",["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class Yl extends Ao{}class Xl extends Ao{_prepare_generation_config(O,Z){return super._prepare_generation_config(O,Z,z.WhisperGenerationConfig)}_retrieve_init_tokens(O){const Z=[O.decoder_start_token_id];let xe=O.language;const Ne=O.task;if(O.is_multilingual){xe||(console.warn("No language specified - defaulting to English (en)."),xe="en");const nt=`<|${(0,U.whisper_language_to_code)(xe)}|>`;Z.push(O.lang_to_id[nt]),Z.push(O.task_to_id[Ne??"transcribe"])}else if(xe||Ne)throw new Error("Cannot specify `task` or `language` for an English-only model. If the model is intended to be multilingual, pass `is_multilingual=true` to generate, or update the generation config.");return!O.return_timestamps&&O.no_timestamps_token_id&&Z.at(-1)!==O.no_timestamps_token_id?Z.push(O.no_timestamps_token_id):O.return_timestamps&&Z.at(-1)===O.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),Z.pop()),Z.filter(De=>De!=null)}async generate({inputs:O=null,generation_config:Z=null,logits_processor:xe=null,stopping_criteria:Ne=null,...De}){Z=this._prepare_generation_config(Z,De);const nt=De.decoder_input_ids??this._retrieve_init_tokens(Z);if(Z.return_timestamps&&(xe??(xe=new _.LogitsProcessorList),xe.push(new _.WhisperTimeStampLogitsProcessor(Z,nt))),Z.begin_suppress_tokens&&(xe??(xe=new _.LogitsProcessorList),xe.push(new _.SuppressTokensAtBeginLogitsProcessor(Z.begin_suppress_tokens,nt.length))),Z.return_token_timestamps){if(!Z.alignment_heads)throw new Error("Model generation config has no `alignment_heads`, token-level timestamps not available. See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config.");Z.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),Z.output_attentions=!0,Z.return_dict_in_generate=!0}const at=await super.generate({inputs:O,generation_config:Z,logits_processor:xe,decoder_input_ids:nt,...De});return Z.return_token_timestamps&&(at.token_timestamps=this._extract_token_timestamps(at,Z.alignment_heads,Z.num_frames)),at}_extract_token_timestamps(O,Z,xe=null,Ne=.02){if(!O.cross_attentions)throw new Error("Model outputs must contain cross attentions to extract timestamps. This is most likely because the model was not exported with `output_attentions=True`.");xe==null&&console.warn("`num_frames` has not been set, meaning the entire audio will be analyzed. This may lead to inaccurate token-level timestamps for short audios (< 30 seconds).");let De=this.config.median_filter_width;De===void 0&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),De=7);const nt=O.cross_attentions,at=Array.from({length:this.config.decoder_layers},(_r,ur)=>(0,w.cat)(nt.map(vr=>vr[ur]),2)),wt=(0,w.stack)(Z.map(([_r,ur])=>{if(_r>=at.length)throw new Error(`Layer index ${_r} is out of bounds for cross attentions (length ${at.length}).`);return xe?at[_r].slice(null,ur,null,[0,xe]):at[_r].slice(null,ur)})).transpose(1,0,2,3),[Mt,Zt]=(0,w.std_mean)(wt,-2,0,!0),Xt=wt.clone();for(let _r=0;_rvr[Mn+1]-vr[Mn]),$r=(0,d.mergeArrays)([1],Ur).map(tn=>!!tn),Gr=[];for(let tn=0;tn<$r.length;++tn)$r[tn]&&Gr.push(Kr[tn]*Ne);hr[_r].data.set(Gr,1)}return hr}}class ko extends ae{constructor(){super(...arguments);we(this,"requires_attention_mask",!1);we(this,"main_input_name","input_values");we(this,"forward_params",["input_values","decoder_input_ids","past_key_values"])}}class qn extends ko{}class Ql extends ko{}class Io extends ae{constructor(){super(...arguments);we(this,"main_input_name","pixel_values");we(this,"forward_params",["pixel_values","decoder_input_ids","encoder_hidden_states","past_key_values"])}}class Vs extends ae{constructor(){super(...arguments);we(this,"forward_params",["input_ids","attention_mask","pixel_values","position_ids","past_key_values"])}}class Li extends Vs{_merge_input_ids_with_image_features({inputs_embeds:O,image_features:Z,input_ids:xe,attention_mask:Ne}){const De=this.config.image_token_index,at=xe.tolist().map(Vt=>Vt.findIndex(er=>er==De)),wt=at.every(Vt=>Vt===-1),Mt=at.every(Vt=>Vt!==-1);if(!wt&&!Mt)throw new Error("Every input should contain either 0 or 1 image token.");if(wt)return{inputs_embeds:O,attention_mask:Ne};const Zt=[],Xt=[];for(let Vt=0;VtArray.from({length:O.dims[0]},Ur=>Array.from({length:O.dims[1]},$r=>1))),hr=Z?Z.tolist():[],_r=xe?xe.tolist():[];let ur=0,vr=0;for(let Kr=0;KrVt[Kr][an]==1),Gr=Ur.reduce((Vr,an,ks)=>(an==wt&&Vr.push(ks),Vr),[]).map(Vr=>Ur[Vr+1]),tn=Gr.filter(Vr=>Vr==nt).length,Mn=Gr.filter(Vr=>Vr==at).length;let En=[],os=0,La=tn,hl=Mn;for(let Vr=0;VrWn>os&&ma==nt),ks=Ur.findIndex((ma,Wn)=>Wn>os&&ma==at),fa=La>0&&an!==-1?an:Ur.length+1,Ra=hl>0&&ks!==-1?ks:Ur.length+1;let fl,ao,pl,ml;fa0?(0,S.max)(En.at(-1))[0]+1:0;En.push(Array.from({length:3*gl},(ma,Wn)=>zf+Wn%gl));const Uf=gl+zf,io=G_*_l*Fa,Vf=Array.from({length:io},(ma,Wn)=>Uf+Math.floor(Wn/(_l*Fa))),Wf=Array.from({length:io},(ma,Wn)=>Uf+Math.floor(Wn/Fa)%_l),pa=Array.from({length:io},(ma,Wn)=>Uf+Wn%Fa);En.push([Vf,Wf,pa].flat()),os=fl+io}if(os0?(0,S.max)(En.at(-1))[0]+1:0,an=Ur.length-os;En.push(Array.from({length:3*an},(ks,fa)=>Vr+fa%an))}const Vn=En.reduce((Vr,an)=>Vr+an.length,0),_s=new Array(Vn);let jf=0;for(let Vr=0;Vr<3;++Vr)for(let an=0;anXt[ur%Xt.length]),hr=Array.from({length:Vt[0]},(_r,ur)=>(0,S.max)(Xt.subarray(Vt[1]*ur,Vt[1]*(ur+1)))[0]+1n+BigInt(Vt[1]));return[new w.Tensor("int64",er,[3,...Vt]),new w.Tensor("int64",hr,[hr.length,1])]}else{const[Xt,Vt]=O.dims,er=BigInt64Array.from({length:3*Xt*Vt},(hr,_r)=>BigInt(Math.floor(_r%Vt/Xt)));return[new w.Tensor("int64",er,[3,...O.dims]),(0,w.zeros)([Xt,1])]}}async encode_image({pixel_values:O,image_grid_thw:Z}){return(await Te(this.sessions.vision_encoder,{pixel_values:O,grid_thw:Z})).image_features}_merge_input_ids_with_image_features(O){return Le({image_token_id:this.config.image_token_id,...O})}prepare_inputs_for_generation(O,Z,xe){if(Z.attention_mask&&!Z.position_ids)if(!Z.past_key_values)[Z.position_ids,Z.rope_deltas]=this.get_rope_index(Z.input_ids,Z.image_grid_thw,Z.video_grid_thw,Z.attention_mask);else{Z.pixel_values=null;const Ne=BigInt(Object.values(Z.past_key_values)[0].dims.at(-2)),De=Z.rope_deltas.map(nt=>Ne+nt);Z.position_ids=(0,w.stack)([De,De,De],0)}return Z}}class ru extends ae{}class Vc extends ru{}class ri extends ru{}class nu extends ae{}class Bi extends nu{}class Wc extends nu{}class su extends ae{}class Gc extends su{}class Hc extends su{}class au extends ae{}class Kc extends au{}class qc extends au{}class iu extends ae{}class Zc extends iu{}class Yc extends iu{}class ou extends ae{}class Xc extends ou{}class Qc extends ou{async _call(O){return new ar(await super._call(O))}}class uu extends ae{}class Jc extends uu{}class ed extends uu{async _call(O){return new ar(await super._call(O))}}class lu extends ae{}class td extends lu{}class ji extends ae{}class cu extends ji{}class rd extends ji{async _call(O){return new ar(await super._call(O))}}class nd extends ae{}class sd extends nd{}class du extends ae{}class ad extends du{}class id extends du{async _call(O){return new ar(await super._call(O))}}class hu extends ae{}class od extends hu{}class fu extends ae{}class ud extends fu{}class Gp extends fu{async _call(O){return new ar(await super._call(O))}}class ld extends ae{}class cd extends ld{async _call(O){return new ui(await super._call(O))}}class Yn extends ae{}class dd extends Yn{}class hd extends Yn{async _call(O){return new ar(await super._call(O))}}class pu extends ae{}class fd extends pu{}class pd extends pu{async _call(O){return new ar(await super._call(O))}}class mu extends ae{}class md extends mu{}class _d extends mu{}class _u extends ae{}class gd extends _u{}class Hp extends _u{}class gu extends ae{}class bd extends gu{}class yd extends gu{async _call(O){return new ar(await super._call(O))}}class zi extends ae{}class wd extends zi{}class vd extends zi{async _call(O){return new Ws(await super._call(O))}}class Ed extends zi{async _call(O){return new ca(await super._call(O))}}class Ws extends He{constructor({logits:O,pred_boxes:Z}){super(),this.logits=O,this.pred_boxes=Z}}class ca extends He{constructor({logits:O,pred_boxes:Z,pred_masks:xe}){super(),this.logits=O,this.pred_boxes=Z,this.pred_masks=xe}}class Gs extends ae{}class bu extends Gs{}class da extends Gs{async _call(O){return new wn(await super._call(O))}}class wn extends He{constructor({logits:O,pred_boxes:Z}){super(),this.logits=O,this.pred_boxes=Z}}class yu extends ae{}class wu extends yu{}class Td extends yu{async _call(O){return new Kp(await super._call(O))}}class Kp extends Ws{}class $a extends ae{}class vu extends $a{}class Eu extends $a{async _call(O){return new ar(await super._call(O))}}class Tu extends ae{}class xd extends Tu{}class xu extends Tu{async _call(O){return new ar(await super._call(O))}}class Ui extends ae{}class Md extends Ui{}class Mu extends Ui{async _call(O){return new ar(await super._call(O))}}class Pu extends ae{}class Vi extends Pu{}class Cu extends Pu{async _call(O){return new ar(await super._call(O))}}class Su extends ae{}class Pd extends Su{}class qp extends Su{}class Au extends ae{}class ku extends Au{}class ni extends Au{}class Cd extends ae{}class Iu extends Cd{}class Wi extends ae{}class Sd extends Wi{}class Ad extends Wi{}class Zp extends Wi{}class kd extends ae{}class Id extends kd{}class $d extends ae{}class Od extends $d{}class Gi extends $d{}class $u extends ae{}class Hi extends $u{}class Ou extends $u{}class Lu extends ae{}class Ld extends Lu{}class Ru extends ae{}class Fu extends Ru{}class Yp extends Ru{async _call(O){return new ar(await super._call(O))}}class Nu extends ae{}class Xp extends Nu{}class Rd extends Nu{async _call(O){return new ar(await super._call(O))}}class Du extends ae{}class Fd extends Du{}class Bu extends Du{async _call(O){return new ar(await super._call(O))}}class ju extends ae{}class Nd extends ju{}class zu extends ju{async _call(O){return new ar(await super._call(O))}}class Dd extends ae{}class Bd extends Dd{}class jd extends ae{}class zd extends jd{}class Ud extends jd{async _call(O){return new Vd(await super._call(O))}}class Vd extends He{constructor({logits:O,pred_boxes:Z}){super(),this.logits=O,this.pred_boxes=Z}}class Qp extends ae{}class Wd extends Qp{async get_image_embeddings({pixel_values:O}){return await ve(this,{pixel_values:O})}async forward(O){if((!O.image_embeddings||!O.image_positional_embeddings)&&(O={...O,...await this.get_image_embeddings(O)}),!O.input_labels&&O.input_points){const xe=O.input_points.dims.slice(0,-1),Ne=xe.reduce((De,nt)=>De*nt,1);O.input_labels=new w.Tensor("int64",new BigInt64Array(Ne).fill(1n),xe)}const Z={image_embeddings:O.image_embeddings,image_positional_embeddings:O.image_positional_embeddings};return O.input_points&&(Z.input_points=O.input_points),O.input_labels&&(Z.input_labels=O.input_labels),O.input_boxes&&(Z.input_boxes=O.input_boxes),await Te(this.sessions.prompt_encoder_mask_decoder,Z)}async _call(O){return new Gd(await super._call(O))}}class Gd extends He{constructor({iou_scores:O,pred_masks:Z}){super(),this.iou_scores=O,this.pred_masks=Z}}class Uu extends ae{}class Hd extends Uu{}class Kd extends Uu{}class qd extends ae{}class Ki extends qd{}class si extends qd{}class Ss extends ae{}class Zd extends Ss{}class Yd extends Ss{async _call(O){return new Oa(await super._call(O))}}class Xd extends Ss{async _call(O){return new ar(await super._call(O))}}class Qd extends Ss{async _call(O){return new gn(await super._call(O))}}class qi extends ae{}class Jd extends qi{}class eh extends qi{async _call(O){return new gn(await super._call(O))}}class th extends ae{}class Jp extends th{}class Zi extends ae{}class Vu extends Zi{}class rh extends Zi{async _call(O){return new Oa(await super._call(O))}}class nh extends Zi{async _call(O){return new ar(await super._call(O))}}class ai extends ae{}class em extends ai{}class sh extends ai{async _call(O){return new Oa(await super._call(O))}}class ah extends ai{async _call(O){return new ar(await super._call(O))}}class tm extends ai{async _call(O){return new gn(await super._call(O))}}class Yi extends ae{}class ih extends Yi{}class oh extends Yi{async _call(O){return new Oa(await super._call(O))}}class uh extends Yi{async _call(O){return new ar(await super._call(O))}}class W_ extends ae{}class lh extends Ss{}class ch extends Ss{async _call(O){return new Oa(await super._call(O))}}class dh extends Ss{async _call(O){return new ar(await super._call(O))}}class ii extends ae{}class hh extends ii{}class fh extends ii{async _call(O){return new Oa(await super._call(O))}}class ph extends ii{async _call(O){return new ar(await super._call(O))}}class mh extends ii{async _call(O){return new Em(await super._call(O))}}class rm extends ii{async _call(O){return new gn(await super._call(O))}}class _h extends ae{}class gh extends _h{}class Xi extends ae{}class nm extends Xi{}class sm extends Xi{}class bh extends Xi{async generate_speech(O,Z,{threshold:xe=.5,minlenratio:Ne=0,maxlenratio:De=20,vocoder:nt=null}={}){const at={input_ids:O},{encoder_outputs:wt,encoder_attention_mask:Mt}=await ve(this,at),Zt=wt.dims[1]/this.config.reduction_factor,Xt=Math.floor(Zt*De),Vt=Math.floor(Zt*Ne),er=this.config.num_mel_bins;let hr=[],_r=null,ur=null,vr=0;for(;;){++vr;const $r=re(!!ur);let Gr;ur?Gr=ur.output_sequence_out:Gr=new w.Tensor("float32",new Float32Array(er),[1,1,er]);let tn={use_cache_branch:$r,output_sequence:Gr,encoder_attention_mask:Mt,speaker_embeddings:Z,encoder_hidden_states:wt};this.addPastKeyValues(tn,_r),ur=await Te(this.sessions.decoder_model_merged,tn),_r=this.getPastKeyValues(ur,_r);const{prob:Mn,spectrum:En}=ur;if(hr.push(En),vr>=Vt&&(Array.from(Mn.data).filter(os=>os>=xe).length>0||vr>=Xt))break}const Kr=(0,w.cat)(hr),{waveform:Ur}=await Te(nt.sessions.model,{spectrogram:Kr});return{spectrogram:Kr,waveform:Ur}}}class yh extends ae{constructor(){super(...arguments);we(this,"main_input_name","spectrogram")}}class wh extends ae{}class vh extends wh{}class Eh extends ae{}class ms extends Eh{}class As extends Eh{}class Hs extends ae{}class ha extends Hs{}class Th extends Hs{}class Wu extends ae{}class xh extends Wu{}class Mh extends Wu{}class Qi extends ae{}class Ph extends Qi{}class Ch extends Qi{static async from_pretrained(O,Z={}){return super.from_pretrained(O,{...Z,model_file_name:Z.model_file_name??"text_model"})}}class Sh extends Qi{static async from_pretrained(O,Z={}){return super.from_pretrained(O,{...Z,model_file_name:Z.model_file_name??"audio_model"})}}class Ah extends ae{}class Gu extends Ah{async _call(O){return new Bf(await super._call(O))}}class Hu extends ae{}class Dn extends Hu{}class kh extends Hu{}class Ih extends Hu{}class Ji extends ae{}class $h extends Ji{}class oi extends Ji{}class Ku extends ae{}class Oh extends Ku{}class Lh extends Ku{async _call(O){return new ar(await super._call(O))}}class qu extends ae{}class am extends qu{}class im extends qu{}class eo extends ae{constructor(){super(...arguments);we(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"])}_apply_and_filter_by_delay_pattern_mask(Z){const[xe,Ne]=Z.dims,De=this.config.decoder.num_codebooks,nt=Ne-De;let at=0;for(let Zt=0;Zt0&&er<=nt&&(Z.data[at++]=Z.data[Zt])}const wt=Math.floor(xe/De),Mt=at/(wt*De);return new w.Tensor(Z.type,Z.data.slice(0,at),[wt,De,Mt])}prepare_inputs_for_generation(Z,xe,Ne){let De=structuredClone(Z);for(let at=0;at=wt&&(De[at][wt]=BigInt(this.config.decoder.pad_token_id));return Ne.guidance_scale!==null&&Ne.guidance_scale>1&&(De=De.concat(De)),super.prepare_inputs_for_generation(De,xe,Ne)}async generate(Z){const xe=await super.generate(Z),Ne=this._apply_and_filter_by_delay_pattern_mask(xe).unsqueeze_(0),{audio_values:De}=await Te(this.sessions.encodec_decode,{audio_codes:Ne});return De}}class Zu extends ae{}class Rh extends Zu{}class Fh extends Zu{async _call(O){return new ar(await super._call(O))}}class Yu extends ae{}class Nh extends Yu{}class Xu extends Yu{async _call(O){return new ar(await super._call(O))}}class Qu extends ae{}class om extends Qu{}class Ju extends Qu{async _call(O){return new ar(await super._call(O))}}class el extends ae{}class Dh extends el{}class Bh extends el{async _call(O){return new ar(await super._call(O))}}class um extends ae{}class jh extends um{}class zh extends ae{}class Uh extends zh{constructor(...Z){super(...Z);we(this,"forward_params",["input_ids","pixel_values","images_seq_mask","images_emb_mask","attention_mask","position_ids","past_key_values"]);this._generation_mode="text"}async forward(Z){const xe=this._generation_mode??"text";let Ne;if(xe==="text"||!Z.past_key_values){const Mt=this.sessions.prepare_inputs_embeds,Zt=(0,d.pick)(Z,Mt.inputNames);Ne=await Te(Mt,Zt)}else{const Mt=this.sessions.gen_img_embeds,Zt=(0,d.pick)({image_ids:Z.input_ids},Mt.inputNames);Ne=await Te(Mt,Zt)}const De={...Z,...Ne},nt=await me(this,De),at=this.sessions[xe==="text"?"lm_head":"gen_head"];if(!at)throw new Error(`Unable to find "${at}" generation head`);const wt=await Te(at,(0,d.pick)(nt,at.inputNames));return{...Ne,...nt,...wt}}async generate(Z){return this._generation_mode="text",super.generate(Z)}async generate_images(Z){this._generation_mode="image";const xe=(Z.inputs??Z[this.main_input_name]).dims[1],De=(await super.generate(Z)).slice(null,[xe,null]),nt=this.sessions.image_decode,{decoded_image:at}=await Te(nt,{generated_tokens:De}),wt=at.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),Mt=[];for(const Zt of wt){const Xt=M.RawImage.fromTensor(Zt);Mt.push(Xt)}return Mt}}class lm extends He{constructor({char_logits:O,bpe_logits:Z,wp_logits:xe}){super(),this.char_logits=O,this.bpe_logits=Z,this.wp_logits=xe}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}}class Vh extends ae{}class Wh extends Vh{async _call(O){return new lm(await super._call(O))}}class Gh extends ae{}class Hh extends Gh{}class Kh extends Gh{}class tl extends ae{}class qh extends tl{}class Zh extends tl{}class Fr{static async from_pretrained(O,{progress_callback:Z=null,config:xe=null,cache_dir:Ne=null,local_files_only:De=!1,revision:nt="main",model_file_name:at=null,subfolder:wt="onnx",device:Mt=null,dtype:Zt=null,use_external_data_format:Xt=null,session_options:Vt={}}={}){const er={progress_callback:Z,config:xe,cache_dir:Ne,local_files_only:De,revision:nt,model_file_name:at,subfolder:wt,device:Mt,dtype:Zt,use_external_data_format:Xt,session_options:Vt};if(er.config=await n.AutoConfig.from_pretrained(O,er),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);for(const hr of this.MODEL_CLASS_MAPPINGS){const _r=hr.get(er.config.model_type);if(_r)return await _r[1].from_pretrained(O,er)}if(this.BASE_IF_FAIL)return console.warn(`Unknown model class "${er.config.model_type}", attempting to construct from base class.`),await ae.from_pretrained(O,er);throw Error(`Unsupported model type: ${er.config.model_type}`)}}we(Fr,"MODEL_CLASS_MAPPINGS",null),we(Fr,"BASE_IF_FAIL",!1);const cm=new Map([["bert",["BertModel",Se]],["modernbert",["ModernBertModel",ht]],["nomic_bert",["NomicBertModel",de]],["roformer",["RoFormerModel",Ee]],["electra",["ElectraModel",nn]],["esm",["EsmModel",$i]],["convbert",["ConvBertModel",Ct]],["camembert",["CamembertModel",qt]],["deberta",["DebertaModel",ia]],["deberta-v2",["DebertaV2Model",At]],["mpnet",["MPNetModel",Pa]],["albert",["AlbertModel",Ja]],["distilbert",["DistilBertModel",zn]],["roberta",["RobertaModel",Nn]],["xlm",["XLMModel",sn]],["xlm-roberta",["XLMRobertaModel",Dt]],["clap",["ClapModel",Ph]],["clip",["CLIPModel",oc]],["clipseg",["CLIPSegModel",fc]],["chinese_clip",["ChineseCLIPModel",ss]],["siglip",["SiglipModel",cc]],["jina_clip",["JinaCLIPModel",Fi]],["mobilebert",["MobileBertModel",Za]],["squeezebert",["SqueezeBertModel",ka]],["wav2vec2",["Wav2Vec2Model",Zd]],["wav2vec2-bert",["Wav2Vec2BertModel",ih]],["unispeech",["UniSpeechModel",Vu]],["unispeech-sat",["UniSpeechSatModel",em]],["hubert",["HubertModel",lh]],["wavlm",["WavLMModel",hh]],["audio-spectrogram-transformer",["ASTModel",Zl]],["vits",["VitsModel",Gu]],["pyannote",["PyAnnoteModel",Jd]],["wespeaker-resnet",["WeSpeakerResNetModel",Jp]],["detr",["DetrModel",wd]],["rt_detr",["RTDetrModel",bu]],["table-transformer",["TableTransformerModel",wu]],["vit",["ViTModel",Xc]],["ijepa",["IJepaModel",Jc]],["pvt",["PvtModel",cu]],["vit_msn",["ViTMSNModel",ad]],["vit_mae",["ViTMAEModel",sd]],["groupvit",["GroupViTModel",od]],["fastvit",["FastViTModel",ud]],["mobilevit",["MobileViTModel",dd]],["mobilevitv2",["MobileViTV2Model",fd]],["owlvit",["OwlViTModel",md]],["owlv2",["Owlv2Model",gd]],["beit",["BeitModel",bd]],["deit",["DeiTModel",vu]],["hiera",["HieraModel",xd]],["convnext",["ConvNextModel",Fu]],["convnextv2",["ConvNextV2Model",Xp]],["dinov2",["Dinov2Model",Fd]],["dinov2_with_registers",["Dinov2WithRegistersModel",Nd]],["resnet",["ResNetModel",Md]],["swin",["SwinModel",Vi]],["swin2sr",["Swin2SRModel",Pd]],["donut-swin",["DonutSwinModel",Ld]],["yolos",["YolosModel",zd]],["dpt",["DPTModel",ku]],["glpn",["GLPNModel",Hi]],["hifigan",["SpeechT5HifiGan",yh]],["efficientnet",["EfficientNetModel",Oh]],["decision_transformer",["DecisionTransformerModel",jh]],["patchtst",["PatchTSTForPrediction",Hh]],["patchtsmixer",["PatchTSMixerForPrediction",qh]],["mobilenet_v1",["MobileNetV1Model",Rh]],["mobilenet_v2",["MobileNetV2Model",Nh]],["mobilenet_v3",["MobileNetV3Model",om]],["mobilenet_v4",["MobileNetV4Model",Dh]],["maskformer",["MaskFormerModel",Od]],["mgp-str",["MgpstrForSceneTextRecognition",Wh]],["style_text_to_speech_2",["StyleTextToSpeech2Model",gh]]]),dm=new Map([["t5",["T5Model",N]],["longt5",["LongT5Model",Ae]],["mt5",["MT5Model",_t]],["bart",["BartModel",St]],["mbart",["MBartModel",rn]],["marian",["MarianModel",Hd]],["whisper",["WhisperModel",Yl]],["m2m_100",["M2M100Model",Ki]],["blenderbot",["BlenderbotModel",ze]],["blenderbot-small",["BlenderbotSmallModel",Xr]]]),hm=new Map([["bloom",["BloomModel",Gc]],["jais",["JAISModel",gc]],["gpt2",["GPT2Model",mc]],["gptj",["GPTJModel",Ec]],["gpt_bigcode",["GPTBigCodeModel",xc]],["gpt_neo",["GPTNeoModel",is]],["gpt_neox",["GPTNeoXModel",wc]],["codegen",["CodeGenModel",Uo]],["llama",["LlamaModel",Wo]],["exaone",["ExaoneModel",Di]],["olmo",["OlmoModel",Ac]],["olmo2",["Olmo2Model",kc]],["mobilellm",["MobileLLMModel",Sc]],["granite",["GraniteModel",Vp]],["cohere",["CohereModel",Oc]],["gemma",["GemmaModel",Cr]],["gemma2",["Gemma2Model",Rc]],["openelm",["OpenELMModel",Nc]],["qwen2",["Qwen2Model",Bc]],["phi",["PhiModel",Vc]],["phi3",["Phi3Model",Bi]],["mpt",["MptModel",Kc]],["opt",["OPTModel",Zc]],["mistral",["MistralModel",ms]],["starcoder2",["Starcoder2Model",ha]],["falcon",["FalconModel",xh]],["stablelm",["StableLmModel",$h]]]),rl=new Map([["speecht5",["SpeechT5ForSpeechToText",sm]],["whisper",["WhisperForConditionalGeneration",Xl]],["moonshine",["MoonshineForConditionalGeneration",Ql]]]),Yh=new Map([["speecht5",["SpeechT5ForTextToSpeech",bh]]]),Xh=new Map([["vits",["VitsModel",Gu]],["musicgen",["MusicgenForConditionalGeneration",eo]]]),Qh=new Map([["bert",["BertForSequenceClassification",qe]],["modernbert",["ModernBertForSequenceClassification",ct]],["roformer",["RoFormerForSequenceClassification",Ze]],["electra",["ElectraForSequenceClassification",Es]],["esm",["EsmForSequenceClassification",Ka]],["convbert",["ConvBertForSequenceClassification",Nt]],["camembert",["CamembertForSequenceClassification",Ts]],["deberta",["DebertaForSequenceClassification",Fs]],["deberta-v2",["DebertaV2ForSequenceClassification",pn]],["mpnet",["MPNetForSequenceClassification",Ca]],["albert",["AlbertForSequenceClassification",Ia]],["distilbert",["DistilBertForSequenceClassification",en]],["roberta",["RobertaForSequenceClassification",Ir]],["xlm",["XLMForSequenceClassification",_n]],["xlm-roberta",["XLMRobertaForSequenceClassification",Co]],["bart",["BartForSequenceClassification",kr]],["mbart",["MBartForSequenceClassification",mr]],["mobilebert",["MobileBertForSequenceClassification",zs]],["squeezebert",["SqueezeBertForSequenceClassification",Xa]]]),Jh=new Map([["bert",["BertForTokenClassification",Ge]],["modernbert",["ModernBertForTokenClassification",gt]],["roformer",["RoFormerForTokenClassification",rt]],["electra",["ElectraForTokenClassification",na]],["esm",["EsmForTokenClassification",qa]],["convbert",["ConvBertForTokenClassification",br]],["camembert",["CamembertForTokenClassification",xs]],["deberta",["DebertaForTokenClassification",Ns]],["deberta-v2",["DebertaV2ForTokenClassification",Ds]],["mpnet",["MPNetForTokenClassification",Sa]],["distilbert",["DistilBertForTokenClassification",ps]],["roberta",["RobertaForTokenClassification",Qr]],["xlm",["XLMForTokenClassification",Ft]],["xlm-roberta",["XLMRobertaForTokenClassification",Kl]]]),nl=new Map([["t5",["T5ForConditionalGeneration",ee]],["longt5",["LongT5ForConditionalGeneration",Oe]],["mt5",["MT5ForConditionalGeneration",Et]],["bart",["BartForConditionalGeneration",tr]],["mbart",["MBartForConditionalGeneration",Gt]],["marian",["MarianMTModel",Kd]],["m2m_100",["M2M100ForConditionalGeneration",si]],["blenderbot",["BlenderbotForConditionalGeneration",xn]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",yn]]]),ef=new Map([["bloom",["BloomForCausalLM",Hc]],["gpt2",["GPT2LMHeadModel",_c]],["jais",["JAISLMHeadModel",bc]],["gptj",["GPTJForCausalLM",Tc]],["gpt_bigcode",["GPTBigCodeForCausalLM",Mc]],["gpt_neo",["GPTNeoForCausalLM",yc]],["gpt_neox",["GPTNeoXForCausalLM",vc]],["codegen",["CodeGenForCausalLM",Pc]],["llama",["LlamaForCausalLM",Up]],["exaone",["ExaoneForCausalLM",Cc]],["olmo",["OlmoForCausalLM",qo]],["olmo2",["Olmo2ForCausalLM",Ic]],["mobilellm",["MobileLLMForCausalLM",ti]],["granite",["GraniteForCausalLM",$c]],["cohere",["CohereForCausalLM",Wp]],["gemma",["GemmaForCausalLM",Lc]],["gemma2",["Gemma2ForCausalLM",Fc]],["openelm",["OpenELMForCausalLM",Dc]],["qwen2",["Qwen2ForCausalLM",jc]],["phi",["PhiForCausalLM",ri]],["phi3",["Phi3ForCausalLM",Wc]],["mpt",["MptForCausalLM",qc]],["opt",["OPTForCausalLM",Yc]],["mbart",["MBartForCausalLM",On]],["mistral",["MistralForCausalLM",As]],["starcoder2",["Starcoder2ForCausalLM",Th]],["falcon",["FalconForCausalLM",Mh]],["trocr",["TrOCRForCausalLM",vh]],["stablelm",["StableLmForCausalLM",oi]],["phi3_v",["Phi3VForCausalLM",Zn]]]),to=new Map([["multi_modality",["MultiModalityCausalLM",Uh]]]),sl=new Map([["bert",["BertForMaskedLM",Ke]],["modernbert",["ModernBertForMaskedLM",mt]],["roformer",["RoFormerForMaskedLM",Fe]],["electra",["ElectraForMaskedLM",$n]],["esm",["EsmForMaskedLM",Ha]],["convbert",["ConvBertForMaskedLM",Lt]],["camembert",["CamembertForMaskedLM",sa]],["deberta",["DebertaForMaskedLM",Ms]],["deberta-v2",["DebertaV2ForMaskedLM",Ut]],["mpnet",["MPNetForMaskedLM",oa]],["albert",["AlbertForMaskedLM",Tr]],["distilbert",["DistilBertForMaskedLM",Ma]],["roberta",["RobertaForMaskedLM",ns]],["xlm",["XLMWithLMHeadModel",Jr]],["xlm-roberta",["XLMRobertaForMaskedLM",Hl]],["mobilebert",["MobileBertForMaskedLM",Oi]],["squeezebert",["SqueezeBertForMaskedLM",Ya]]]),al=new Map([["bert",["BertForQuestionAnswering",We]],["roformer",["RoFormerForQuestionAnswering",dt]],["electra",["ElectraForQuestionAnswering",fn]],["convbert",["ConvBertForQuestionAnswering",Rr]],["camembert",["CamembertForQuestionAnswering",aa]],["deberta",["DebertaForQuestionAnswering",jn]],["deberta-v2",["DebertaV2ForQuestionAnswering",Ps]],["mpnet",["MPNetForQuestionAnswering",Aa]],["albert",["AlbertForQuestionAnswering",ei]],["distilbert",["DistilBertForQuestionAnswering",fr]],["roberta",["RobertaForQuestionAnswering",xt]],["xlm",["XLMForQuestionAnswering",ua]],["xlm-roberta",["XLMRobertaForQuestionAnswering",ql]],["mobilebert",["MobileBertForQuestionAnswering",rs]],["squeezebert",["SqueezeBertForQuestionAnswering",Qa]]]),ro=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Io]],["idefics3",["Idefics3ForConditionalGeneration",$o]]]),tf=new Map([["llava",["LlavaForConditionalGeneration",Li]],["llava_onevision",["LlavaOnevisionForConditionalGeneration",Jl]],["moondream1",["Moondream1ForConditionalGeneration",ec]],["florence2",["Florence2ForConditionalGeneration",rc]],["qwen2-vl",["Qwen2VLForConditionalGeneration",Uc]],["idefics3",["Idefics3ForConditionalGeneration",$o]],["paligemma",["PaliGemmaForConditionalGeneration",sc]]]),fm=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Io]]]),rf=new Map([["vit",["ViTForImageClassification",Qc]],["ijepa",["IJepaForImageClassification",ed]],["pvt",["PvtForImageClassification",rd]],["vit_msn",["ViTMSNForImageClassification",id]],["fastvit",["FastViTForImageClassification",Gp]],["mobilevit",["MobileViTForImageClassification",hd]],["mobilevitv2",["MobileViTV2ForImageClassification",pd]],["beit",["BeitForImageClassification",yd]],["deit",["DeiTForImageClassification",Eu]],["hiera",["HieraForImageClassification",xu]],["convnext",["ConvNextForImageClassification",Yp]],["convnextv2",["ConvNextV2ForImageClassification",Rd]],["dinov2",["Dinov2ForImageClassification",Bu]],["dinov2_with_registers",["Dinov2WithRegistersForImageClassification",zu]],["resnet",["ResNetForImageClassification",Mu]],["swin",["SwinForImageClassification",Cu]],["segformer",["SegformerForImageClassification",kh]],["efficientnet",["EfficientNetForImageClassification",Lh]],["mobilenet_v1",["MobileNetV1ForImageClassification",Fh]],["mobilenet_v2",["MobileNetV2ForImageClassification",Xu]],["mobilenet_v3",["MobileNetV3ForImageClassification",Ju]],["mobilenet_v4",["MobileNetV4ForImageClassification",Bh]]]),il=new Map([["detr",["DetrForObjectDetection",vd]],["rt_detr",["RTDetrForObjectDetection",da]],["table-transformer",["TableTransformerForObjectDetection",Td]],["yolos",["YolosForObjectDetection",Ud]]]),ol=new Map([["owlvit",["OwlViTForObjectDetection",_d]],["owlv2",["Owlv2ForObjectDetection",Hp]],["grounding-dino",["GroundingDinoForObjectDetection",Bd]]]),nf=new Map([["detr",["DetrForSegmentation",Ed]],["clipseg",["CLIPSegForImageSegmentation",pc]]]),sf=new Map([["segformer",["SegformerForSemanticSegmentation",Ih]],["sapiens",["SapiensForSemanticSegmentation",Sd]]]),ul=new Map([["detr",["DetrForSegmentation",Ed]],["maskformer",["MaskFormerForInstanceSegmentation",Gi]]]),af=new Map([["sam",["SamModel",Wd]]]),of=new Map([["wav2vec2",["Wav2Vec2ForCTC",Yd]],["wav2vec2-bert",["Wav2Vec2BertForCTC",oh]],["unispeech",["UniSpeechForCTC",rh]],["unispeech-sat",["UniSpeechSatForCTC",sh]],["wavlm",["WavLMForCTC",fh]],["hubert",["HubertForCTC",ch]]]),ll=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",Xd]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",uh]],["unispeech",["UniSpeechForSequenceClassification",nh]],["unispeech-sat",["UniSpeechSatForSequenceClassification",ah]],["wavlm",["WavLMForSequenceClassification",ph]],["hubert",["HubertForSequenceClassification",dh]],["audio-spectrogram-transformer",["ASTForAudioClassification",So]]]),uf=new Map([["wavlm",["WavLMForXVector",mh]]]),lf=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",tm]],["wavlm",["WavLMForAudioFrameClassification",rm]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",Qd]],["pyannote",["PyAnnoteForAudioFrameClassification",eh]]]),cf=new Map([["vitmatte",["VitMatteForImageMatting",cd]]]),pm=new Map([["patchtst",["PatchTSTForPrediction",Kh]],["patchtsmixer",["PatchTSMixerForPrediction",Zh]]]),mm=new Map([["swin2sr",["Swin2SRForImageSuperResolution",qp]]]),df=new Map([["dpt",["DPTForDepthEstimation",ni]],["depth_anything",["DepthAnythingForDepthEstimation",Iu]],["glpn",["GLPNForDepthEstimation",Ou]],["sapiens",["SapiensForDepthEstimation",Ad]],["depth_pro",["DepthProForDepthEstimation",Id]]]),hf=new Map([["sapiens",["SapiensForNormalEstimation",Zp]]]),ff=new Map([["vitpose",["VitPoseForPoseEstimation",td]]]),pf=new Map([["clip",["CLIPVisionModelWithProjection",lc]],["siglip",["SiglipVisionModel",hc]],["jina_clip",["JinaCLIPVisionModel",as]]]),_m=[[cm,F.EncoderOnly],[dm,F.EncoderDecoder],[hm,F.DecoderOnly],[Qh,F.EncoderOnly],[Jh,F.EncoderOnly],[nl,F.Seq2Seq],[rl,F.Seq2Seq],[ef,F.DecoderOnly],[to,F.MultiModality],[sl,F.EncoderOnly],[al,F.EncoderOnly],[ro,F.Vision2Seq],[tf,F.ImageTextToText],[rf,F.EncoderOnly],[nf,F.EncoderOnly],[ul,F.EncoderOnly],[sf,F.EncoderOnly],[cf,F.EncoderOnly],[pm,F.EncoderOnly],[mm,F.EncoderOnly],[df,F.EncoderOnly],[hf,F.EncoderOnly],[ff,F.EncoderOnly],[il,F.EncoderOnly],[ol,F.EncoderOnly],[af,F.MaskGeneration],[of,F.EncoderOnly],[ll,F.EncoderOnly],[Yh,F.Seq2Seq],[Xh,F.EncoderOnly],[uf,F.EncoderOnly],[lf,F.EncoderOnly],[pf,F.EncoderOnly]];for(const[A,O]of _m)for(const[Z,xe]of A.values())I.set(Z,O),$.set(xe,Z),k.set(Z,xe);const gm=[["MusicgenForConditionalGeneration",eo,F.Musicgen],["Phi3VForCausalLM",Zn,F.Phi3V],["CLIPTextModelWithProjection",uc,F.EncoderOnly],["SiglipTextModel",dc,F.EncoderOnly],["JinaCLIPTextModel",Lo,F.EncoderOnly],["ClapTextModelWithProjection",Ch,F.EncoderOnly],["ClapAudioModelWithProjection",Sh,F.EncoderOnly]];for(const[A,O,Z]of gm)I.set(A,Z),$.set(O,A),k.set(A,O);class cl extends Fr{}we(cl,"MODEL_CLASS_MAPPINGS",_m.map(O=>O[0])),we(cl,"BASE_IF_FAIL",!0);class mf extends Fr{}we(mf,"MODEL_CLASS_MAPPINGS",[Qh]);class bm extends Fr{}we(bm,"MODEL_CLASS_MAPPINGS",[Jh]);class _f extends Fr{}we(_f,"MODEL_CLASS_MAPPINGS",[nl]);class gf extends Fr{}we(gf,"MODEL_CLASS_MAPPINGS",[rl]);class bf extends Fr{}we(bf,"MODEL_CLASS_MAPPINGS",[Yh]);class yf extends Fr{}we(yf,"MODEL_CLASS_MAPPINGS",[Xh]);class ym extends Fr{}we(ym,"MODEL_CLASS_MAPPINGS",[ef]);class wf extends Fr{}we(wf,"MODEL_CLASS_MAPPINGS",[sl]);class vf extends Fr{}we(vf,"MODEL_CLASS_MAPPINGS",[al]);class Ef extends Fr{}we(Ef,"MODEL_CLASS_MAPPINGS",[ro]);class Tf extends Fr{}we(Tf,"MODEL_CLASS_MAPPINGS",[rf]);class xf extends Fr{}we(xf,"MODEL_CLASS_MAPPINGS",[nf]);class Mf extends Fr{}we(Mf,"MODEL_CLASS_MAPPINGS",[sf]);class Pf extends Fr{}we(Pf,"MODEL_CLASS_MAPPINGS",[ul]);class Cf extends Fr{}we(Cf,"MODEL_CLASS_MAPPINGS",[il]);class Sf extends Fr{}we(Sf,"MODEL_CLASS_MAPPINGS",[ol]);class Af extends Fr{}we(Af,"MODEL_CLASS_MAPPINGS",[af]);class kf extends Fr{}we(kf,"MODEL_CLASS_MAPPINGS",[of]);class dl extends Fr{}we(dl,"MODEL_CLASS_MAPPINGS",[ll]);class If extends Fr{}we(If,"MODEL_CLASS_MAPPINGS",[uf]);class $f extends Fr{}we($f,"MODEL_CLASS_MAPPINGS",[lf]);class Of extends Fr{}we(Of,"MODEL_CLASS_MAPPINGS",[fm]);class Lf extends Fr{}we(Lf,"MODEL_CLASS_MAPPINGS",[cf]);class Rf extends Fr{}we(Rf,"MODEL_CLASS_MAPPINGS",[mm]);class Ff extends Fr{}we(Ff,"MODEL_CLASS_MAPPINGS",[df]);class Nf extends Fr{}we(Nf,"MODEL_CLASS_MAPPINGS",[hf]);class wm extends Fr{}we(wm,"MODEL_CLASS_MAPPINGS",[ff]);class Df extends Fr{}we(Df,"MODEL_CLASS_MAPPINGS",[pf]);class vm extends He{constructor({logits:O,past_key_values:Z,encoder_outputs:xe,decoder_attentions:Ne=null,cross_attentions:De=null}){super(),this.logits=O,this.past_key_values=Z,this.encoder_outputs=xe,this.decoder_attentions=Ne,this.cross_attentions=De}}class ar extends He{constructor({logits:O,...Z}){super(),this.logits=O;const xe=Object.values(Z);xe.length>0&&(this.attentions=xe)}}class Em extends He{constructor({logits:O,embeddings:Z}){super(),this.logits=O,this.embeddings=Z}}class gn extends He{constructor({logits:O}){super(),this.logits=O}}class vn extends He{constructor({logits:O}){super(),this.logits=O}}class Sn extends He{constructor({start_logits:O,end_logits:Z}){super(),this.start_logits=O,this.end_logits=Z}}class Oa extends He{constructor({logits:O}){super(),this.logits=O}}class Tm extends He{constructor({logits:O,past_key_values:Z}){super(),this.logits=O,this.past_key_values=Z}}class ui extends He{constructor({alphas:O}){super(),this.alphas=O}}class Bf extends He{constructor({waveform:O,spectrogram:Z}){super(),this.waveform=O,this.spectrogram=Z}}},"./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js":(r,e,t)=>{t.r(e),t.d(e,{ASTFeatureExtractor:()=>o});var n=t("./src/base/feature_extraction_utils.js");t("./src/utils/tensor.js");var a=t("./src/utils/audio.js");class o extends n.FeatureExtractor{constructor(d){super(d);const c=this.config.sampling_rate,h=(0,a.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(c/2),c,null,"kaldi",!0);for(let _=0;_{t.r(e),t.d(e,{AutoFeatureExtractor:()=>u});var n=t("./src/utils/constants.js"),a=t("./src/utils/hub.js");t("./src/base/feature_extraction_utils.js");var o=t("./src/models/feature_extractors.js");class u{static async from_pretrained(c,h={}){const _=await(0,a.getModelJSON)(c,n.FEATURE_EXTRACTOR_NAME,!0,h),y=_.feature_extractor_type,w=o[y];if(!w)throw new Error(`Unknown feature_extractor_type: '${y}'. Please report this at ${n.GITHUB_ISSUE_URL}.`);return new w(_)}}},"./src/models/auto/image_processing_auto.js":(r,e,t)=>{t.r(e),t.d(e,{AutoImageProcessor:()=>d});var n=t("./src/utils/constants.js"),a=t("./src/utils/hub.js"),o=t("./src/base/image_processors_utils.js"),u=t("./src/models/image_processors.js");class d{static async from_pretrained(h,_={}){const y=await(0,a.getModelJSON)(h,n.IMAGE_PROCESSOR_NAME,!0,_),w=y.image_processor_type??y.feature_extractor_type;let M=u[w];return M||(w!==void 0&&console.warn(`Image processor type '${w}' not found, assuming base ImageProcessor. Please report this at ${n.GITHUB_ISSUE_URL}.`),M=o.ImageProcessor),new M(y)}}},"./src/models/auto/processing_auto.js":(r,e,t)=>{t.r(e),t.d(e,{AutoProcessor:()=>h});var n=t("./src/utils/constants.js"),a=t("./src/utils/hub.js"),o=t("./src/base/processing_utils.js"),u=t("./src/models/processors.js"),d=t("./src/models/image_processors.js"),c=t("./src/models/feature_extractors.js");class h{static async from_pretrained(y,w={}){const M=await(0,a.getModelJSON)(y,n.IMAGE_PROCESSOR_NAME,!0,w),{image_processor_type:S,feature_extractor_type:G,processor_class:H}=M;if(H&&u[H])return u[H].from_pretrained(y,w);if(!S&&!G)throw new Error("No `image_processor_type` or `feature_extractor_type` found in the config.");const B={};if(S){const U=d[S];if(!U)throw new Error(`Unknown image_processor_type: '${S}'.`);B.image_processor=new U(M)}if(G){const U=d[G];if(U)B.image_processor=new U(M);else{const F=c[G];if(!F)throw new Error(`Unknown feature_extractor_type: '${G}'.`);B.feature_extractor=new F(M)}}const z={};return new o.Processor(z,B)}}},"./src/models/beit/image_processing_beit.js":(r,e,t)=>{t.r(e),t.d(e,{BeitFeatureExtractor:()=>a});var n=t("./src/base/image_processors_utils.js");class a extends n.ImageProcessor{}},"./src/models/bit/image_processing_bit.js":(r,e,t)=>{t.r(e),t.d(e,{BitImageProcessor:()=>a});var n=t("./src/base/image_processors_utils.js");class a extends n.ImageProcessor{}},"./src/models/chinese_clip/image_processing_chinese_clip.js":(r,e,t)=>{t.r(e),t.d(e,{ChineseCLIPFeatureExtractor:()=>a});var n=t("./src/base/image_processors_utils.js");class a extends n.ImageProcessor{}},"./src/models/clap/feature_extraction_clap.js":(r,e,t)=>{t.r(e),t.d(e,{ClapFeatureExtractor:()=>o});var n=t("./src/base/feature_extraction_utils.js");t("./src/utils/tensor.js");var a=t("./src/utils/audio.js");class o extends n.FeatureExtractor{constructor(d){super(d),this.mel_filters=(0,a.mel_filter_bank)(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,null,"htk"),this.mel_filters_slaney=(0,a.mel_filter_bank)(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,"slaney","slaney"),this.window=(0,a.window_function)(this.config.fft_window_size,"hann")}async _get_input_mel(d,c,h,_){let y;const w=d.length-c;if(w>0)if(h==="rand_trunc"){const M=Math.floor(Math.random()*(w+1));d=d.subarray(M,M+c),y=await this._extract_fbank_features(d,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${h}" not implemented`);else{if(w<0){let M=new Float64Array(c);if(M.set(d),_==="repeat")for(let S=d.length;S{t.r(e),t.d(e,{CLIPFeatureExtractor:()=>o,CLIPImageProcessor:()=>a});var n=t("./src/base/image_processors_utils.js");class a extends n.ImageProcessor{}class o extends a{}},"./src/models/convnext/image_processing_convnext.js":(r,e,t)=>{t.r(e),t.d(e,{ConvNextFeatureExtractor:()=>o,ConvNextImageProcessor:()=>a});var n=t("./src/base/image_processors_utils.js");class a extends n.ImageProcessor{constructor(d){super(d),this.crop_pct=this.config.crop_pct??224/256}async resize(d){var h;const c=(h=this.size)==null?void 0:h.shortest_edge;if(c===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(c<384){const _=Math.floor(c/this.crop_pct),[y,w]=this.get_resize_output_image_size(d,{shortest_edge:_});d=await d.resize(y,w,{resample:this.resample}),d=await d.center_crop(c,c)}else d=await d.resize(c,c,{resample:this.resample});return d}}class o extends a{}},"./src/models/deit/image_processing_deit.js":(r,e,t)=>{t.r(e),t.d(e,{DeiTFeatureExtractor:()=>o,DeiTImageProcessor:()=>a});var n=t("./src/base/image_processors_utils.js");class a extends n.ImageProcessor{}class o extends a{}},"./src/models/detr/image_processing_detr.js":(r,e,t)=>{t.r(e),t.d(e,{DetrFeatureExtractor:()=>u,DetrImageProcessor:()=>o});var n=t("./src/base/image_processors_utils.js"),a=t("./src/utils/tensor.js");class o extends n.ImageProcessor{async _call(c){const h=await super._call(c),_=[h.pixel_values.dims[0],64,64],y=(0,a.full)(_,1n);return{...h,pixel_mask:y}}post_process_object_detection(...c){return(0,n.post_process_object_detection)(...c)}post_process_panoptic_segmentation(...c){return(0,n.post_process_panoptic_segmentation)(...c)}post_process_instance_segmentation(...c){return(0,n.post_process_instance_segmentation)(...c)}}class u extends o{}},"./src/models/donut/image_processing_donut.js":(r,e,t)=>{t.r(e),t.d(e,{DonutFeatureExtractor:()=>o,DonutImageProcessor:()=>a});var n=t("./src/base/image_processors_utils.js");class a extends n.ImageProcessor{pad_image(d,c,h,_={}){const[y,w,M]=c;let S=this.image_mean;Array.isArray(this.image_mean)||(S=new Array(M).fill(S));let G=this.image_std;Array.isArray(G)||(G=new Array(M).fill(S));const H=S.map((B,z)=>-B/G[z]);return super.pad_image(d,c,h,{center:!0,constant_values:H,..._})}}class o extends a{}},"./src/models/dpt/image_processing_dpt.js":(r,e,t)=>{t.r(e),t.d(e,{DPTFeatureExtractor:()=>o,DPTImageProcessor:()=>a});var n=t("./src/base/image_processors_utils.js");class a extends n.ImageProcessor{}class o extends a{}},"./src/models/efficientnet/image_processing_efficientnet.js":(r,e,t)=>{t.r(e),t.d(e,{EfficientNetImageProcessor:()=>a});var n=t("./src/base/image_processors_utils.js");class a extends n.ImageProcessor{constructor(u){super(u),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(d=>d*d))}}},"./src/models/feature_extractors.js":(r,e,t)=>{t.r(e),t.d(e,{ASTFeatureExtractor:()=>n.ASTFeatureExtractor,ClapFeatureExtractor:()=>a.ClapFeatureExtractor,ImageFeatureExtractor:()=>w.ImageProcessor,MoonshineFeatureExtractor:()=>o.MoonshineFeatureExtractor,PyAnnoteFeatureExtractor:()=>u.PyAnnoteFeatureExtractor,SeamlessM4TFeatureExtractor:()=>d.SeamlessM4TFeatureExtractor,SpeechT5FeatureExtractor:()=>c.SpeechT5FeatureExtractor,Wav2Vec2FeatureExtractor:()=>h.Wav2Vec2FeatureExtractor,WeSpeakerFeatureExtractor:()=>_.WeSpeakerFeatureExtractor,WhisperFeatureExtractor:()=>y.WhisperFeatureExtractor});var n=t("./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js"),a=t("./src/models/clap/feature_extraction_clap.js"),o=t("./src/models/moonshine/feature_extraction_moonshine.js"),u=t("./src/models/pyannote/feature_extraction_pyannote.js"),d=t("./src/models/seamless_m4t/feature_extraction_seamless_m4t.js"),c=t("./src/models/speecht5/feature_extraction_speecht5.js"),h=t("./src/models/wav2vec2/feature_extraction_wav2vec2.js"),_=t("./src/models/wespeaker/feature_extraction_wespeaker.js"),y=t("./src/models/whisper/feature_extraction_whisper.js"),w=t("./src/base/image_processors_utils.js")},"./src/models/florence2/processing_florence2.js":(r,e,t)=>{t.r(e),t.d(e,{Florence2Processor:()=>u});var n=t("./src/base/processing_utils.js"),a=t("./src/models/auto/image_processing_auto.js"),o=t("./src/tokenizers.js");class u extends n.Processor{constructor(c,h){super(c,h);const{tasks_answer_post_processing_type:_,task_prompts_without_inputs:y,task_prompts_with_input:w}=this.image_processor.config;this.tasks_answer_post_processing_type=new Map(Object.entries(_??{})),this.task_prompts_without_inputs=new Map(Object.entries(y??{})),this.task_prompts_with_input=new Map(Object.entries(w??{})),this.regexes={quad_boxes:/(.+?)/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(c){typeof c=="string"&&(c=[c]);const h=[];for(const _ of c)if(this.task_prompts_without_inputs.has(_))h.push(this.task_prompts_without_inputs.get(_));else{for(const[y,w]of this.task_prompts_with_input)if(_.includes(y)){h.push(w.replaceAll("{input}",_).replaceAll(y,""));break}h.length!==c.length&&h.push(_)}return h}post_process_generation(c,h,_){const y=this.tasks_answer_post_processing_type.get(h)??"pure_text";c=c.replaceAll("","").replaceAll("","");let w;switch(y){case"pure_text":w=c;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const M=y==="ocr"?"quad_boxes":"bboxes",S=c.matchAll(this.regexes[M]),G=[],H=[];for(const[B,z,...U]of S)G.push(z?z.trim():G.at(-1)??""),H.push(U.map((F,I)=>(Number(F)+.5)/this.size_per_bin*_[I%2]));w={labels:G,[M]:H};break;default:throw new Error(`Task "${h}" (of type "${y}") not yet implemented.`)}return{[h]:w}}async _call(c,h=null,_={}){if(!c&&!h)throw new Error("Either text or images must be provided");const y=await this.image_processor(c,_),w=h?this.tokenizer(h,_):{};return{...y,...w}}}we(u,"tokenizer_class",o.AutoTokenizer),we(u,"image_processor_class",a.AutoImageProcessor)},"./src/models/glpn/image_processing_glpn.js":(r,e,t)=>{t.r(e),t.d(e,{GLPNFeatureExtractor:()=>a});var n=t("./src/base/image_processors_utils.js");class a extends n.ImageProcessor{}},"./src/models/grounding_dino/image_processing_grounding_dino.js":(r,e,t)=>{t.r(e),t.d(e,{GroundingDinoImageProcessor:()=>o});var n=t("./src/base/image_processors_utils.js"),a=t("./src/utils/tensor.js");class o extends n.ImageProcessor{async _call(d){const c=await super._call(d),h=c.pixel_values.dims,_=(0,a.ones)([h[0],h[2],h[3]]);return{...c,pixel_mask:_}}}},"./src/models/grounding_dino/processing_grounding_dino.js":(r,e,t)=>{t.r(e),t.d(e,{GroundingDinoProcessor:()=>c});var n=t("./src/base/processing_utils.js"),a=t("./src/models/auto/image_processing_auto.js"),o=t("./src/tokenizers.js"),u=t("./src/base/image_processors_utils.js");function d(h,_){const w=h.dims.at(-1)-1,M=h.tolist();M.fill(!1,0,1),M.fill(!1,w);const S=_.tolist();return M.map((G,H)=>G?H:null).filter(G=>G!==null).map(G=>S[G])}class c extends n.Processor{async _call(_,y,w={}){const M=_?await this.image_processor(_,w):{};return{...y?this.tokenizer(y,w):{},...M}}post_process_grounded_object_detection(_,y,{box_threshold:w=.25,text_threshold:M=.25,target_sizes:S=null}={}){const{logits:G,pred_boxes:H}=_,B=G.dims[0];if(S!==null&&S.length!==B)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const z=G.dims.at(1),U=G.sigmoid(),F=U.max(-1).tolist(),I=H.tolist().map($=>$.map(j=>(0,u.center_to_corners_format)(j))),k=[];for(let $=0;$ie.map((oe,re)=>oe*j[(re+1)%2])));const ce=F[$],ue=[],Pe=[],Te=[];for(let ie=0;ie{t.r(e),t.d(e,{Idefics3ImageProcessor:()=>o});var n=t("./src/base/image_processors_utils.js"),a=t("./src/utils/tensor.js");class o extends n.ImageProcessor{constructor(d){super(d),this.do_image_splitting=d.do_image_splitting??!0,this.max_image_size=d.max_image_size}get_resize_for_vision_encoder(d,c){let[h,_]=d.dims.slice(-2);const y=_/h;return _>=h?(_=Math.ceil(_/c)*c,h=Math.floor(_/y),h=Math.ceil(h/c)*c):(h=Math.ceil(h/c)*c,_=Math.floor(h*y),_=Math.ceil(_/c)*c),{height:h,width:_}}async _call(d,{do_image_splitting:c=null,return_row_col_info:h=!1}={}){let _;if(!Array.isArray(d))_=[[d]];else{if(d.length===0||!d[0])throw new Error("No images provided.");Array.isArray(d[0])?_=d:_=[d]}let y=[],w=[],M=[];const S=[],G=[];for(const $ of _){let j=await Promise.all($.map(Pe=>this.preprocess(Pe)));S.push(...j.map(Pe=>Pe.original_size)),G.push(...j.map(Pe=>Pe.reshaped_input_size)),j.forEach(Pe=>Pe.pixel_values.unsqueeze_(0));const{longest_edge:ce}=this.max_image_size;let ue;if(c??this.do_image_splitting){let Pe=new Array(j.length),Te=new Array(j.length);ue=await Promise.all(j.map(async(ie,oe)=>{const re=this.get_resize_for_vision_encoder(ie.pixel_values,ce),ge=await(0,a.interpolate_4d)(ie.pixel_values,{size:[re.height,re.width]}),{frames:ve,num_splits_h:me,num_splits_w:Le}=await this.split_image(ge,this.max_image_size);return Pe[oe]=me,Te[oe]=Le,(0,a.cat)(ve,0)})),w.push(Pe),M.push(Te)}else{const Pe=[ce,ce];ue=await Promise.all(j.map(Te=>(0,a.interpolate_4d)(Te.pixel_values,{size:Pe}))),w.push(new Array(j.length).fill(0)),M.push(new Array(j.length).fill(0))}y.push((0,a.cat)(ue,0))}const H=y.length,[B,z,U,F]=y[0].dims;let I,k;if(H===1)I=y[0].unsqueeze_(0),k=(0,a.full)([H,B,U,F],!0);else{const $=Math.max(...y.map(ue=>ue.dims.at(0)));k=(0,a.full)([H,$,U,F],!0);const j=k.data,ce=$*U*F;for(let ue=0;ueh||M>_){S=Math.ceil(w/h),G=Math.ceil(M/_);const H=Math.ceil(w/S),B=Math.ceil(M/G);for(let F=0;F{t.r(e),t.d(e,{Idefics3Processor:()=>_});var n=t("./src/base/processing_utils.js"),a=t("./src/models/auto/image_processing_auto.js"),o=t("./src/tokenizers.js");t("./src/utils/image.js");var u=t("./src/utils/core.js");function d(y,w,M,S,G,H){let B="";for(let z=0;z`+G.repeat(y);B+=` `}return B+=` ${S}${H}`+G.repeat(y)+`${S}`,B}function c(y,w,M,S){return`${w}${S}`+M.repeat(y)+`${w}`}function h(y,w,M,S,G,H){return y===0&&w===0?c(M,S,G,H):d(M,y,w,S,G,H)}class _ extends n.Processor{constructor(){super(...arguments);we(this,"fake_image_token","");we(this,"image_token","");we(this,"global_img_token","")}async _call(M,S=null,G={}){G.return_row_col_info??(G.return_row_col_info=!0);let H;S&&(H=await this.image_processor(S,G)),Array.isArray(M)||(M=[M]);const B=H.rows??[new Array(M.length).fill(0)],z=H.cols??[new Array(M.length).fill(0)],U=this.config.image_seq_len,F=[],I=[];for(let $=0;$h(oe,ue[re],U,this.fake_image_token,this.image_token,this.global_img_token)),Te=j.split(this.image_token);if(Te.length===0)throw new Error("The image token should be present in the text.");let ie=Te[0];for(let oe=0;oe{t.r(e),t.d(e,{BeitFeatureExtractor:()=>n.BeitFeatureExtractor,BitImageProcessor:()=>a.BitImageProcessor,CLIPFeatureExtractor:()=>u.CLIPFeatureExtractor,CLIPImageProcessor:()=>u.CLIPImageProcessor,ChineseCLIPFeatureExtractor:()=>o.ChineseCLIPFeatureExtractor,ConvNextFeatureExtractor:()=>d.ConvNextFeatureExtractor,ConvNextImageProcessor:()=>d.ConvNextImageProcessor,DPTFeatureExtractor:()=>y.DPTFeatureExtractor,DPTImageProcessor:()=>y.DPTImageProcessor,DeiTFeatureExtractor:()=>c.DeiTFeatureExtractor,DeiTImageProcessor:()=>c.DeiTImageProcessor,DetrFeatureExtractor:()=>h.DetrFeatureExtractor,DetrImageProcessor:()=>h.DetrImageProcessor,DonutFeatureExtractor:()=>_.DonutFeatureExtractor,DonutImageProcessor:()=>_.DonutImageProcessor,EfficientNetImageProcessor:()=>w.EfficientNetImageProcessor,GLPNFeatureExtractor:()=>M.GLPNFeatureExtractor,GroundingDinoImageProcessor:()=>S.GroundingDinoImageProcessor,Idefics3ImageProcessor:()=>G.Idefics3ImageProcessor,JinaCLIPImageProcessor:()=>B.JinaCLIPImageProcessor,LlavaOnevisionImageProcessor:()=>z.LlavaOnevisionImageProcessor,Mask2FormerImageProcessor:()=>U.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>F.MaskFormerFeatureExtractor,MaskFormerImageProcessor:()=>F.MaskFormerImageProcessor,MobileNetV1FeatureExtractor:()=>I.MobileNetV1FeatureExtractor,MobileNetV1ImageProcessor:()=>I.MobileNetV1ImageProcessor,MobileNetV2FeatureExtractor:()=>k.MobileNetV2FeatureExtractor,MobileNetV2ImageProcessor:()=>k.MobileNetV2ImageProcessor,MobileNetV3FeatureExtractor:()=>$.MobileNetV3FeatureExtractor,MobileNetV3ImageProcessor:()=>$.MobileNetV3ImageProcessor,MobileNetV4FeatureExtractor:()=>j.MobileNetV4FeatureExtractor,MobileNetV4ImageProcessor:()=>j.MobileNetV4ImageProcessor,MobileViTFeatureExtractor:()=>ce.MobileViTFeatureExtractor,MobileViTImageProcessor:()=>ce.MobileViTImageProcessor,NougatImageProcessor:()=>ue.NougatImageProcessor,OwlViTFeatureExtractor:()=>Te.OwlViTFeatureExtractor,OwlViTImageProcessor:()=>Te.OwlViTImageProcessor,Owlv2ImageProcessor:()=>Pe.Owlv2ImageProcessor,Phi3VImageProcessor:()=>ie.Phi3VImageProcessor,PvtImageProcessor:()=>oe.PvtImageProcessor,Qwen2VLImageProcessor:()=>re.Qwen2VLImageProcessor,RTDetrImageProcessor:()=>ge.RTDetrImageProcessor,SamImageProcessor:()=>ve.SamImageProcessor,SegformerFeatureExtractor:()=>me.SegformerFeatureExtractor,SegformerImageProcessor:()=>me.SegformerImageProcessor,SiglipImageProcessor:()=>Le.SiglipImageProcessor,Swin2SRImageProcessor:()=>$e.Swin2SRImageProcessor,VLMImageProcessor:()=>H.VLMImageProcessor,ViTFeatureExtractor:()=>pe.ViTFeatureExtractor,ViTImageProcessor:()=>pe.ViTImageProcessor,VitMatteImageProcessor:()=>X.VitMatteImageProcessor,VitPoseImageProcessor:()=>le.VitPoseImageProcessor,YolosFeatureExtractor:()=>ke.YolosFeatureExtractor,YolosImageProcessor:()=>ke.YolosImageProcessor});var n=t("./src/models/beit/image_processing_beit.js"),a=t("./src/models/bit/image_processing_bit.js"),o=t("./src/models/chinese_clip/image_processing_chinese_clip.js"),u=t("./src/models/clip/image_processing_clip.js"),d=t("./src/models/convnext/image_processing_convnext.js"),c=t("./src/models/deit/image_processing_deit.js"),h=t("./src/models/detr/image_processing_detr.js"),_=t("./src/models/donut/image_processing_donut.js"),y=t("./src/models/dpt/image_processing_dpt.js"),w=t("./src/models/efficientnet/image_processing_efficientnet.js"),M=t("./src/models/glpn/image_processing_glpn.js"),S=t("./src/models/grounding_dino/image_processing_grounding_dino.js"),G=t("./src/models/idefics3/image_processing_idefics3.js"),H=t("./src/models/janus/image_processing_janus.js"),B=t("./src/models/jina_clip/image_processing_jina_clip.js"),z=t("./src/models/llava_onevision/image_processing_llava_onevision.js"),U=t("./src/models/mask2former/image_processing_mask2former.js"),F=t("./src/models/maskformer/image_processing_maskformer.js"),I=t("./src/models/mobilenet_v1/image_processing_mobilenet_v1.js"),k=t("./src/models/mobilenet_v2/image_processing_mobilenet_v2.js"),$=t("./src/models/mobilenet_v3/image_processing_mobilenet_v3.js"),j=t("./src/models/mobilenet_v4/image_processing_mobilenet_v4.js"),ce=t("./src/models/mobilevit/image_processing_mobilevit.js"),ue=t("./src/models/nougat/image_processing_nougat.js"),Pe=t("./src/models/owlv2/image_processing_owlv2.js"),Te=t("./src/models/owlvit/image_processing_owlvit.js"),ie=t("./src/models/phi3_v/image_processing_phi3_v.js"),oe=t("./src/models/pvt/image_processing_pvt.js"),re=t("./src/models/qwen2_vl/image_processing_qwen2_vl.js"),ge=t("./src/models/rt_detr/image_processing_rt_detr.js"),ve=t("./src/models/sam/image_processing_sam.js"),me=t("./src/models/segformer/image_processing_segformer.js"),Le=t("./src/models/siglip/image_processing_siglip.js"),$e=t("./src/models/swin2sr/image_processing_swin2sr.js"),pe=t("./src/models/vit/image_processing_vit.js"),X=t("./src/models/vitmatte/image_processing_vitmatte.js"),le=t("./src/models/vitpose/image_processing_vitpose.js"),ke=t("./src/models/yolos/image_processing_yolos.js")},"./src/models/janus/image_processing_janus.js":(r,e,t)=>{t.r(e),t.d(e,{VLMImageProcessor:()=>a});var n=t("./src/base/image_processors_utils.js");class a extends n.ImageProcessor{constructor(u){super({do_pad:!0,pad_size:{width:u.image_size,height:u.image_size},...u}),this.constant_values=this.config.background_color.map(d=>d*this.rescale_factor)}pad_image(u,d,c,h){return super.pad_image(u,d,c,{constant_values:this.constant_values,center:!0,...h})}}},"./src/models/janus/processing_janus.js":(r,e,t)=>{t.r(e),t.d(e,{VLChatProcessor:()=>h});var n=t("./src/base/processing_utils.js"),a=t("./src/models/auto/image_processing_auto.js"),o=t("./src/tokenizers.js"),u=t("./src/utils/core.js"),d=t("./src/utils/tensor.js"),c=t("./src/utils/image.js");class h extends n.Processor{constructor(y,w){super(y,w),this.image_tag=this.config.image_tag,this.image_start_tag=this.config.image_start_tag,this.image_end_tag=this.config.image_end_tag,this.num_image_tokens=this.config.num_image_tokens}async _call(y,{images:w=null,chat_template:M="default"}={}){w?Array.isArray(w)||(w=[w]):w=await Promise.all(y.filter(ue=>ue.images).flatMap(ue=>ue.images).map(ue=>c.RawImage.read(ue)));const S=this.tokenizer,G=S.apply_chat_template(y,{tokenize:!1,add_generation_prompt:!0,chat_template:M}),H=ue=>S.encode(ue,{add_special_tokens:!1}),B=G.split(this.image_tag),z=B.length-1;if(w.length!==z)throw new Error(`Number of images provided (${w.length}) does not match number of "${this.image_tag}" image tags (${z})`);const[U,F,I]=S.model.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]);let k=H(B[0]),$=new Array(k.length).fill(!1);for(let ue=1;ue0){const ue=await this.image_processor(w);return ue.pixel_values.unsqueeze_(0),{...ce,...ue}}return ce}}we(h,"image_processor_class",a.AutoImageProcessor),we(h,"tokenizer_class",o.AutoTokenizer),we(h,"uses_processor_config",!0)},"./src/models/jina_clip/image_processing_jina_clip.js":(r,e,t)=>{t.r(e),t.d(e,{JinaCLIPImageProcessor:()=>a});var n=t("./src/base/image_processors_utils.js");class a extends n.ImageProcessor{constructor(u){const{resize_mode:d,fill_color:c,interpolation:h,size:_,...y}=u,w=d==="squash"?{width:_,height:_}:d==="shortest"?{shortest_edge:_}:{longest_edge:_},M=h==="bicubic"?3:2;super({...y,size:w,resample:M,do_center_crop:!0,crop_size:_,do_normalize:!0})}}},"./src/models/jina_clip/processing_jina_clip.js":(r,e,t)=>{t.r(e),t.d(e,{JinaCLIPProcessor:()=>u});var n=t("./src/base/processing_utils.js"),a=t("./src/models/auto/image_processing_auto.js"),o=t("./src/tokenizers.js");class u extends n.Processor{async _call(c=null,h=null,_={}){if(!c&&!h)throw new Error("Either text or images must be provided");const y=c?this.tokenizer(c,_):{},w=h?await this.image_processor(h,_):{};return{...y,...w}}}we(u,"tokenizer_class",o.AutoTokenizer),we(u,"image_processor_class",a.AutoImageProcessor)},"./src/models/llava_onevision/image_processing_llava_onevision.js":(r,e,t)=>{t.r(e),t.d(e,{LlavaOnevisionImageProcessor:()=>a});var n=t("./src/base/image_processors_utils.js");class a extends n.ImageProcessor{}},"./src/models/mask2former/image_processing_mask2former.js":(r,e,t)=>{t.r(e),t.d(e,{Mask2FormerImageProcessor:()=>a});var n=t("./src/models/maskformer/image_processing_maskformer.js");class a extends n.MaskFormerImageProcessor{}},"./src/models/maskformer/image_processing_maskformer.js":(r,e,t)=>{t.r(e),t.d(e,{MaskFormerFeatureExtractor:()=>o,MaskFormerImageProcessor:()=>a});var n=t("./src/base/image_processors_utils.js");class a extends n.ImageProcessor{post_process_panoptic_segmentation(...d){return(0,n.post_process_panoptic_segmentation)(...d)}post_process_instance_segmentation(...d){return(0,n.post_process_instance_segmentation)(...d)}}class o extends a{}},"./src/models/mgp_str/processing_mgp_str.js":(r,e,t)=>{t.r(e),t.d(e,{MgpstrProcessor:()=>c});var n=t("./src/base/processing_utils.js"),a=t("./src/models/auto/image_processing_auto.js"),o=t("./src/tokenizers.js"),u=t("./src/utils/maths.js");const d={char:["char_decode",1],bpe:["bpe_decode",2],wp:["wp_decode",102]};class c extends n.Processor{get char_tokenizer(){return this.components.char_tokenizer}get bpe_tokenizer(){return this.components.bpe_tokenizer}get wp_tokenizer(){return this.components.wp_tokenizer}_decode_helper(_,y){if(!d.hasOwnProperty(y))throw new Error(`Format ${y} is not supported.`);const[w,M]=d[y],S=this[w].bind(this),[G,H]=_.dims,B=[],z=[],U=_.tolist();for(let I=0;I0?j.reduce((ue,Pe)=>ue*Pe,1):0;z.push($),B.push(ce)}return[S(z),B]}char_decode(_){return this.char_tokenizer.batch_decode(_).map(y=>y.replaceAll(" ",""))}bpe_decode(_){return this.bpe_tokenizer.batch_decode(_)}wp_decode(_){return this.wp_tokenizer.batch_decode(_).map(y=>y.replaceAll(" ",""))}batch_decode([_,y,w]){const[M,S]=this._decode_helper(_,"char"),[G,H]=this._decode_helper(y,"bpe"),[B,z]=this._decode_helper(w,"wp"),U=[],F=[];for(let I=0;I{t.r(e),t.d(e,{MobileNetV1FeatureExtractor:()=>o,MobileNetV1ImageProcessor:()=>a});var n=t("./src/base/image_processors_utils.js");class a extends n.ImageProcessor{}class o extends a{}},"./src/models/mobilenet_v2/image_processing_mobilenet_v2.js":(r,e,t)=>{t.r(e),t.d(e,{MobileNetV2FeatureExtractor:()=>o,MobileNetV2ImageProcessor:()=>a});var n=t("./src/base/image_processors_utils.js");class a extends n.ImageProcessor{}class o extends a{}},"./src/models/mobilenet_v3/image_processing_mobilenet_v3.js":(r,e,t)=>{t.r(e),t.d(e,{MobileNetV3FeatureExtractor:()=>o,MobileNetV3ImageProcessor:()=>a});var n=t("./src/base/image_processors_utils.js");class a extends n.ImageProcessor{}class o extends a{}},"./src/models/mobilenet_v4/image_processing_mobilenet_v4.js":(r,e,t)=>{t.r(e),t.d(e,{MobileNetV4FeatureExtractor:()=>o,MobileNetV4ImageProcessor:()=>a});var n=t("./src/base/image_processors_utils.js");class a extends n.ImageProcessor{}class o extends a{}},"./src/models/mobilevit/image_processing_mobilevit.js":(r,e,t)=>{t.r(e),t.d(e,{MobileViTFeatureExtractor:()=>o,MobileViTImageProcessor:()=>a});var n=t("./src/base/image_processors_utils.js");class a extends n.ImageProcessor{}class o extends a{}},"./src/models/moonshine/feature_extraction_moonshine.js":(r,e,t)=>{t.r(e),t.d(e,{MoonshineFeatureExtractor:()=>o});var n=t("./src/base/feature_extraction_utils.js"),a=t("./src/utils/tensor.js");class o extends n.FeatureExtractor{async _call(d){(0,n.validate_audio_inputs)(d,"MoonshineFeatureExtractor"),d instanceof Float64Array&&(d=new Float32Array(d));const c=[1,d.length];return{input_values:new a.Tensor("float32",d,c)}}}},"./src/models/moonshine/processing_moonshine.js":(r,e,t)=>{t.r(e),t.d(e,{MoonshineProcessor:()=>u});var n=t("./src/models/auto/feature_extraction_auto.js"),a=t("./src/tokenizers.js"),o=t("./src/base/processing_utils.js");class u extends o.Processor{async _call(c){return await this.feature_extractor(c)}}we(u,"tokenizer_class",a.AutoTokenizer),we(u,"feature_extractor_class",n.AutoFeatureExtractor)},"./src/models/nougat/image_processing_nougat.js":(r,e,t)=>{t.r(e),t.d(e,{NougatImageProcessor:()=>a});var n=t("./src/models/donut/image_processing_donut.js");class a extends n.DonutImageProcessor{}},"./src/models/owlv2/image_processing_owlv2.js":(r,e,t)=>{t.r(e),t.d(e,{Owlv2ImageProcessor:()=>a});var n=t("./src/models/owlvit/image_processing_owlvit.js");class a extends n.OwlViTImageProcessor{}},"./src/models/owlvit/image_processing_owlvit.js":(r,e,t)=>{t.r(e),t.d(e,{OwlViTFeatureExtractor:()=>o,OwlViTImageProcessor:()=>a});var n=t("./src/base/image_processors_utils.js");class a extends n.ImageProcessor{post_process_object_detection(...d){return(0,n.post_process_object_detection)(...d)}}class o extends a{}},"./src/models/owlvit/processing_owlvit.js":(r,e,t)=>{t.r(e),t.d(e,{OwlViTProcessor:()=>u});var n=t("./src/base/processing_utils.js"),a=t("./src/models/auto/image_processing_auto.js"),o=t("./src/tokenizers.js");class u extends n.Processor{}we(u,"tokenizer_class",o.AutoTokenizer),we(u,"image_processor_class",a.AutoImageProcessor)},"./src/models/paligemma/processing_paligemma.js":(r,e,t)=>{t.r(e),t.d(e,{PaliGemmaProcessor:()=>c});var n=t("./src/base/processing_utils.js"),a=t("./src/models/auto/image_processing_auto.js"),o=t("./src/tokenizers.js");const u="";function d(h,_,y,w,M){return`${w.repeat(y*M)}${_}${h} `}class c extends n.Processor{async _call(_,y=null,w={}){y||(console.warn("You are using PaliGemma without a text prefix. It will perform as a picture-captioning model."),y=""),Array.isArray(_)||(_=[_]),Array.isArray(y)||(y=[y]);const M=this.tokenizer.bos_token,S=this.image_processor.config.image_seq_length;let G;y.some(z=>z.includes(u))?G=y.map(z=>{const U=z.replaceAll(u,u.repeat(S)),F=U.lastIndexOf(u),I=F===-1?0:F+u.length;return U.slice(0,I)+M+U.slice(I)+` `}):(console.warn("You are passing both `text` and `images` to `PaliGemmaProcessor`. The processor expects special image tokens in the text, as many tokens as there are images per each text. It is recommended to add `` tokens in the very beginning of your text. For this call, we will infer how many images each text has and add special tokens."),G=y.map(z=>d(z,M,S,u,_.length)));const H=this.tokenizer(G,w);return{...await this.image_processor(_,w),...H}}}we(c,"tokenizer_class",o.AutoTokenizer),we(c,"image_processor_class",a.AutoImageProcessor),we(c,"uses_processor_config",!1)},"./src/models/phi3_v/image_processing_phi3_v.js":(r,e,t)=>{t.r(e),t.d(e,{Phi3VImageProcessor:()=>_});var n=t("./src/base/image_processors_utils.js"),a=t("./src/utils/tensor.js");const o=336,u=[2,3],{ceil:d,floor:c,sqrt:h}=Math;class _ extends n.ImageProcessor{constructor(w){super({...w,do_normalize:!0,do_pad:!0,pad_size:"custom",do_convert_rgb:!0,do_resize:!0}),this._num_crops=w.num_crops}calc_num_image_tokens_from_image_size(w,M){const{num_img_tokens:S}=this.config;return c((c(M/o)*c(w/o)+1)*S+1+(c(M/o)+1)*h(S))}get_resize_output_image_size(w,M){const S=this._num_crops,[G,H]=w.size;let B=G/H,z=1;for(;z*Math.ceil(z/B)<=S;)z+=1;z-=1;const U=Math.floor(z*336),F=Math.floor(U/B);return[U,F]}pad_image(w,M,S,G={}){const[H,B]=M,z=o*d(H/o),U=o*d(B/o),F=[1,1,1].map((I,k)=>(I-this.image_mean[k])/this.image_std[k]);return super.pad_image(w,M,{width:U,height:z},{center:!0,constant_values:F,...G})}async _call(w,{num_crops:M=null}={}){if(this._num_crops=M??(M=this.config.num_crops),M<4||h(M)%1!==0)throw new Error("num_crops must be a square number >= 4");Array.isArray(w)||(w=[w]);const S=w.length,G=await Promise.all(w.map($=>this.preprocess($))),H=G.map($=>$.original_size),B=G.map($=>$.reshaped_input_size),z=[];for(const{pixel_values:$}of G){$.unsqueeze_(0);const[j,ce]=$.dims.slice(-2),ue=await(0,a.interpolate_4d)($,{size:[o,o],mode:"bicubic"});if(M>0){const Pe=[],Te=h(M),ie=c(ce/Te),oe=c(j/Te);for(let ge=0;ge$.map(j=>o*d(j/o))),I=new a.Tensor("int64",F.flat(),[S,2]),k=F.map(([$,j])=>this.calc_num_image_tokens_from_image_size(j,$));return{pixel_values:U,original_sizes:H,reshaped_input_sizes:B,image_sizes:I,num_img_tokens:k}}}},"./src/models/phi3_v/processing_phi3_v.js":(r,e,t)=>{t.r(e),t.d(e,{Phi3VProcessor:()=>c});var n=t("./src/base/processing_utils.js"),a=t("./src/models/auto/image_processing_auto.js"),o=t("./src/tokenizers.js");t("./src/utils/image.js");const u="<|image|>",d=/<\|image_\d+\|>/g;class c extends n.Processor{async _call(_,y=null,{padding:w=!0,truncation:M=!0,num_crops:S=null}={}){Array.isArray(_)||(_=[_]);let G,H;if(y){H=await this.image_processor(y,{num_crops:S});const{num_img_tokens:B}=H,z=_.map((F,I)=>F.split(d).join(u.repeat(B[I])));G=this.tokenizer(z,{padding:w,truncation:M});const U=this.tokenizer.model.convert_tokens_to_ids([u])[0];G.input_ids.map_(F=>F==U?-F:F)}else G=this.tokenizer(_);return{...G,...H}}}we(c,"image_processor_class",a.AutoImageProcessor),we(c,"tokenizer_class",o.AutoTokenizer)},"./src/models/processors.js":(r,e,t)=>{t.r(e),t.d(e,{Florence2Processor:()=>n.Florence2Processor,GroundingDinoProcessor:()=>a.GroundingDinoProcessor,Idefics3Processor:()=>o.Idefics3Processor,JinaCLIPProcessor:()=>d.JinaCLIPProcessor,MgpstrProcessor:()=>c.MgpstrProcessor,MoonshineProcessor:()=>h.MoonshineProcessor,OwlViTProcessor:()=>_.OwlViTProcessor,PaliGemmaProcessor:()=>w.PaliGemmaProcessor,Phi3VProcessor:()=>y.Phi3VProcessor,PyAnnoteProcessor:()=>M.PyAnnoteProcessor,Qwen2VLProcessor:()=>S.Qwen2VLProcessor,SamProcessor:()=>G.SamProcessor,SpeechT5Processor:()=>H.SpeechT5Processor,VLChatProcessor:()=>u.VLChatProcessor,Wav2Vec2ProcessorWithLM:()=>B.Wav2Vec2ProcessorWithLM,WhisperProcessor:()=>z.WhisperProcessor});var n=t("./src/models/florence2/processing_florence2.js"),a=t("./src/models/grounding_dino/processing_grounding_dino.js"),o=t("./src/models/idefics3/processing_idefics3.js"),u=t("./src/models/janus/processing_janus.js"),d=t("./src/models/jina_clip/processing_jina_clip.js"),c=t("./src/models/mgp_str/processing_mgp_str.js"),h=t("./src/models/moonshine/processing_moonshine.js"),_=t("./src/models/owlvit/processing_owlvit.js"),y=t("./src/models/phi3_v/processing_phi3_v.js"),w=t("./src/models/paligemma/processing_paligemma.js"),M=t("./src/models/pyannote/processing_pyannote.js"),S=t("./src/models/qwen2_vl/processing_qwen2_vl.js"),G=t("./src/models/sam/processing_sam.js"),H=t("./src/models/speecht5/processing_speecht5.js"),B=t("./src/models/wav2vec2/processing_wav2vec2.js"),z=t("./src/models/whisper/processing_whisper.js")},"./src/models/pvt/image_processing_pvt.js":(r,e,t)=>{t.r(e),t.d(e,{PvtImageProcessor:()=>a});var n=t("./src/base/image_processors_utils.js");class a extends n.ImageProcessor{}},"./src/models/pyannote/feature_extraction_pyannote.js":(r,e,t)=>{t.r(e),t.d(e,{PyAnnoteFeatureExtractor:()=>u});var n=t("./src/base/feature_extraction_utils.js"),a=t("./src/utils/tensor.js"),o=t("./src/utils/maths.js");class u extends n.FeatureExtractor{async _call(c){(0,n.validate_audio_inputs)(c,"PyAnnoteFeatureExtractor"),c instanceof Float64Array&&(c=new Float32Array(c));const h=[1,1,c.length];return{input_values:new a.Tensor("float32",c,h)}}samples_to_frames(c){return(c-this.config.offset)/this.config.step}post_process_speaker_diarization(c,h){const _=h/this.samples_to_frames(h)/this.config.sampling_rate,y=[];for(const w of c.tolist()){const M=[];let S=-1;for(let G=0;G({id:G,start:H*_,end:B*_,confidence:z/(B-H)})))}return y}}},"./src/models/pyannote/processing_pyannote.js":(r,e,t)=>{t.r(e),t.d(e,{PyAnnoteProcessor:()=>o});var n=t("./src/base/processing_utils.js"),a=t("./src/models/pyannote/feature_extraction_pyannote.js");class o extends n.Processor{async _call(d){return await this.feature_extractor(d)}post_process_speaker_diarization(...d){return this.feature_extractor.post_process_speaker_diarization(...d)}get sampling_rate(){return this.feature_extractor.config.sampling_rate}}we(o,"feature_extractor_class",a.PyAnnoteFeatureExtractor)},"./src/models/qwen2_vl/image_processing_qwen2_vl.js":(r,e,t)=>{t.r(e),t.d(e,{Qwen2VLImageProcessor:()=>o});var n=t("./src/base/image_processors_utils.js"),a=t("./src/utils/tensor.js");class o extends n.ImageProcessor{async _call(d,...c){const{pixel_values:h,original_sizes:_,reshaped_input_sizes:y}=await super._call(d,...c);let w=h;const{temporal_patch_size:M,merge_size:S,patch_size:G}=this.config;w.dims[0]===1&&(w=(0,a.cat)(Array.from({length:M},()=>w),0));const H=w.dims[0]/M,B=w.dims[1],z=Math.floor(w.dims[2]/G),U=Math.floor(w.dims[3]/G),F=w.view(H,M,B,Math.floor(z/S),S,G,Math.floor(U/S),S,G).permute(0,3,6,4,7,2,1,5,8).view(H*z*U,B*M*G*G),I=new a.Tensor("int64",[H,z,U],[1,3]);return{pixel_values:F,image_grid_thw:I,original_sizes:_,reshaped_input_sizes:y}}}},"./src/models/qwen2_vl/processing_qwen2_vl.js":(r,e,t)=>{t.r(e),t.d(e,{Qwen2VLProcessor:()=>u});var n=t("./src/base/processing_utils.js"),a=t("./src/models/auto/image_processing_auto.js"),o=t("./src/tokenizers.js");t("./src/utils/image.js");class u extends n.Processor{async _call(c,h=null,..._){Array.isArray(c)||(c=[c]);let y,w;if(h&&(y=await this.image_processor(h),w=y.image_grid_thw),w){let S=this.image_processor.config.merge_size**2,G=0;const H=w.tolist();c=c.map(B=>{for(;B.includes("<|image_pad|>");){const z=Number(H[G++].reduce((U,F)=>U*F,1n));B=B.replace("<|image_pad|>","<|placeholder|>".repeat(Math.floor(z/S)))}return B.replaceAll("<|placeholder|>","<|image_pad|>")})}return{...this.tokenizer(c),...y}}}we(u,"image_processor_class",a.AutoImageProcessor),we(u,"tokenizer_class",o.AutoTokenizer)},"./src/models/rt_detr/image_processing_rt_detr.js":(r,e,t)=>{t.r(e),t.d(e,{RTDetrImageProcessor:()=>a});var n=t("./src/base/image_processors_utils.js");class a extends n.ImageProcessor{post_process_object_detection(...u){return(0,n.post_process_object_detection)(...u)}}},"./src/models/sam/image_processing_sam.js":(r,e,t)=>{t.r(e),t.d(e,{SamImageProcessor:()=>u});var n=t("./src/base/image_processors_utils.js"),a=t("./src/utils/core.js"),o=t("./src/utils/tensor.js");class u extends n.ImageProcessor{reshape_input_points(c,h,_,y=!1){c=structuredClone(c);let w=(0,a.calculateDimensions)(c);if(w.length===3)y||(w=[1,...w]),c=[c];else if(w.length!==4)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");for(let M=0;My!==h.dims[w]))throw Error(`The first ${_.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new o.Tensor("int64",c.flat(1/0).map(BigInt),_)}async _call(c,{input_points:h=null,input_labels:_=null,input_boxes:y=null}={}){const w=await super._call(c);if(h&&(w.input_points=this.reshape_input_points(h,w.original_sizes,w.reshaped_input_sizes)),_){if(!w.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");w.input_labels=this.add_input_labels(_,w.input_points)}return y&&(w.input_boxes=this.reshape_input_points(y,w.original_sizes,w.reshaped_input_sizes,!0)),w}async post_process_masks(c,h,_,{mask_threshold:y=0,binarize:w=!0,pad_size:M=null}={}){const S=[];M=M??this.pad_size;const G=[M.height,M.width];for(let H=0;Hy&&(I[k]=1);U=new o.Tensor("bool",I,U.dims)}S.push(U)}return S}generate_crop_boxes(c,h,{crop_n_layers:_=0,overlap_ratio:y=512/1500,points_per_crop:w=32,crop_n_points_downscale_factor:M=1}={}){}}},"./src/models/sam/processing_sam.js":(r,e,t)=>{t.r(e),t.d(e,{SamProcessor:()=>o});var n=t("./src/base/processing_utils.js"),a=t("./src/models/auto/image_processing_auto.js");class o extends n.Processor{async _call(...d){return await this.image_processor(...d)}post_process_masks(...d){return this.image_processor.post_process_masks(...d)}reshape_input_points(...d){return this.image_processor.reshape_input_points(...d)}}we(o,"image_processor_class",a.AutoImageProcessor)},"./src/models/seamless_m4t/feature_extraction_seamless_m4t.js":(r,e,t)=>{t.r(e),t.d(e,{SeamlessM4TFeatureExtractor:()=>u});var n=t("./src/base/feature_extraction_utils.js"),a=t("./src/utils/tensor.js"),o=t("./src/utils/audio.js");class u extends n.FeatureExtractor{constructor(c){super(c);const h=this.config.sampling_rate,_=(0,o.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(h/2),h,null,"kaldi",!0);for(let y=0;y<_.length;++y)_[y].push(0);this.mel_filters=_,this.window=(0,o.window_function)(400,"povey",{periodic:!1})}async _extract_fbank_features(c,h){return c=c.map(_=>_*32768),(0,o.spectrogram)(c,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:h,transpose:!0})}async _call(c,{padding:h=!0,pad_to_multiple_of:_=2,do_normalize_per_mel_bins:y=!0,return_attention_mask:w=!0}={}){(0,n.validate_audio_inputs)(c,"SeamlessM4TFeatureExtractor");let M=await this._extract_fbank_features(c,this.config.max_length);if(y){const[I,k]=M.dims,$=M.data;for(let j=0;j0){const ce=new Float32Array(k*(I+j));ce.set($),ce.fill(this.config.padding_value,$.length);const ue=I+j;M=new a.Tensor(M.type,ce,[ue,k]),w&&(S=new a.Tensor("int64",new BigInt64Array(ue),[1,ue]),S.data.fill(1n,0,I))}}const[G,H]=M.dims,B=this.config.stride;if(G%B!==0)throw new Error(`The number of frames (${G}) must be a multiple of the stride (${B}).`);const U=M.view(1,Math.floor(G/B),H*B),F={input_features:U};if(w){const I=U.dims[1],k=new BigInt64Array(I);if(S){const $=S.data;for(let j=1,ce=0;j{t.r(e),t.d(e,{SegformerFeatureExtractor:()=>o,SegformerImageProcessor:()=>a});var n=t("./src/base/image_processors_utils.js");class a extends n.ImageProcessor{post_process_semantic_segmentation(...d){return(0,n.post_process_semantic_segmentation)(...d)}}class o extends a{}},"./src/models/siglip/image_processing_siglip.js":(r,e,t)=>{t.r(e),t.d(e,{SiglipImageProcessor:()=>a});var n=t("./src/base/image_processors_utils.js");class a extends n.ImageProcessor{}},"./src/models/speecht5/feature_extraction_speecht5.js":(r,e,t)=>{t.r(e),t.d(e,{SpeechT5FeatureExtractor:()=>a});var n=t("./src/base/feature_extraction_utils.js");class a extends n.FeatureExtractor{}},"./src/models/speecht5/processing_speecht5.js":(r,e,t)=>{t.r(e),t.d(e,{SpeechT5Processor:()=>u});var n=t("./src/base/processing_utils.js"),a=t("./src/tokenizers.js"),o=t("./src/models/auto/feature_extraction_auto.js");class u extends n.Processor{async _call(c){return await this.feature_extractor(c)}}we(u,"tokenizer_class",a.AutoTokenizer),we(u,"feature_extractor_class",o.AutoFeatureExtractor)},"./src/models/swin2sr/image_processing_swin2sr.js":(r,e,t)=>{t.r(e),t.d(e,{Swin2SRImageProcessor:()=>a});var n=t("./src/base/image_processors_utils.js");class a extends n.ImageProcessor{pad_image(u,d,c,h={}){const[_,y,w]=d;return super.pad_image(u,d,{width:y+(c-y%c)%c,height:_+(c-_%c)%c},{mode:"symmetric",center:!1,constant_values:-1,...h})}}},"./src/models/vit/image_processing_vit.js":(r,e,t)=>{t.r(e),t.d(e,{ViTFeatureExtractor:()=>o,ViTImageProcessor:()=>a});var n=t("./src/base/image_processors_utils.js");class a extends n.ImageProcessor{}class o extends a{}},"./src/models/vitmatte/image_processing_vitmatte.js":(r,e,t)=>{t.r(e),t.d(e,{VitMatteImageProcessor:()=>o});var n=t("./src/base/image_processors_utils.js"),a=t("./src/utils/tensor.js");class o extends n.ImageProcessor{async _call(d,c){Array.isArray(d)||(d=[d]),Array.isArray(c)||(c=[c]);const h=await Promise.all(d.map(w=>this.preprocess(w))),_=await Promise.all(c.map(w=>this.preprocess(w,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:(0,a.stack)(h.map((w,M)=>(0,a.cat)([w.pixel_values,_[M].pixel_values],0)),0),original_sizes:h.map(w=>w.original_size),reshaped_input_sizes:h.map(w=>w.reshaped_input_size)}}}},"./src/models/vitpose/image_processing_vitpose.js":(r,e,t)=>{t.r(e),t.d(e,{VitPoseImageProcessor:()=>a});var n=t("./src/base/image_processors_utils.js");class a extends n.ImageProcessor{post_process_pose_estimation(u,d,{threshold:c=null}={}){const h=u.tolist(),[_,y,w,M]=u.dims,S=[];for(let G=0;G<_;++G){const H=h[G],B=d[G],z=[];for(let U=0;U{t.r(e),t.d(e,{Wav2Vec2FeatureExtractor:()=>o});var n=t("./src/base/feature_extraction_utils.js"),a=t("./src/utils/tensor.js");class o extends n.FeatureExtractor{_zero_mean_unit_var_norm(d){const h=d.reduce((y,w)=>y+w,0)/d.length,_=d.reduce((y,w)=>y+(w-h)**2,0)/d.length;return d.map(y=>(y-h)/Math.sqrt(_+1e-7))}async _call(d){(0,n.validate_audio_inputs)(d,"Wav2Vec2FeatureExtractor"),d instanceof Float64Array&&(d=new Float32Array(d));let c=d;this.config.do_normalize&&(c=this._zero_mean_unit_var_norm(c));const h=[1,c.length];return{input_values:new a.Tensor("float32",c,h),attention_mask:new a.Tensor("int64",new BigInt64Array(c.length).fill(1n),h)}}}},"./src/models/wav2vec2/processing_wav2vec2.js":(r,e,t)=>{t.r(e),t.d(e,{Wav2Vec2ProcessorWithLM:()=>o});var n=t("./src/base/processing_utils.js"),a=t("./src/models/auto/feature_extraction_auto.js");class o extends n.Processor{async _call(d){return await this.feature_extractor(d)}}we(o,"feature_extractor_class",a.AutoFeatureExtractor)},"./src/models/wespeaker/feature_extraction_wespeaker.js":(r,e,t)=>{t.r(e),t.d(e,{WeSpeakerFeatureExtractor:()=>o});var n=t("./src/base/feature_extraction_utils.js");t("./src/utils/tensor.js");var a=t("./src/utils/audio.js");class o extends n.FeatureExtractor{constructor(d){super(d);const c=this.config.sampling_rate,h=(0,a.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(c/2),c,null,"kaldi",!0);for(let _=0;_c*32768),(0,a.spectrogram)(d,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,transpose:!0,min_num_frames:this.min_num_frames})}async _call(d){(0,n.validate_audio_inputs)(d,"WeSpeakerFeatureExtractor");const c=(await this._extract_fbank_features(d)).unsqueeze_(0);if(this.config.fbank_centering_span===null){const h=c.mean(1).data,_=c.data,[y,w,M]=c.dims;for(let S=0;S{t.r(e),t.d(e,{WHISPER_LANGUAGE_MAPPING:()=>a,WHISPER_TO_LANGUAGE_CODE_MAPPING:()=>o,whisper_language_to_code:()=>u});const n=[["en","english"],["zh","chinese"],["de","german"],["es","spanish"],["ru","russian"],["ko","korean"],["fr","french"],["ja","japanese"],["pt","portuguese"],["tr","turkish"],["pl","polish"],["ca","catalan"],["nl","dutch"],["ar","arabic"],["sv","swedish"],["it","italian"],["id","indonesian"],["hi","hindi"],["fi","finnish"],["vi","vietnamese"],["he","hebrew"],["uk","ukrainian"],["el","greek"],["ms","malay"],["cs","czech"],["ro","romanian"],["da","danish"],["hu","hungarian"],["ta","tamil"],["no","norwegian"],["th","thai"],["ur","urdu"],["hr","croatian"],["bg","bulgarian"],["lt","lithuanian"],["la","latin"],["mi","maori"],["ml","malayalam"],["cy","welsh"],["sk","slovak"],["te","telugu"],["fa","persian"],["lv","latvian"],["bn","bengali"],["sr","serbian"],["az","azerbaijani"],["sl","slovenian"],["kn","kannada"],["et","estonian"],["mk","macedonian"],["br","breton"],["eu","basque"],["is","icelandic"],["hy","armenian"],["ne","nepali"],["mn","mongolian"],["bs","bosnian"],["kk","kazakh"],["sq","albanian"],["sw","swahili"],["gl","galician"],["mr","marathi"],["pa","punjabi"],["si","sinhala"],["km","khmer"],["sn","shona"],["yo","yoruba"],["so","somali"],["af","afrikaans"],["oc","occitan"],["ka","georgian"],["be","belarusian"],["tg","tajik"],["sd","sindhi"],["gu","gujarati"],["am","amharic"],["yi","yiddish"],["lo","lao"],["uz","uzbek"],["fo","faroese"],["ht","haitian creole"],["ps","pashto"],["tk","turkmen"],["nn","nynorsk"],["mt","maltese"],["sa","sanskrit"],["lb","luxembourgish"],["my","myanmar"],["bo","tibetan"],["tl","tagalog"],["mg","malagasy"],["as","assamese"],["tt","tatar"],["haw","hawaiian"],["ln","lingala"],["ha","hausa"],["ba","bashkir"],["jw","javanese"],["su","sundanese"]],a=new Map(n),o=new Map([...n.map(([d,c])=>[c,d]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function u(d){d=d.toLowerCase();let c=o.get(d);if(c===void 0)if(a.has(d))c=d;else{const _=d.length===2?a.keys():a.values();throw new Error(`Language "${d}" is not supported. Must be one of: ${JSON.stringify(_)}`)}return c}},"./src/models/whisper/feature_extraction_whisper.js":(r,e,t)=>{t.r(e),t.d(e,{WhisperFeatureExtractor:()=>u});var n=t("./src/base/feature_extraction_utils.js");t("./src/utils/tensor.js");var a=t("./src/utils/audio.js"),o=t("./src/utils/maths.js");class u extends n.FeatureExtractor{constructor(c){var h;super(c),(h=this.config).mel_filters??(h.mel_filters=(0,a.mel_filter_bank)(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney")),this.window=(0,a.window_function)(this.config.n_fft,"hann")}async _extract_fbank_features(c){const h=await(0,a.spectrogram)(c,this.window,this.config.n_fft,this.config.hop_length,{power:2,mel_filters:this.config.mel_filters,log_mel:"log10",max_num_frames:this.config.nb_max_frames}),_=h.data,y=(0,o.max)(_)[0];for(let w=0;w<_.length;++w)_[w]=(Math.max(_[w],y-8)+4)/4;return h}async _call(c){(0,n.validate_audio_inputs)(c,"WhisperFeatureExtractor");let h;return c.length>this.config.n_samples?(console.warn("Attempting to extract features for audio longer than 30 seconds. If using a pipeline to extract transcript from a long audio clip, remember to specify `chunk_length_s` and/or `stride_length_s`."),h=c.slice(0,this.config.n_samples)):(h=new Float32Array(this.config.n_samples),h.set(c)),{input_features:(await this._extract_fbank_features(h)).unsqueeze_(0)}}}},"./src/models/whisper/generation_whisper.js":(r,e,t)=>{t.r(e),t.d(e,{WhisperGenerationConfig:()=>a});var n=t("./src/generation/configuration_utils.js");class a extends n.GenerationConfig{constructor(){super(...arguments);we(this,"return_timestamps",null);we(this,"return_token_timestamps",null);we(this,"num_frames",null);we(this,"alignment_heads",null);we(this,"task",null);we(this,"language",null);we(this,"no_timestamps_token_id",null);we(this,"prompt_ids",null);we(this,"is_multilingual",null);we(this,"lang_to_id",null);we(this,"task_to_id",null);we(this,"max_initial_timestamp_index",1)}}},"./src/models/whisper/processing_whisper.js":(r,e,t)=>{t.r(e),t.d(e,{WhisperProcessor:()=>u});var n=t("./src/models/auto/feature_extraction_auto.js"),a=t("./src/tokenizers.js"),o=t("./src/base/processing_utils.js");class u extends o.Processor{async _call(c){return await this.feature_extractor(c)}}we(u,"tokenizer_class",a.AutoTokenizer),we(u,"feature_extractor_class",n.AutoFeatureExtractor)},"./src/models/yolos/image_processing_yolos.js":(r,e,t)=>{t.r(e),t.d(e,{YolosFeatureExtractor:()=>o,YolosImageProcessor:()=>a});var n=t("./src/base/image_processors_utils.js");class a extends n.ImageProcessor{post_process_object_detection(...d){return(0,n.post_process_object_detection)(...d)}}class o extends a{}},"./src/ops/registry.js":(r,e,t)=>{t.r(e),t.d(e,{TensorOpRegistry:()=>u});var n=t("./src/backends/onnx.js"),a=t("./src/utils/tensor.js");const o=async(d,c,h)=>{const _=await(0,n.createInferenceSession)(new Uint8Array(d),c);return async y=>{const w=(0,n.isONNXProxy)(),M=Object.fromEntries(Object.entries(y).map(([G,H])=>[G,(w?H.clone():H).ort_tensor])),S=await _.run(M);return Array.isArray(h)?h.map(G=>new a.Tensor(S[G])):new a.Tensor(S[h])}};class u{static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=o([8,10,18,0,58,129,1,10,41,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,18,10,4,109,111,100,101,34,7,110,101,97,114,101,115,116,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,21],this.session_options,"y")),this._nearest_interpolate_4d}static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=o([8,9,18,0,58,128,1,10,40,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,17,10,4,109,111,100,101,34,6,108,105,110,101,97,114,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bilinear_interpolate_4d}static get bicubic_interpolate_4d(){return this._bicubic_interpolate_4d||(this._bicubic_interpolate_4d=o([8,9,18,0,58,127,10,39,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,16,10,4,109,111,100,101,34,5,99,117,98,105,99,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bicubic_interpolate_4d}static get matmul(){return this._matmul||(this._matmul=o([8,9,18,0,58,55,10,17,10,1,97,10,1,98,18,1,99,34,6,77,97,116,77,117,108,18,1,114,90,9,10,1,97,18,4,10,2,8,1,90,9,10,1,98,18,4,10,2,8,1,98,9,10,1,99,18,4,10,2,8,1,66,2,16,20],this.session_options,"c")),this._matmul}static get stft(){return this._stft||(this._stft=o([8,7,18,0,58,148,1,10,38,10,1,115,10,1,106,10,1,119,10,1,108,18,1,111,34,4,83,84,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,115,90,26,10,1,115,18,21,10,19,8,1,18,15,10,3,18,1,98,10,3,18,1,115,10,3,18,1,99,90,11,10,1,106,18,6,10,4,8,7,18,0,90,16,10,1,119,18,11,10,9,8,1,18,5,10,3,18,1,119,90,11,10,1,108,18,6,10,4,8,7,18,0,98,31,10,1,111,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,102,10,3,18,1,100,10,3,18,1,99,66,2,16,17],this.session_options,"o")),this._stft}static get rfft(){return this._rfft||(this._rfft=o([8,9,18,0,58,97,10,33,10,1,120,10,0,10,1,97,18,1,121,34,3,68,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,100,90,21,10,1,120,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,90,11,10,1,97,18,6,10,4,8,7,18,0,98,21,10,1,121,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,66,2,16,20],this.session_options,"y")),this._rfft}static get top_k(){return this._top_k||(this._top_k=o([8,10,18,0,58,73,10,18,10,1,120,10,1,107,18,1,118,18,1,105,34,4,84,111,112,75,18,1,116,90,9,10,1,120,18,4,10,2,8,1,90,15,10,1,107,18,10,10,8,8,7,18,4,10,2,8,1,98,9,10,1,118,18,4,10,2,8,1,98,9,10,1,105,18,4,10,2,8,7,66,2,16,21],this.session_options,["v","i"])),this._top_k}static get slice(){return this._slice||(this._slice=o([8,7,18,0,58,96,10,25,10,1,120,10,1,115,10,1,101,10,1,97,10,1,116,18,1,121,34,5,83,108,105,99,101,18,1,114,90,9,10,1,120,18,4,10,2,8,1,90,9,10,1,115,18,4,10,2,8,7,90,9,10,1,101,18,4,10,2,8,7,90,9,10,1,97,18,4,10,2,8,7,90,9,10,1,116,18,4,10,2,8,7,98,9,10,1,121,18,4,10,2,8,1,66,2,16,13],this.session_options,"y")),this._slice}}we(u,"session_options",{})},"./src/pipelines.js":(r,e,t)=>{t.r(e),t.d(e,{AudioClassificationPipeline:()=>Te,AutomaticSpeechRecognitionPipeline:()=>oe,DepthEstimationPipeline:()=>ke,DocumentQuestionAnsweringPipeline:()=>pe,FeatureExtractionPipeline:()=>ue,FillMaskPipeline:()=>U,ImageClassificationPipeline:()=>ge,ImageFeatureExtractionPipeline:()=>Pe,ImageSegmentationPipeline:()=>ve,ImageToImagePipeline:()=>le,ImageToTextPipeline:()=>re,ObjectDetectionPipeline:()=>Le,Pipeline:()=>G,QuestionAnsweringPipeline:()=>z,SummarizationPipeline:()=>I,Text2TextGenerationPipeline:()=>F,TextClassificationPipeline:()=>H,TextGenerationPipeline:()=>j,TextToAudioPipeline:()=>X,TokenClassificationPipeline:()=>B,TranslationPipeline:()=>k,ZeroShotAudioClassificationPipeline:()=>ie,ZeroShotClassificationPipeline:()=>ce,ZeroShotImageClassificationPipeline:()=>me,ZeroShotObjectDetectionPipeline:()=>$e,pipeline:()=>ae});var n=t("./src/tokenizers.js"),a=t("./src/models.js"),o=t("./src/models/auto/processing_auto.js");t("./src/base/processing_utils.js");var u=t("./src/utils/generic.js"),d=t("./src/utils/core.js"),c=t("./src/utils/maths.js"),h=t("./src/utils/audio.js"),_=t("./src/utils/tensor.js"),y=t("./src/utils/image.js");async function w(Ve){return Array.isArray(Ve)||(Ve=[Ve]),await Promise.all(Ve.map(he=>y.RawImage.read(he)))}async function M(Ve,he){return Array.isArray(Ve)||(Ve=[Ve]),await Promise.all(Ve.map(Se=>typeof Se=="string"||Se instanceof URL?(0,h.read_audio)(Se,he):Se instanceof Float64Array?new Float32Array(Se):Se))}function S(Ve,he){he&&(Ve=Ve.map(We=>We|0));const[Se,Ke,qe,Ge]=Ve;return{xmin:Se,ymin:Ke,xmax:qe,ymax:Ge}}class G extends u.Callable{constructor({task:he,model:Se,tokenizer:Ke=null,processor:qe=null}){super(),this.task=he,this.model=Se,this.tokenizer=Ke,this.processor=qe}async dispose(){await this.model.dispose()}}class H extends G{constructor(he){super(he)}async _call(he,{top_k:Se=1}={}){const Ke=this.tokenizer(he,{padding:!0,truncation:!0}),qe=await this.model(Ke),Ge=this.model.config.problem_type==="multi_label_classification"?ht=>ht.sigmoid():ht=>new _.Tensor("float32",(0,c.softmax)(ht.data),ht.dims),We=this.model.config.id2label,st=[];for(const ht of qe.logits){const mt=Ge(ht),ct=await(0,_.topk)(mt,Se),gt=ct[0].tolist(),de=ct[1].tolist().map((J,Ee)=>({label:We?We[J]:`LABEL_${J}`,score:gt[Ee]}));Se===1?st.push(...de):st.push(de)}return Array.isArray(he)||Se===1?st:st[0]}}class B extends G{constructor(he){super(he)}async _call(he,{ignore_labels:Se=["O"]}={}){const Ke=Array.isArray(he),qe=this.tokenizer(Ke?he:[he],{padding:!0,truncation:!0}),We=(await this.model(qe)).logits,st=this.model.config.id2label,ht=[];for(let mt=0;mtdt==this.tokenizer.sep_token_id);ht[gt].map((dt,bt)=>dt==1&&(bt===0||bt>de&&mt.findIndex(Ct=>Ct==W[bt])===-1));const J=Ge[gt].tolist(),Ee=We[gt].tolist();for(let dt=1;dtbt==W[dt])!==-1)&&(J[dt]=-1/0,Ee[dt]=-1/0);const Fe=(0,c.softmax)(J).map((dt,bt)=>[dt,bt]),Ze=(0,c.softmax)(Ee).map((dt,bt)=>[dt,bt]);Fe[0][0]=0,Ze[0][0]=0;const rt=(0,d.product)(Fe,Ze).filter(dt=>dt[0][1]<=dt[1][1]).map(dt=>[dt[0][1],dt[1][1],dt[0][0]*dt[1][0]]).sort((dt,bt)=>bt[2]-dt[2]);for(let dt=0;dtJ==this.tokenizer.mask_token_id);if(mt===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const ct=qe[st][mt],gt=await(0,_.topk)(new _.Tensor("float32",(0,c.softmax)(ct.data),ct.dims),Se),W=gt[0].tolist(),de=gt[1].tolist();Ge.push(de.map((J,Ee)=>{const Fe=ht.slice();return Fe[mt]=J,{score:W[Ee],token:Number(J),token_str:this.tokenizer.decode([J]),sequence:this.tokenizer.decode(Fe,{skip_special_tokens:!0})}}))}return Array.isArray(he)?Ge:Ge[0]}}class F extends G{constructor(Se){super(Se);we(this,"_key","generated_text")}async _call(Se,Ke={}){Array.isArray(Se)||(Se=[Se]),this.model.config.prefix&&(Se=Se.map(mt=>this.model.config.prefix+mt));const qe=this.model.config.task_specific_params;qe&&qe[this.task]&&qe[this.task].prefix&&(Se=Se.map(mt=>qe[this.task].prefix+mt));const Ge=this.tokenizer,We={padding:!0,truncation:!0};let st;this instanceof k&&"_build_translation_inputs"in Ge?st=Ge._build_translation_inputs(Se,We,Ke):st=Ge(Se,We);const ht=await this.model.generate({...st,...Ke});return Ge.batch_decode(ht,{skip_special_tokens:!0}).map(mt=>({[this._key]:mt}))}}class I extends F{constructor(Se){super(Se);we(this,"_key","summary_text")}}class k extends F{constructor(Se){super(Se);we(this,"_key","translation_text")}}function $(Ve){return Array.isArray(Ve)&&Ve.every(he=>"role"in he&&"content"in he)}class j extends G{constructor(he){super(he)}async _call(he,Se={}){let Ke=!1,qe=!1,Ge;if(typeof he=="string")Ge=he=[he];else if(Array.isArray(he)&&he.every(de=>typeof de=="string"))Ke=!0,Ge=he;else{if($(he))he=[he];else if(Array.isArray(he)&&he.every($))Ke=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");qe=!0,Ge=he.map(de=>this.tokenizer.apply_chat_template(de,{tokenize:!1,add_generation_prompt:!0}))}const We=Se.add_special_tokens??!1,st=qe?!1:Se.return_full_text??!0;this.tokenizer.padding_side="left";const ht=this.tokenizer(Ge,{add_special_tokens:We,padding:!0,truncation:!0}),mt=await this.model.generate({...ht,...Se}),ct=this.tokenizer.batch_decode(mt,{skip_special_tokens:!0});let gt;!st&&ht.input_ids.dims.at(-1)>0&&(gt=this.tokenizer.batch_decode(ht.input_ids,{skip_special_tokens:!0}).map(de=>de.length));const W=Array.from({length:he.length},de=>[]);for(let de=0;de[Se.toLowerCase(),Ke])),this.entailment_id=this.label2id.entailment,this.entailment_id===void 0&&(console.warn("Could not find 'entailment' in label2id mapping. Using 2 as entailment_id."),this.entailment_id=2),this.contradiction_id=this.label2id.contradiction??this.label2id.not_entailment,this.contradiction_id===void 0&&(console.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0)}async _call(he,Se,{hypothesis_template:Ke="This example is {}.",multi_label:qe=!1}={}){const Ge=Array.isArray(he);Ge||(he=[he]),Array.isArray(Se)||(Se=[Se]);const We=Se.map(mt=>Ke.replace("{}",mt)),st=qe||Se.length===1,ht=[];for(const mt of he){const ct=[];for(const de of We){const J=this.tokenizer(mt,{text_pair:de,padding:!0,truncation:!0}),Ee=await this.model(J);st?ct.push([Ee.logits.data[this.contradiction_id],Ee.logits.data[this.entailment_id]]):ct.push(Ee.logits.data[this.entailment_id])}const W=(st?ct.map(de=>(0,c.softmax)(de)[1]):(0,c.softmax)(ct)).map((de,J)=>[de,J]).sort((de,J)=>J[0]-de[0]);ht.push({sequence:mt,labels:W.map(de=>Se[de[1]]),scores:W.map(de=>de[0])})}return Ge?ht:ht[0]}}class ue extends G{constructor(he){super(he)}async _call(he,{pooling:Se="none",normalize:Ke=!1,quantize:qe=!1,precision:Ge="binary"}={}){const We=this.tokenizer(he,{padding:!0,truncation:!0}),st=await this.model(We);let ht=st.last_hidden_state??st.logits??st.token_embeddings;if(Se!=="none")if(Se==="mean")ht=(0,_.mean_pooling)(ht,We.attention_mask);else if(Se==="cls")ht=ht.slice(null,0);else throw Error(`Pooling method '${Se}' not supported.`);return Ke&&(ht=ht.normalize(2,-1)),qe&&(ht=(0,_.quantize_embeddings)(ht,Ge)),ht}}class Pe extends G{constructor(he){super(he)}async _call(he,{pool:Se=null}={}){const Ke=await w(he),{pixel_values:qe}=await this.processor(Ke),Ge=await this.model({pixel_values:qe});let We;if(Se){if(!("pooler_output"in Ge))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");We=Ge.pooler_output}else We=Ge.last_hidden_state??Ge.logits??Ge.image_embeds;return We}}class Te extends G{constructor(he){super(he)}async _call(he,{top_k:Se=5}={}){const Ke=this.processor.feature_extractor.config.sampling_rate,qe=await M(he,Ke),Ge=this.model.config.id2label,We=[];for(const st of qe){const ht=await this.processor(st),ct=(await this.model(ht)).logits[0],gt=await(0,_.topk)(new _.Tensor("float32",(0,c.softmax)(ct.data),ct.dims),Se),W=gt[0].tolist(),J=gt[1].tolist().map((Ee,Fe)=>({label:Ge?Ge[Ee]:`LABEL_${Ee}`,score:W[Fe]}));We.push(J)}return Array.isArray(he)?We:We[0]}}class ie extends G{constructor(he){super(he)}async _call(he,Se,{hypothesis_template:Ke="This is a sound of {}."}={}){const qe=!Array.isArray(he);qe&&(he=[he]);const Ge=Se.map(ct=>Ke.replace("{}",ct)),We=this.tokenizer(Ge,{padding:!0,truncation:!0}),st=this.processor.feature_extractor.config.sampling_rate,ht=await M(he,st),mt=[];for(const ct of ht){const gt=await this.processor(ct),W=await this.model({...We,...gt}),de=(0,c.softmax)(W.logits_per_audio.data);mt.push([...de].map((J,Ee)=>({score:J,label:Se[Ee]})))}return qe?mt[0]:mt}}class oe extends G{constructor(he){super(he)}async _call(he,Se={}){switch(this.model.config.model_type){case"whisper":return this._call_whisper(he,Se);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(he,Se);case"moonshine":return this._call_moonshine(he,Se);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(he,Se){Se.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),Se.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const Ke=!Array.isArray(he);Ke&&(he=[he]);const qe=this.processor.feature_extractor.config.sampling_rate,Ge=await M(he,qe),We=[];for(const st of Ge){const ht=await this.processor(st),ct=(await this.model(ht)).logits[0],gt=[];for(const de of ct)gt.push((0,c.max)(de.data)[1]);const W=this.tokenizer.decode(gt);We.push({text:W})}return Ke?We[0]:We}async _call_whisper(he,Se){const Ke=Se.return_timestamps??!1,qe=Se.chunk_length_s??0,Ge=Se.force_full_sequences??!1;let We=Se.stride_length_s??null;const st={...Se};Ke==="word"&&(st.return_token_timestamps=!0,st.return_timestamps=!1);const ht=!Array.isArray(he);ht&&(he=[he]);const mt=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,ct=this.processor.feature_extractor.config.hop_length,gt=this.processor.feature_extractor.config.sampling_rate,W=await M(he,gt),de=[];for(const J of W){let Ee=[];if(qe>0){if(We===null)We=qe/6;else if(qe<=We)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const rt=gt*qe,dt=gt*We,bt=rt-2*dt;let Ct=0;for(;;){const Lt=Ct+rt,Nt=J.subarray(Ct,Lt),br=await this.processor(Nt),Rr=Ct===0,Yr=Lt>=J.length;if(Ee.push({stride:[Nt.length,Rr?0:dt,Yr?0:dt],input_features:br.input_features,is_last:Yr}),Yr)break;Ct+=bt}}else Ee=[{stride:[J.length,0,0],input_features:(await this.processor(J)).input_features,is_last:!0}];for(const rt of Ee){st.num_frames=Math.floor(rt.stride[0]/ct);const dt=await this.model.generate({inputs:rt.input_features,...st});Ke==="word"?(rt.tokens=dt.sequences.tolist()[0],rt.token_timestamps=dt.token_timestamps.tolist()[0].map(bt=>(0,c.round)(bt,2))):rt.tokens=dt[0].tolist(),rt.stride=rt.stride.map(bt=>bt/gt)}const[Fe,Ze]=this.tokenizer._decode_asr(Ee,{time_precision:mt,return_timestamps:Ke,force_full_sequences:Ge});de.push({text:Fe,...Ze})}return ht?de[0]:de}async _call_moonshine(he,Se){const Ke=!Array.isArray(he);Ke&&(he=[he]);const qe=this.processor.feature_extractor.config.sampling_rate,Ge=await M(he,qe),We=[];for(const st of Ge){const ht=await this.processor(st),mt=Math.floor(st.length/qe)*6,ct=await this.model.generate({max_new_tokens:mt,...Se,...ht}),gt=this.processor.batch_decode(ct,{skip_special_tokens:!0})[0];We.push({text:gt})}return Ke?We[0]:We}}class re extends G{constructor(he){super(he)}async _call(he,Se={}){const Ke=Array.isArray(he),qe=await w(he),{pixel_values:Ge}=await this.processor(qe),We=[];for(const st of Ge){st.dims=[1,...st.dims];const ht=await this.model.generate({inputs:st,...Se}),mt=this.tokenizer.batch_decode(ht,{skip_special_tokens:!0}).map(ct=>({generated_text:ct.trim()}));We.push(mt)}return Ke?We:We[0]}}class ge extends G{constructor(he){super(he)}async _call(he,{top_k:Se=5}={}){const Ke=await w(he),{pixel_values:qe}=await this.processor(Ke),Ge=await this.model({pixel_values:qe}),We=this.model.config.id2label,st=[];for(const ht of Ge.logits){const mt=await(0,_.topk)(new _.Tensor("float32",(0,c.softmax)(ht.data),ht.dims),Se),ct=mt[0].tolist(),W=mt[1].tolist().map((de,J)=>({label:We?We[de]:`LABEL_${de}`,score:ct[J]}));st.push(W)}return Array.isArray(he)?st:st[0]}}class ve extends G{constructor(he){super(he),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(he,{threshold:Se=.5,mask_threshold:Ke=.5,overlap_mask_area_threshold:qe=.8,label_ids_to_fuse:Ge=null,target_sizes:We=null,subtask:st=null}={}){if(Array.isArray(he)&&he.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const mt=await w(he),ct=mt.map(Ze=>[Ze.height,Ze.width]),{pixel_values:gt,pixel_mask:W}=await this.processor(mt),de=await this.model({pixel_values:gt,pixel_mask:W});let J=null;if(st!==null)J=this.subtasks_mapping[st];else for(let[Ze,rt]of Object.entries(this.subtasks_mapping))if(rt in this.processor.image_processor){J=this.processor.image_processor[rt].bind(this.processor.image_processor),st=Ze;break}const Ee=this.model.config.id2label,Fe=[];if(st==="panoptic"||st==="instance"){const Ze=J(de,Se,Ke,qe,Ge,We??ct)[0],rt=Ze.segmentation;for(const dt of Ze.segments_info){const bt=new Uint8ClampedArray(rt.data.length);for(let Lt=0;LtKe.replace("{}",W)),st=this.tokenizer(We,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:ht}=await this.processor(Ge),mt=await this.model({...st,pixel_values:ht}),ct=this.model.config.model_type==="siglip"?W=>W.sigmoid().data:W=>(0,c.softmax)(W.data),gt=[];for(const W of mt.logits_per_image){const J=[...ct(W)].map((Ee,Fe)=>({score:Ee,label:Se[Fe]}));J.sort((Ee,Fe)=>Fe.score-Ee.score),gt.push(J)}return qe?gt:gt[0]}}class Le extends G{constructor(he){super(he)}async _call(he,{threshold:Se=.9,percentage:Ke=!1}={}){const qe=Array.isArray(he);if(qe&&he.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const Ge=await w(he),We=Ke?null:Ge.map(de=>[de.height,de.width]),{pixel_values:st,pixel_mask:ht}=await this.processor(Ge),mt=await this.model({pixel_values:st,pixel_mask:ht}),ct=this.processor.image_processor.post_process_object_detection(mt,Se,We),gt=this.model.config.id2label,W=ct.map(de=>de.boxes.map((J,Ee)=>({score:de.scores[Ee],label:gt[de.classes[Ee]],box:S(J,!Ke)})));return qe?W:W[0]}}class $e extends G{constructor(he){super(he)}async _call(he,Se,{threshold:Ke=.1,top_k:qe=null,percentage:Ge=!1}={}){const We=Array.isArray(he),st=await w(he),ht=this.tokenizer(Se,{padding:!0,truncation:!0}),mt=await this.processor(st),ct=[];for(let gt=0;gt({score:Ze.scores[dt],label:Ze.labels[dt],box:S(rt,!Ge)}))}else{const Ze=this.processor.image_processor.post_process_object_detection(Ee,Ke,de,!0)[0];Fe=Ze.boxes.map((rt,dt)=>({score:Ze.scores[dt],label:Se[Ze.classes[dt]],box:S(rt,!Ge)}))}Fe.sort((Ze,rt)=>rt.score-Ze.score),qe!==null&&(Fe=Fe.slice(0,qe)),ct.push(Fe)}return We?ct:ct[0]}}class pe extends G{constructor(he){super(he)}async _call(he,Se,Ke={}){const qe=(await w(he))[0],{pixel_values:Ge}=await this.processor(qe),We=`${Se}`,st=this.tokenizer(We,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,ht=await this.model.generate({inputs:Ge,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:st,...Ke}),ct=this.tokenizer.batch_decode(ht)[0].match(/(.*?)<\/s_answer>/);let gt=null;return ct&&ct.length>=2&&(gt=ct[1].trim()),[{answer:gt}]}}class X extends G{constructor(Se){super(Se);we(this,"DEFAULT_VOCODER_ID","Xenova/speecht5_hifigan");this.vocoder=Se.vocoder??null}async _call(Se,{speaker_embeddings:Ke=null}={}){return this.processor?this._call_text_to_spectrogram(Se,{speaker_embeddings:Ke}):this._call_text_to_waveform(Se)}async _call_text_to_waveform(Se){const Ke=this.tokenizer(Se,{padding:!0,truncation:!0}),{waveform:qe}=await this.model(Ke),Ge=this.model.config.sampling_rate;return new h.RawAudio(qe.data,Ge)}async _call_text_to_spectrogram(Se,{speaker_embeddings:Ke}){if(this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await a.AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"})),(typeof Ke=="string"||Ke instanceof URL)&&(Ke=new Float32Array(await(await fetch(Ke)).arrayBuffer())),Ke instanceof Float32Array)Ke=new _.Tensor("float32",Ke,[1,Ke.length]);else if(!(Ke instanceof _.Tensor))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");const{input_ids:qe}=this.tokenizer(Se,{padding:!0,truncation:!0}),{waveform:Ge}=await this.model.generate_speech(qe,Ke,{vocoder:this.vocoder}),We=this.processor.feature_extractor.config.sampling_rate;return new h.RawAudio(Ge.data,We)}}class le extends G{constructor(he){super(he)}async _call(he){const Se=await w(he),Ke=await this.processor(Se),qe=await this.model(Ke),Ge=[];for(const We of qe.reconstruction){const st=We.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");Ge.push(y.RawImage.fromTensor(st))}return Ge.length>1?Ge:Ge[0]}}class ke extends G{constructor(he){super(he)}async _call(he){const Se=await w(he),Ke=await this.processor(Se),{predicted_depth:qe}=await this.model(Ke),Ge=[];for(let We=0;We1?Ge:Ge[0]}}const Re=Object.freeze({"text-classification":{tokenizer:n.AutoTokenizer,pipeline:H,model:a.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:n.AutoTokenizer,pipeline:B,model:a.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:n.AutoTokenizer,pipeline:z,model:a.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:n.AutoTokenizer,pipeline:U,model:a.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:n.AutoTokenizer,pipeline:I,model:a.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:n.AutoTokenizer,pipeline:k,model:a.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:n.AutoTokenizer,pipeline:F,model:a.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:n.AutoTokenizer,pipeline:j,model:a.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:n.AutoTokenizer,pipeline:ce,model:a.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:Te,model:a.AutoModelForAudioClassification,processor:o.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:n.AutoTokenizer,pipeline:ie,model:a.AutoModel,processor:o.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:n.AutoTokenizer,pipeline:oe,model:[a.AutoModelForSpeechSeq2Seq,a.AutoModelForCTC],processor:o.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:n.AutoTokenizer,pipeline:X,model:[a.AutoModelForTextToWaveform,a.AutoModelForTextToSpectrogram],processor:[o.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:n.AutoTokenizer,pipeline:re,model:a.AutoModelForVision2Seq,processor:o.AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:ge,model:a.AutoModelForImageClassification,processor:o.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:ve,model:[a.AutoModelForImageSegmentation,a.AutoModelForSemanticSegmentation,a.AutoModelForUniversalSegmentation],processor:o.AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"zero-shot-image-classification":{tokenizer:n.AutoTokenizer,pipeline:me,model:a.AutoModel,processor:o.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:Le,model:a.AutoModelForObjectDetection,processor:o.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:n.AutoTokenizer,pipeline:$e,model:a.AutoModelForZeroShotObjectDetection,processor:o.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:n.AutoTokenizer,pipeline:pe,model:a.AutoModelForDocumentQuestionAnswering,processor:o.AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:le,model:a.AutoModelForImageToImage,processor:o.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:ke,model:a.AutoModelForDepthEstimation,processor:o.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:n.AutoTokenizer,pipeline:ue,model:a.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:o.AutoProcessor,pipeline:Pe,model:[a.AutoModelForImageFeatureExtraction,a.AutoModel],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),Xe=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function ae(Ve,he=null,{progress_callback:Se=null,config:Ke=null,cache_dir:qe=null,local_files_only:Ge=!1,revision:We="main",device:st=null,dtype:ht=null,model_file_name:mt=null,session_options:ct={}}={}){Ve=Xe[Ve]??Ve;const gt=Re[Ve.split("_",1)[0]];if(!gt)throw Error(`Unsupported pipeline: ${Ve}. Must be one of [${Object.keys(Re)}]`);he||(he=gt.default.model,console.log(`No model specified. Using default model: "${he}".`));const W={progress_callback:Se,config:Ke,cache_dir:qe,local_files_only:Ge,revision:We,device:st,dtype:ht,model_file_name:mt,session_options:ct},de=new Map([["tokenizer",gt.tokenizer],["model",gt.model],["processor",gt.processor]]),J=await He(de,he,W);J.task=Ve,(0,d.dispatchCallback)(Se,{status:"ready",task:Ve,model:he});const Ee=gt.pipeline;return new Ee(J)}async function He(Ve,he,Se){const Ke=Object.create(null),qe=[];for(const[Ge,We]of Ve.entries()){if(!We)continue;let st;Array.isArray(We)?st=new Promise(async(ht,mt)=>{var gt,W;let ct;for(const de of We){if(de===null){ht(null);return}try{ht(await de.from_pretrained(he,Se));return}catch(J){if((gt=J.message)!=null&>.includes("Unsupported model type"))ct=J;else if((W=J.message)!=null&&W.includes("Could not locate file"))ct=J;else{mt(J);return}}}mt(ct)}):st=We.from_pretrained(he,Se),Ke[Ge]=st,qe.push(st)}await Promise.all(qe);for(const[Ge,We]of Object.entries(Ke))Ke[Ge]=await We;return Ke}},"./src/tokenizers.js":(r,e,t)=>{t.r(e),t.d(e,{AlbertTokenizer:()=>Ts,AutoTokenizer:()=>Tr,BartTokenizer:()=>Ps,BertTokenizer:()=>sa,BlenderbotSmallTokenizer:()=>Xa,BlenderbotTokenizer:()=>Ya,BloomTokenizer:()=>ps,CLIPTokenizer:()=>Sa,CamembertTokenizer:()=>ot,CodeGenTokenizer:()=>Ca,CodeLlamaTokenizer:()=>Bs,CohereTokenizer:()=>Ia,ConvBertTokenizer:()=>Fs,DebertaTokenizer:()=>Kn,DebertaV2Tokenizer:()=>ia,DistilBertTokenizer:()=>jn,ElectraTokenizer:()=>Ut,EsmTokenizer:()=>js,FalconTokenizer:()=>Ka,GPT2Tokenizer:()=>Ds,GPTNeoXTokenizer:()=>qa,GemmaTokenizer:()=>Oi,Grok1Tokenizer:()=>zs,HerbertTokenizer:()=>Ms,LlamaTokenizer:()=>Ma,M2M100Tokenizer:()=>Pa,MBart50Tokenizer:()=>zn,MBartTokenizer:()=>Dr,MPNetTokenizer:()=>Ha,MarianTokenizer:()=>Wt,MgpstrTokenizer:()=>ei,MobileBertTokenizer:()=>xs,NllbTokenizer:()=>Un,NougatTokenizer:()=>Us,PreTrainedTokenizer:()=>qt,Qwen2Tokenizer:()=>Za,RoFormerTokenizer:()=>Ns,RobertaTokenizer:()=>en,SiglipTokenizer:()=>Aa,SpeechT5Tokenizer:()=>Qa,SqueezeBertTokenizer:()=>aa,T5Tokenizer:()=>pn,TokenizerModel:()=>Pe,VitsTokenizer:()=>Ja,Wav2Vec2CTCTokenizer:()=>ka,WhisperTokenizer:()=>oa,XLMRobertaTokenizer:()=>$i,XLMTokenizer:()=>At,is_chinese_char:()=>U});var n=t("./src/utils/generic.js"),a=t("./src/utils/core.js"),o=t("./src/utils/hub.js"),u=t("./src/utils/maths.js"),d=t("./src/utils/tensor.js"),c=t("./src/utils/data-structures.js"),h=t("./node_modules/@huggingface/jinja/dist/index.js"),_=t("./src/models/whisper/common_whisper.js");async function y(Ie,N){const ee=await Promise.all([(0,o.getModelJSON)(Ie,"tokenizer.json",!0,N),(0,o.getModelJSON)(Ie,"tokenizer_config.json",!0,N)]);return N.legacy!==null&&(ee[1].legacy=N.legacy),ee}function w(Ie,N){const ee=[];let fe=0;for(const Ae of Ie.matchAll(N)){const Oe=Ae[0];fe0&&ee.push(Oe),fe=Ae.index+Oe.length}return fe=19968&&Ie<=40959||Ie>=13312&&Ie<=19903||Ie>=131072&&Ie<=173791||Ie>=173824&&Ie<=177983||Ie>=177984&&Ie<=178207||Ie>=178208&&Ie<=183983||Ie>=63744&&Ie<=64255||Ie>=194560&&Ie<=195103}function F(Ie,N,ee){const fe=[];let Ae=0;for(;Aethis.tokens_to_ids.get(ee)??this.unk_token_id)}convert_ids_to_tokens(N){return N.map(ee=>this.vocab[ee]??this.unk_token)}}class Te extends Pe{constructor(N){super(N),this.tokens_to_ids=S(N.vocab),this.unk_token_id=this.tokens_to_ids.get(N.unk_token),this.unk_token=N.unk_token,this.max_input_chars_per_word=N.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[ee,fe]of this.tokens_to_ids)this.vocab[fe]=ee}encode(N){const ee=[];for(const fe of N){const Ae=[...fe];if(Ae.length>this.max_input_chars_per_word){ee.push(this.unk_token);continue}let Oe=!1,Je=0;const _t=[];for(;Je0&&(St=this.config.continuing_subword_prefix+St),this.tokens_to_ids.has(St)){yt=St;break}--Et}if(yt===null){Oe=!0;break}_t.push(yt),Je=Et}Oe?ee.push(this.unk_token):ee.push(..._t)}return ee}}class ie extends Pe{constructor(N,ee){super(N);const fe=N.vocab.length;this.vocab=new Array(fe),this.scores=new Array(fe);for(let Ae=0;Ae[Ae,Oe])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=ee.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.minScore=(0,u.min)(this.scores)[0],this.unk_score=this.minScore-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new c.CharTrie,this.trie.extend(this.vocab),this.fuse_unk=!0}populateNodes(N){const ee=N.chars,fe=1;let Ae=0;for(;Ae{const Ie=[...Array.from({length:94},(Ae,Oe)=>Oe+33),...Array.from({length:12},(Ae,Oe)=>Oe+161),...Array.from({length:82},(Ae,Oe)=>Oe+174)],N=Ie.slice();let ee=0;for(let Ae=0;Ae<256;++Ae)Ie.includes(Ae)||(Ie.push(Ae),N.push(256+ee),ee+=1);const fe=N.map(Ae=>String.fromCharCode(Ae));return Object.fromEntries(Ie.map((Ae,Oe)=>[Ae,fe[Oe]]))})(),re=(0,a.reverseDictionary)(oe);class ge extends Pe{constructor(N){super(N),this.tokens_to_ids=S(N.vocab),this.unk_token_id=this.tokens_to_ids.get(N.unk_token),this.unk_token=N.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[fe,Ae]of this.tokens_to_ids)this.vocab[Ae]=fe;const ee=Array.isArray(N.merges[0]);this.merges=ee?N.merges:N.merges.map(fe=>fe.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((fe,Ae)=>[JSON.stringify(fe),Ae])),this.end_of_word_suffix=N.end_of_word_suffix,this.continuing_subword_suffix=N.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??!1,this.cache=new Map}bpe(N){if(N.length===0)return[];const ee=this.cache.get(N);if(ee!==void 0)return ee;const fe=Array.from(N);this.end_of_word_suffix&&(fe[fe.length-1]+=this.end_of_word_suffix);let Ae=[];if(fe.length>1){const Oe=new c.PriorityQueue((Et,yt)=>Et.score`<0x${_t.toString(16).toUpperCase().padStart(2,"0")}>`);Je.every(_t=>this.tokens_to_ids.has(_t))?ee.push(...Je):ee.push(this.unk_token)}else ee.push(this.unk_token)}return ee}}class ve extends Pe{constructor(N,ee){super(N),this.tokens_to_ids=S(ee.target_lang?N.vocab[ee.target_lang]:N.vocab),this.bos_token=ee.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=ee.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=ee.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=ee.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(const[fe,Ae]of this.tokens_to_ids)this.vocab[Ae]=fe}encode(N){return N}}class me extends n.Callable{constructor(N){super(),this.config=N}static fromConfig(N){if(N===null)return null;switch(N.type){case"BertNormalizer":return new He(N);case"Precompiled":return new Rr(N);case"Sequence":return new ae(N);case"Replace":return new Le(N);case"NFC":return new $e(N);case"NFKC":return new pe(N);case"NFKD":return new X(N);case"Strip":return new le(N);case"StripAccents":return new ke(N);case"Lowercase":return new Re(N);case"Prepend":return new Xe(N);default:throw new Error(`Unknown Normalizer type: ${N.type}`)}}normalize(N){throw Error("normalize should be implemented in subclass.")}_call(N){return this.normalize(N)}}class Le extends me{normalize(N){const ee=M(this.config.pattern);return ee===null?N:N.replaceAll(ee,this.config.content)}}class $e extends me{normalize(N){return N=N.normalize("NFC"),N}}class pe extends me{normalize(N){return N=N.normalize("NFKC"),N}}class X extends me{normalize(N){return N=N.normalize("NFKD"),N}}class le extends me{normalize(N){return this.config.strip_left&&this.config.strip_right?N=N.trim():(this.config.strip_left&&(N=N.trimStart()),this.config.strip_right&&(N=N.trimEnd())),N}}class ke extends me{normalize(N){return N=B(N),N}}class Re extends me{normalize(N){return N=N.toLowerCase(),N}}class Xe extends me{normalize(N){return N=this.config.prepend+N,N}}class ae extends me{constructor(N){super(N),this.normalizers=N.normalizers.map(ee=>me.fromConfig(ee))}normalize(N){return this.normalizers.reduce((ee,fe)=>fe.normalize(ee),N)}}class He extends me{_tokenize_chinese_chars(N){const ee=[];for(let fe=0;fethis.pre_tokenize_text(fe,ee)):this.pre_tokenize_text(N,ee)).flat()}_call(N,ee){return this.pre_tokenize(N,ee)}}class he extends Ve{constructor(N){super(),this.pattern=new RegExp(`[^\\s${k}]+|[${k}]`,"gu")}pre_tokenize_text(N,ee){return N.trim().match(this.pattern)||[]}}class Se extends Ve{constructor(N){super(),this.config=N,this.add_prefix_space=this.config.add_prefix_space,this.trim_offsets=this.config.trim_offsets,this.use_regex=this.config.use_regex??!0,this.pattern=new RegExp("'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+","gu"),this.byte_encoder=oe,this.text_encoder=new TextEncoder}pre_tokenize_text(N,ee){return this.add_prefix_space&&!N.startsWith(" ")&&(N=" "+N),(this.use_regex?N.match(this.pattern)||[]:[N]).map(Ae=>Array.from(this.text_encoder.encode(Ae),Oe=>this.byte_encoder[Oe]).join(""))}}class Ke extends Ve{constructor(N){super(),this.config=N,this.pattern=M(this.config.pattern,this.config.invert)}pre_tokenize_text(N,ee){var fe;return this.pattern===null?[]:this.config.invert?N.match(this.pattern)||[]:((fe=this.config.behavior)==null?void 0:fe.toLowerCase())==="removed"?N.split(this.pattern).filter(Ae=>Ae):w(N,this.pattern)}}class qe extends Ve{constructor(N){super(),this.config=N,this.pattern=new RegExp(`[^${k}]+|[${k}]+`,"gu")}pre_tokenize_text(N,ee){return N.match(this.pattern)||[]}}class Ge extends Ve{constructor(N){super(),this.config=N;const ee=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(ee,"gu")}pre_tokenize_text(N,ee){return N.match(this.pattern)||[]}}class We extends n.Callable{constructor(N){super(),this.config=N}static fromConfig(N){if(N===null)return null;switch(N.type){case"TemplateProcessing":return new mt(N);case"ByteLevel":return new ct(N);case"RobertaProcessing":return new ht(N);case"BertProcessing":return new st(N);case"Sequence":return new gt(N);default:throw new Error(`Unknown PostProcessor type: ${N.type}`)}}post_process(N,...ee){throw Error("post_process should be implemented in subclass.")}_call(N,...ee){return this.post_process(N,...ee)}}class st extends We{constructor(N){super(N),this.cls=N.cls[0],this.sep=N.sep[0]}post_process(N,ee=null,{add_special_tokens:fe=!0}={}){fe&&(N=(0,a.mergeArrays)([this.cls],N,[this.sep]));let Ae=new Array(N.length).fill(0);if(ee!==null){const Oe=fe&&this instanceof ht?[this.sep]:[],Je=fe?[this.sep]:[];N=(0,a.mergeArrays)(N,Oe,ee,Je),Ae=(0,a.mergeArrays)(Ae,new Array(ee.length+Oe.length+Je.length).fill(1))}return{tokens:N,token_type_ids:Ae}}}class ht extends st{}class mt extends We{constructor(N){super(N),this.single=N.single,this.pair=N.pair}post_process(N,ee=null,{add_special_tokens:fe=!0}={}){const Ae=ee===null?this.single:this.pair;let Oe=[],Je=[];for(const _t of Ae)"SpecialToken"in _t?fe&&(Oe.push(_t.SpecialToken.id),Je.push(_t.SpecialToken.type_id)):"Sequence"in _t&&(_t.Sequence.id==="A"?(Oe=(0,a.mergeArrays)(Oe,N),Je=(0,a.mergeArrays)(Je,new Array(N.length).fill(_t.Sequence.type_id))):_t.Sequence.id==="B"&&(Oe=(0,a.mergeArrays)(Oe,ee),Je=(0,a.mergeArrays)(Je,new Array(ee.length).fill(_t.Sequence.type_id))));return{tokens:Oe,token_type_ids:Je}}}class ct extends We{post_process(N,ee=null){return ee&&(N=(0,a.mergeArrays)(N,ee)),{tokens:N}}}class gt extends We{constructor(N){super(N),this.processors=N.processors.map(ee=>We.fromConfig(ee))}post_process(N,ee=null,fe={}){let Ae;for(const Oe of this.processors)if(Oe instanceof ct)N=Oe.post_process(N).tokens,ee&&(ee=Oe.post_process(ee).tokens);else{const Je=Oe.post_process(N,ee,fe);N=Je.tokens,Ae=Je.token_type_ids}return{tokens:N,token_type_ids:Ae}}}class W extends n.Callable{constructor(N){super(),this.config=N,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=N.trim_offsets}static fromConfig(N){if(N===null)return null;switch(N.type){case"WordPiece":return new Ze(N);case"Metaspace":return new br(N);case"ByteLevel":return new rt(N);case"Replace":return new de(N);case"ByteFallback":return new J(N);case"Fuse":return new Ee(N);case"Strip":return new Fe(N);case"Sequence":return new bt(N);case"CTC":return new dt(N);case"BPEDecoder":return new Ct(N);default:throw new Error(`Unknown Decoder type: ${N.type}`)}}_call(N){return this.decode(N)}decode(N){return this.decode_chain(N).join("")}decode_chain(N){throw Error("`decode_chain` should be implemented in subclass.")}}class de extends W{decode_chain(N){const ee=M(this.config.pattern);return ee===null?N:N.map(fe=>fe.replaceAll(ee,this.config.content))}}class J extends W{constructor(N){super(N),this.text_decoder=new TextDecoder}decode_chain(N){const ee=[];let fe=[];for(const Ae of N){let Oe=null;if(Ae.length===6&&Ae.startsWith("<0x")&&Ae.endsWith(">")){const Je=parseInt(Ae.slice(3,5),16);isNaN(Je)||(Oe=Je)}if(Oe!==null)fe.push(Oe);else{if(fe.length>0){const Je=this.text_decoder.decode(Uint8Array.from(fe));ee.push(Je),fe=[]}ee.push(Ae)}}if(fe.length>0){const Ae=this.text_decoder.decode(Uint8Array.from(fe));ee.push(Ae),fe=[]}return ee}}class Ee extends W{decode_chain(N){return[N.join("")]}}class Fe extends W{constructor(N){super(N),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain(N){return N.map(ee=>{let fe=0;for(let Oe=0;Oe(fe!==0&&(ee.startsWith(this.config.prefix)?ee=ee.replace(this.config.prefix,""):ee=" "+ee),this.cleanup&&(ee=H(ee)),ee))}}class rt extends W{constructor(N){super(N),this.byte_decoder=re,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(N){const ee=N.join(""),fe=new Uint8Array([...ee].map(Oe=>this.byte_decoder[Oe]));return this.text_decoder.decode(fe)}decode_chain(N){const ee=[];let fe=[];for(const Ae of N)this.added_tokens.find(Oe=>Oe.content===Ae)!==void 0?(fe.length>0&&(ee.push(this.convert_tokens_to_string(fe)),fe=[]),ee.push(Ae)):fe.push(Ae);return fe.length>0&&ee.push(this.convert_tokens_to_string(fe)),ee}}class dt extends W{constructor(N){super(N),this.pad_token=this.config.pad_token,this.word_delimiter_token=this.config.word_delimiter_token,this.cleanup=this.config.cleanup}convert_tokens_to_string(N){if(N.length===0)return"";const ee=[N[0]];for(let Oe=1;OeOe!==this.pad_token).join("");return this.cleanup&&(Ae=H(Ae).replaceAll(this.word_delimiter_token," ").trim()),Ae}decode_chain(N){return[this.convert_tokens_to_string(N)]}}class bt extends W{constructor(N){super(N),this.decoders=N.decoders.map(ee=>W.fromConfig(ee))}decode_chain(N){return this.decoders.reduce((ee,fe)=>fe.decode_chain(ee),N)}}class Ct extends W{constructor(N){super(N),this.suffix=this.config.suffix}decode_chain(N){return N.map((ee,fe)=>ee.replaceAll(this.suffix,fe===N.length-1?"":" "))}}class Lt extends W{decode_chain(N){let ee="";for(let fe=1;fefe.normalize("NFKC")).join("~"):N=N.normalize("NFKC"),N}}class Yr extends Ve{constructor(N){super(),this.tokenizers=N.pretokenizers.map(ee=>Ve.fromConfig(ee))}pre_tokenize_text(N,ee){return this.tokenizers.reduce((fe,Ae)=>Ae.pre_tokenize(fe,ee),[N])}}class nn extends Ve{constructor(N){super()}pre_tokenize_text(N,ee){return N.match(/\w+|[^\w\s]+/g)||[]}}class $n extends Ve{constructor(N){super()}pre_tokenize_text(N,ee){return I(N)}}class Es extends Ve{constructor(N){super(),this.config=N,this.pattern=M(this.config.pattern),this.content=this.config.content}pre_tokenize_text(N,ee){return this.pattern===null?[N]:[N.replaceAll(this.pattern,this.config.content)]}}const na=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function fn(Ie,N,ee,fe){for(const Ae of Object.keys(Ie)){const Oe=N-Ie[Ae].length,Je=ee(Ae),_t=new Array(Oe).fill(Je);Ie[Ae]=fe==="right"?(0,a.mergeArrays)(Ie[Ae],_t):(0,a.mergeArrays)(_t,Ie[Ae])}}function fs(Ie,N){for(const ee of Object.keys(Ie))Ie[ee].length=N}class qt extends n.Callable{constructor(ee,fe){super();we(this,"return_token_type_ids",!1);we(this,"padding_side","right");this._tokenizer_config=fe,this.normalizer=me.fromConfig(ee.normalizer),this.pre_tokenizer=Ve.fromConfig(ee.pre_tokenizer),this.model=Pe.fromConfig(ee.model,fe),this.post_processor=We.fromConfig(ee.post_processor),this.decoder=W.fromConfig(ee.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const Ae of ee.added_tokens){const Oe=new ue(Ae);this.added_tokens.push(Oe),this.model.tokens_to_ids.set(Oe.content,Oe.id),this.model.vocab[Oe.id]=Oe.content,Oe.special&&(this.special_tokens.push(Oe.content),this.all_special_ids.push(Oe.id))}if(this.additional_special_tokens=fe.additional_special_tokens??[],this.special_tokens.push(...this.additional_special_tokens),this.special_tokens=[...new Set(this.special_tokens)],this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.added_tokens_regex=this.added_tokens.length>0?new RegExp(this.added_tokens.slice().sort((Ae,Oe)=>Oe.content.length-Ae.content.length).map(Ae=>`${Ae.lstrip?"\\s*":""}(${(0,a.escapeRegExp)(Ae.content)})${Ae.rstrip?"\\s*":""}`).join("|")):null,this.mask_token=this.getToken("mask_token"),this.mask_token_id=this.model.tokens_to_ids.get(this.mask_token),this.pad_token=this.getToken("pad_token","eos_token"),this.pad_token_id=this.model.tokens_to_ids.get(this.pad_token),this.sep_token=this.getToken("sep_token"),this.sep_token_id=this.model.tokens_to_ids.get(this.sep_token),this.unk_token=this.getToken("unk_token"),this.unk_token_id=this.model.tokens_to_ids.get(this.unk_token),this.bos_token=this.getToken("bos_token"),this.bos_token_id=this.model.tokens_to_ids.get(this.bos_token),this.eos_token=this.getToken("eos_token"),this.eos_token_id=this.model.tokens_to_ids.get(this.eos_token),this.model_max_length=fe.model_max_length,this.remove_space=fe.remove_space,this.clean_up_tokenization_spaces=fe.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=fe.do_lowercase_and_remove_accent??!1,fe.padding_side&&(this.padding_side=fe.padding_side),this.legacy=!1,this.chat_template=fe.chat_template??null,Array.isArray(this.chat_template)){const Ae=Object.create(null);for(const{name:Oe,template:Je}of this.chat_template){if(typeof Oe!="string"||typeof Je!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');Ae[Oe]=Je}this.chat_template=Ae}this._compiled_template_cache=new Map}getToken(...ee){for(const fe of ee){const Ae=this._tokenizer_config[fe];if(Ae)if(typeof Ae=="object"){if(Ae.__type==="AddedToken")return Ae.content;throw Error(`Unknown token: ${Ae}`)}else return Ae}return null}static async from_pretrained(ee,{progress_callback:fe=null,config:Ae=null,cache_dir:Oe=null,local_files_only:Je=!1,revision:_t="main",legacy:Et=null}={}){const yt=await y(ee,{progress_callback:fe,config:Ae,cache_dir:Oe,local_files_only:Je,revision:_t,legacy:Et});return new this(...yt)}_call(ee,{text_pair:fe=null,add_special_tokens:Ae=!0,padding:Oe=!1,truncation:Je=null,max_length:_t=null,return_tensor:Et=!0,return_token_type_ids:yt=null}={}){const St=Array.isArray(ee);let tr;if(St){if(ee.length===0)throw Error("text array must be non-empty");if(fe!==null){if(Array.isArray(fe)){if(ee.length!==fe.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");tr=ee.map((Pr,rn)=>this._encode_plus(Pr,{text_pair:fe[rn],add_special_tokens:Ae,return_token_type_ids:yt}))}else tr=ee.map(Pr=>this._encode_plus(Pr,{add_special_tokens:Ae,return_token_type_ids:yt}))}else{if(ee==null)throw Error("text may not be null or undefined");if(Array.isArray(fe))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");tr=[this._encode_plus(ee,{text_pair:fe,add_special_tokens:Ae,return_token_type_ids:yt})]}if(_t===null?Oe==="max_length"?_t=this.model_max_length:_t=(0,u.max)(tr.map(Pr=>Pr.input_ids.length))[0]:Je||console.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation=true` to explicitly truncate examples to max length."),_t=Math.min(_t,this.model_max_length??1/0),Oe||Je)for(let Pr=0;Pr_t?Je&&fs(tr[Pr],_t):Oe&&fn(tr[Pr],_t,rn=>rn==="input_ids"?this.pad_token_id:0,this.padding_side));const kr={};if(Et){if(!(Oe&&Je)&&tr.some(rn=>{var Gt;for(const mr of Object.keys(rn))if(rn[mr].length!==((Gt=tr[0][mr])==null?void 0:Gt.length))return!0;return!1}))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.");const Pr=[tr.length,tr[0].input_ids.length];for(const rn of Object.keys(tr[0]))kr[rn]=new d.Tensor("int64",BigInt64Array.from(tr.flatMap(Gt=>Gt[rn]).map(BigInt)),Pr)}else{for(const Pr of Object.keys(tr[0]))kr[Pr]=tr.map(rn=>rn[Pr]);if(!St)for(const Pr of Object.keys(kr))kr[Pr]=kr[Pr][0]}return kr}_encode_text(ee){return ee===null?null:(this.added_tokens_regex?ee.split(this.added_tokens_regex).filter(Oe=>Oe):[ee]).map((Oe,Je)=>{if(this.added_tokens.find(Et=>Et.content===Oe)!==void 0)return Oe;{if(this.remove_space===!0&&(Oe=Oe.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(Oe=z(Oe)),this.normalizer!==null&&(Oe=this.normalizer(Oe)),Oe.length===0)return[];const Et=this.pre_tokenizer!==null?this.pre_tokenizer(Oe,{section_index:Je}):[Oe];return this.model(Et)}}).flat()}_encode_plus(ee,{text_pair:fe=null,add_special_tokens:Ae=!0,return_token_type_ids:Oe=null}={}){const{tokens:Je,token_type_ids:_t}=this._tokenize_helper(ee,{pair:fe,add_special_tokens:Ae}),Et=this.model.convert_tokens_to_ids(Je),yt={input_ids:Et,attention_mask:new Array(Et.length).fill(1)};return(Oe??this.return_token_type_ids)&&_t&&(yt.token_type_ids=_t),yt}_tokenize_helper(ee,{pair:fe=null,add_special_tokens:Ae=!1}={}){const Oe=this._encode_text(ee),Je=this._encode_text(fe);return this.post_processor?this.post_processor(Oe,Je,{add_special_tokens:Ae}):{tokens:(0,a.mergeArrays)(Oe??[],Je??[])}}tokenize(ee,{pair:fe=null,add_special_tokens:Ae=!1}={}){return this._tokenize_helper(ee,{pair:fe,add_special_tokens:Ae}).tokens}encode(ee,{text_pair:fe=null,add_special_tokens:Ae=!0,return_token_type_ids:Oe=null}={}){return this._encode_plus(ee,{text_pair:fe,add_special_tokens:Ae,return_token_type_ids:Oe}).input_ids}batch_decode(ee,fe={}){return ee instanceof d.Tensor&&(ee=ee.tolist()),ee.map(Ae=>this.decode(Ae,fe))}decode(ee,fe={}){if(ee instanceof d.Tensor&&(ee=G(ee)),!Array.isArray(ee)||ee.length===0||!(0,a.isIntegralNumber)(ee[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(ee,fe)}decode_single(ee,{skip_special_tokens:fe=!1,clean_up_tokenization_spaces:Ae=null}){let Oe=this.model.convert_ids_to_tokens(ee);fe&&(Oe=Oe.filter(_t=>!this.special_tokens.includes(_t)));let Je=this.decoder?this.decoder(Oe):Oe.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(Je=Je.replaceAll(this.decoder.end_of_word_suffix," "),fe&&(Je=Je.trim())),(Ae??this.clean_up_tokenization_spaces)&&(Je=H(Je)),Je}get_chat_template({chat_template:ee=null,tools:fe=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){const Ae=this.chat_template;if(ee!==null&&Object.hasOwn(Ae,ee))ee=Ae[ee];else if(ee===null)if(fe!==null&&"tool_use"in Ae)ee=Ae.tool_use;else if("default"in Ae)ee=Ae.default;else throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(Ae).sort()}.`)}else if(ee===null)if(this.chat_template)ee=this.chat_template;else throw Error("Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating");return ee}apply_chat_template(ee,{tools:fe=null,documents:Ae=null,chat_template:Oe=null,add_generation_prompt:Je=!1,tokenize:_t=!0,padding:Et=!1,truncation:yt=!1,max_length:St=null,return_tensor:tr=!0,return_dict:kr=!1,tokenizer_kwargs:Pr={},...rn}={}){if(Oe=this.get_chat_template({chat_template:Oe,tools:fe}),typeof Oe!="string")throw Error(`chat_template must be a string, but got ${typeof Oe}`);let Gt=this._compiled_template_cache.get(Oe);Gt===void 0&&(Gt=new h.Template(Oe),this._compiled_template_cache.set(Oe,Gt));const mr=Object.create(null);for(const mn of na){const ze=this.getToken(mn);ze&&(mr[mn]=ze)}const On=Gt.render({messages:ee,add_generation_prompt:Je,tools:fe,documents:Ae,...mr,...rn});if(_t){const mn=this._call(On,{add_special_tokens:!1,padding:Et,truncation:yt,max_length:St,return_tensor:tr,...Pr});return kr?mn:mn.input_ids}return On}}class sa extends qt{constructor(){super(...arguments);we(this,"return_token_type_ids",!0)}}class Ts extends qt{constructor(){super(...arguments);we(this,"return_token_type_ids",!0)}}class xs extends qt{constructor(){super(...arguments);we(this,"return_token_type_ids",!0)}}class aa extends qt{constructor(){super(...arguments);we(this,"return_token_type_ids",!0)}}class Kn extends qt{constructor(){super(...arguments);we(this,"return_token_type_ids",!0)}}class ia extends qt{constructor(){super(...arguments);we(this,"return_token_type_ids",!0)}}class Ms extends qt{constructor(){super(...arguments);we(this,"return_token_type_ids",!0)}}class Fs extends qt{constructor(){super(...arguments);we(this,"return_token_type_ids",!0)}}class Ns extends qt{constructor(){super(...arguments);we(this,"return_token_type_ids",!0)}}class jn extends qt{}class ot extends qt{}class At extends qt{constructor(ee,fe){super(ee,fe);we(this,"return_token_type_ids",!0);console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}}class Ut extends qt{constructor(){super(...arguments);we(this,"return_token_type_ids",!0)}}class pn extends qt{}class Ds extends qt{}class Ps extends qt{}class Dr extends qt{constructor(N,ee){super(N,ee),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(fe=>this.languageRegex.test(fe)),this.lang_to_token=fe=>fe}_build_translation_inputs(N,ee,fe){return rs(this,N,ee,fe)}}class zn extends Dr{}class en extends qt{}class ps extends qt{}const fr="▁";class Ma extends qt{constructor(ee,fe){super(ee,fe);we(this,"padding_side","left");this.legacy=fe.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new Nt({replacement:fr,add_prefix_space:!0,prepend_scheme:"first"}))}_encode_text(ee){if(ee===null)return null;if(this.legacy||ee.length===0)return super._encode_text(ee);let fe=super._encode_text(fr+ee.replaceAll(fr," "));return fe.length>1&&fe[0]===fr&&this.special_tokens.includes(fe[1])&&(fe=fe.slice(1)),fe}}class Bs extends qt{}class $i extends qt{}class Ha extends qt{}class Ka extends qt{}class qa extends qt{}class js extends qt{}class Za extends qt{}class Oi extends qt{}class zs extends qt{}function rs(Ie,N,ee,fe){if(!("language_codes"in Ie)||!Array.isArray(Ie.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in Ie)||!(Ie.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in Ie)||typeof Ie.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const Ae=fe.src_lang,Oe=fe.tgt_lang;if(!Ie.language_codes.includes(Oe))throw new Error(`Target language code "${Oe}" is not valid. Must be one of: {${Ie.language_codes.join(", ")}}`);if(Ae!==void 0){if(!Ie.language_codes.includes(Ae))throw new Error(`Source language code "${Ae}" is not valid. Must be one of: {${Ie.language_codes.join(", ")}}`);for(const Je of Ie.post_processor.config.single)if("SpecialToken"in Je&&Ie.languageRegex.test(Je.SpecialToken.id)){Je.SpecialToken.id=Ie.lang_to_token(Ae);break}}return fe.forced_bos_token_id=Ie.model.convert_tokens_to_ids([Ie.lang_to_token(Oe)])[0],Ie._call(N,ee)}class Un extends qt{constructor(N,ee){super(N,ee),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(fe=>this.languageRegex.test(fe)),this.lang_to_token=fe=>fe}_build_translation_inputs(N,ee,fe){return rs(this,N,ee,fe)}}class Pa extends qt{constructor(N,ee){super(N,ee),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(fe=>this.languageRegex.test(fe)).map(fe=>fe.slice(2,-2)),this.lang_to_token=fe=>`__${fe}__`}_build_translation_inputs(N,ee,fe){return rs(this,N,ee,fe)}}class oa extends qt{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr(N,{return_timestamps:ee=!1,return_language:fe=!1,time_precision:Ae=null,force_full_sequences:Oe=!0}={}){if(Ae===null)throw Error("Must specify time_precision");let Je=null;const _t=ee==="word";function Et(){return{language:Je,timestamp:[null,null],text:""}}const yt=[];let St=Et(),tr=0;const kr=this.timestamp_begin,rn=kr+1500;let Gt=[],mr=[],On=!1,mn=null;const ze=new Set(this.all_special_ids);for(const Xr of N){const yn=Xr.tokens,jt=_t?Xr.token_timestamps:null;let Nn=null,ns=kr;if("stride"in Xr){const[xt,sr,sn]=Xr.stride;if(tr-=sr,mn=xt-sn,sr&&(ns=sr/Ae+kr),sn)for(let Jr=yn.length-1;Jr>=0;--Jr){const _n=Number(yn[Jr]);if(_n>=kr){if(Nn!==null&&(_n-kr)*Ae=kr&&sr<=rn){const sn=(sr-kr)*Ae+tr,Jr=(0,u.round)(sn,2);if(Nn!==null&&sr>=Nn)On=!0;else if(On||Gt.length>0&&sr0?(Gt.push(Ir),_t&&mr.push(Qr)):Gt.every(xt=>xt.length===0)&&(St=Et(),Gt=[],Ir=[],mr=[],Qr=[])}if(Gt.length>0){if(Oe&&ee)throw new Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");const[Xr,yn]=this.findLongestCommonSequence(Gt,mr),jt=this.decode(Xr);St.text=jt,_t&&(St.words=this.collateWordTimestamps(Xr,yn,Je)),yt.push(St)}let xn=Object.create(null);const Cs=yt.map(Xr=>Xr.text).join("");if(ee||fe){for(let Xr=0;Xr0;let _t=Je?[]:null,Et=Je?ee[0]:null;for(let yt=1;ytsr===ns[sn]&&Et[Cs+sn]<=ee[yt][jt+sn]).length:Ir=yn.filter((sr,sn)=>sr===ns[sn]).length;const Qr=xn/1e4,xt=Ir/xn+Qr;Ir>1&&xt>tr&&(tr=xt,kr=[Cs,Xr,jt,Nn])}const[rn,Gt,mr,On]=kr,mn=Math.floor((Gt+rn)/2),ze=Math.floor((On+mr)/2);Oe.push(...fe.slice(0,mn)),fe=St.slice(ze),Ae=fe.length,Je&&(_t.push(...Et.slice(0,mn)),Et=ee[yt].slice(ze))}return Oe.push(...fe),Je?(_t.push(...Et),[Oe,_t]):[Oe,[]]}collateWordTimestamps(N,ee,fe){const[Ae,Oe,Je]=this.combineTokensIntoWords(N,fe),_t=[];for(let Et=0;Et=Ae){const _t=((Je-Ae)*fe).toFixed(2);Oe.push(`<|${_t}|>`),Oe.push([])}else Oe[Oe.length-1].push(Je);return Oe=Oe.map(Je=>typeof Je=="string"?Je:super.decode(Je,ee)),Oe.join("")}splitTokensOnUnicode(N){const ee=this.decode(N,{decode_with_timestamps:!0}),fe="�",Ae=[],Oe=[],Je=[];let _t=[],Et=[],yt=0;for(let St=0;St=this.model.tokens_to_ids.get("<|endoftext|>"),rn=St.startsWith(" "),Gt=St.trim(),mr=Et.test(Gt);if(Pr||rn||mr||Oe.length===0)Oe.push(St),Je.push(tr),_t.push(kr);else{const On=Oe.length-1;Oe[On]+=St,Je[On].push(...tr),_t[On].push(...kr)}}return[Oe,Je,_t]}mergePunctuations(N,ee,fe,Ae,Oe){const Je=structuredClone(N),_t=structuredClone(ee),Et=structuredClone(fe);let yt=Je.length-2,St=Je.length-1;for(;yt>=0;)Je[yt].startsWith(" ")&&Ae.includes(Je[yt].trim())?(Je[St]=Je[yt]+Je[St],_t[St]=(0,a.mergeArrays)(_t[yt],_t[St]),Et[St]=(0,a.mergeArrays)(Et[yt],Et[St]),Je[yt]="",_t[yt]=[],Et[yt]=[]):St=yt,--yt;for(yt=0,St=1;Sttr),_t.filter(tr=>tr.length>0),Et.filter(tr=>tr.length>0)]}}class Ca extends qt{}class Sa extends qt{}class Aa extends qt{}class Wt extends qt{constructor(N,ee){super(N,ee),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(fe=>this.languageRegex.test(fe)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(N){if(N===null)return null;const[ee,...fe]=N.trim().split(this.languageRegex);if(fe.length===0)return super._encode_text(ee);if(fe.length===2){const[Ae,Oe]=fe;return this.supported_language_codes.includes(Ae)||console.warn(`Unsupported language code "${Ae}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),(0,a.mergeArrays)([Ae],super._encode_text(Oe))}}}class ka extends qt{}class Ya extends qt{}class Xa extends qt{}class Qa extends qt{}class Us extends qt{}class Ja extends qt{constructor(N,ee){super(N,ee),this.decoder=new Lt({})}}class Ia extends qt{}class ei extends qt{}class Tr{static async from_pretrained(N,{progress_callback:ee=null,config:fe=null,cache_dir:Ae=null,local_files_only:Oe=!1,revision:Je="main",legacy:_t=null}={}){var kr;const[Et,yt]=await y(N,{progress_callback:ee,config:fe,cache_dir:Ae,local_files_only:Oe,revision:Je,legacy:_t}),St=((kr=yt.tokenizer_class)==null?void 0:kr.replace(/Fast$/,""))??"PreTrainedTokenizer";let tr=this.TOKENIZER_CLASS_MAPPING[St];return tr||(console.warn(`Unknown tokenizer class "${St}", attempting to construct from base class.`),tr=qt),new tr(Et,yt)}}we(Tr,"TOKENIZER_CLASS_MAPPING",{T5Tokenizer:pn,DistilBertTokenizer:jn,CamembertTokenizer:ot,DebertaTokenizer:Kn,DebertaV2Tokenizer:ia,BertTokenizer:sa,HerbertTokenizer:Ms,ConvBertTokenizer:Fs,RoFormerTokenizer:Ns,XLMTokenizer:At,ElectraTokenizer:Ut,MobileBertTokenizer:xs,SqueezeBertTokenizer:aa,AlbertTokenizer:Ts,GPT2Tokenizer:Ds,BartTokenizer:Ps,MBartTokenizer:Dr,MBart50Tokenizer:zn,RobertaTokenizer:en,WhisperTokenizer:oa,CodeGenTokenizer:Ca,CLIPTokenizer:Sa,SiglipTokenizer:Aa,MarianTokenizer:Wt,BloomTokenizer:ps,NllbTokenizer:Un,M2M100Tokenizer:Pa,LlamaTokenizer:Ma,CodeLlamaTokenizer:Bs,XLMRobertaTokenizer:$i,MPNetTokenizer:Ha,FalconTokenizer:Ka,GPTNeoXTokenizer:qa,EsmTokenizer:js,Wav2Vec2CTCTokenizer:ka,BlenderbotTokenizer:Ya,BlenderbotSmallTokenizer:Xa,SpeechT5Tokenizer:Qa,NougatTokenizer:Us,VitsTokenizer:Ja,Qwen2Tokenizer:Za,GemmaTokenizer:Oi,Grok1Tokenizer:zs,CohereTokenizer:Ia,MgpstrTokenizer:ei,PreTrainedTokenizer:qt})},"./src/utils/audio.js":(r,e,t)=>{t.r(e),t.d(e,{RawAudio:()=>Te,hamming:()=>w,hanning:()=>y,mel_filter_bank:()=>U,read_audio:()=>h,spectrogram:()=>j,window_function:()=>ce});var n=t("./src/utils/hub.js"),a=t("./src/utils/maths.js"),o=t("./src/utils/core.js"),u=t("./src/env.js"),d=t("?7a2c"),c=t("./src/utils/tensor.js");async function h(ie,oe){if(typeof AudioContext>"u")throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.");const re=await(await(0,n.getFile)(ie)).arrayBuffer(),ge=new AudioContext({sampleRate:oe});typeof oe>"u"&&console.warn(`No sampling rate provided, using default of ${ge.sampleRate}Hz.`);const ve=await ge.decodeAudioData(re);let me;if(ve.numberOfChannels===2){const Le=Math.sqrt(2),$e=ve.getChannelData(0),pe=ve.getChannelData(1);me=new Float32Array($e.length);for(let X=0;X2595*Math.log10(1+ie/700),kaldi:ie=>1127*Math.log(1+ie/700),slaney:(ie,oe=1e3,re=15,ge=27/Math.log(6.4))=>ie>=oe?re+Math.log(ie/oe)*ge:3*ie/200};function S(ie,oe="htk"){const re=M[oe];if(!re)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof ie=="number"?re(ie):ie.map(ge=>re(ge))}const G={htk:ie=>700*(10**(ie/2595)-1),kaldi:ie=>700*(Math.exp(ie/1127)-1),slaney:(ie,oe=1e3,re=15,ge=Math.log(6.4)/27)=>ie>=re?oe*Math.exp(ge*(ie-re)):200*ie/3};function H(ie,oe="htk"){const re=G[oe];if(!re)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof ie=="number"?re(ie):ie.map(ge=>re(ge))}function B(ie,oe){const re=Float64Array.from({length:oe.length-1},(Le,$e)=>oe[$e+1]-oe[$e]),ge=Array.from({length:ie.length},()=>new Array(oe.length));for(let Le=0;Lenew Array(ie.length));for(let Le=0;Leie+ge*me)}function U(ie,oe,re,ge,ve,me=null,Le="htk",$e=!1){if(me!==null&&me!=="slaney")throw new Error('norm must be one of null or "slaney"');const pe=S(re,Le),X=S(ge,Le),le=z(pe,X,oe+2);let ke=H(le,Le),Re;if($e){const ae=ve/(ie*2);Re=S(Float64Array.from({length:ie},(He,Ve)=>Ve*ae),Le),ke=le}else Re=z(0,Math.floor(ve/2),ie);const Xe=B(Re,ke);if(me!==null&&me==="slaney")for(let ae=0;aeve)throw Error(`frame_length (${re}) may not be larger than fft_length (${ve})`);if(Ge!==re)throw new Error(`Length of the window (${Ge}) must equal frame_length (${re})`);if(ge<=0)throw new Error("hop_length must be greater than zero");if(me===null&&le!==null)throw new Error("You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.");if(Le){if($e!=="reflect")throw new Error(`pad_mode="${$e}" not implemented yet.`);const Ze=Math.floor((ve-1)/2)+1;ie=F(ie,Ze,Ze)}let We=Math.floor(1+Math.floor((ie.length-re)/ge));he!==null&&WeWe?Ke&&(mt=Se):mt=ht=Se);const ct=new a.FFT(ve),gt=new Float64Array(ve),W=new Float64Array(ct.outputBufferSize),de=new Float32Array(st*mt);for(let Ze=0;Ze=1;--bt)gt[bt]-=X*gt[bt-1];gt[0]*=1-X}for(let bt=0;btMath.pow($e,.85));break;default:throw new Error(`Unknown window type ${oe}.`)}if(re&&(Le=Le.subarray(0,ie)),ge===null)return Le;if(ie>ge)throw new Error(`Length of the window (${ie}) may not be larger than frame_length (${ge})`);return Le}function ue(ie,oe){let re=44;const ge=new ArrayBuffer(re+ie.length*4),ve=new DataView(ge);Pe(ve,0,"RIFF"),ve.setUint32(4,36+ie.length*4,!0),Pe(ve,8,"WAVE"),Pe(ve,12,"fmt "),ve.setUint32(16,16,!0),ve.setUint16(20,3,!0),ve.setUint16(22,1,!0),ve.setUint32(24,oe,!0),ve.setUint32(28,oe*4,!0),ve.setUint16(32,4,!0),ve.setUint16(34,32,!0),Pe(ve,36,"data"),ve.setUint32(40,ie.length*4,!0);for(let me=0;me{let me=await ve.arrayBuffer();d.writeFileSync(ge,Buffer.from(me))};else throw new Error("Unable to save because filesystem is disabled in this environment.");await re(oe,this.toBlob())}}},"./src/utils/constants.js":(r,e,t)=>{t.r(e),t.d(e,{CHAT_TEMPLATE_NAME:()=>c,CONFIG_NAME:()=>a,FEATURE_EXTRACTOR_NAME:()=>o,GENERATION_CONFIG_NAME:()=>h,GITHUB_ISSUE_URL:()=>n,IMAGE_PROCESSOR_NAME:()=>u,PROCESSOR_NAME:()=>d});const n="https://github.com/huggingface/transformers.js/issues/new/choose",a="config.json",o="preprocessor_config.json",u=o,d="processor_config.json",c="chat_template.json",h="generation_config.json"},"./src/utils/core.js":(r,e,t)=>{t.r(e),t.d(e,{calculateDimensions:()=>h,calculateReflectOffset:()=>M,count:()=>B,dispatchCallback:()=>n,escapeRegExp:()=>o,isIntegralNumber:()=>d,isNullishDimension:()=>c,isTypedArray:()=>u,len:()=>H,mergeArrays:()=>y,pick:()=>G,pop:()=>_,product:()=>w,reverseDictionary:()=>a,saveBlob:()=>S});function n(z,U){z&&z(U)}function a(z){return Object.fromEntries(Object.entries(z).map(([U,F])=>[F,U]))}function o(z){return z.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function u(z){var U,F,I;return((I=(F=(U=z==null?void 0:z.prototype)==null?void 0:U.__proto__)==null?void 0:F.constructor)==null?void 0:I.name)==="TypedArray"}function d(z){return Number.isInteger(z)||typeof z=="bigint"}function c(z){return z==null||z===-1}function h(z){const U=[];let F=z;for(;Array.isArray(F);)U.push(F.length),F=F[0];return U}function _(z,U,F=void 0){const I=z[U];if(I!==void 0)return delete z[U],I;if(F===void 0)throw Error(`Key ${U} does not exist in object.`);return F}function y(...z){return Array.prototype.concat.apply([],z)}function w(...z){return z.reduce((U,F)=>U.flatMap(I=>F.map(k=>[I,k])))}function M(z,U){return Math.abs((z+U)%(2*U)-U)}function S(z,U){const F=URL.createObjectURL(U),I=document.createElement("a");I.href=F,I.download=z,I.click(),I.remove(),URL.revokeObjectURL(F)}function G(z,U){return Object.assign({},...U.map(F=>{if(z[F]!==void 0)return{[F]:z[F]}}))}function H(z){let U=0;for(const F of z)++U;return U}function B(z,U){let F=0;for(const I of z)I===U&&++F;return F}},"./src/utils/data-structures.js":(r,e,t)=>{t.r(e),t.d(e,{CharTrie:()=>a,PriorityQueue:()=>n,TokenLattice:()=>u});class n{constructor(h=(y,w)=>y>w,_=1/0){this._heap=[],this._comparator=h,this._maxSize=_}get size(){return this._heap.length}isEmpty(){return this.size===0}peek(){return this._heap[0]}push(...h){return this.extend(h)}extend(h){for(const _ of h)if(this.size0&&this._swap(0,_),this._heap.pop(),this._siftDown(),h}replace(h){const _=this.peek();return this._heap[0]=h,this._siftDown(),_}_parent(h){return(h+1>>>1)-1}_left(h){return(h<<1)+1}_right(h){return h+1<<1}_greater(h,_){return this._comparator(this._heap[h],this._heap[_])}_swap(h,_){const y=this._heap[h];this._heap[h]=this._heap[_],this._heap[_]=y}_siftUp(){this._siftUpFrom(this.size-1)}_siftUpFrom(h){for(;h>0&&this._greater(h,this._parent(h));)this._swap(h,this._parent(h)),h=this._parent(h)}_siftDown(){let h=0;for(;this._left(h)[]),this.endNodes=Array.from({length:this.len+1},()=>[]);const w=new d(this.bosTokenId,0,0,0,0),M=new d(this.eosTokenId,1,this.len,0,0);this.nodes.push(w.clone()),this.nodes.push(M.clone()),this.beginNodes[this.len].push(M),this.endNodes[0].push(w)}insert(h,_,y,w){const M=this.nodes.length,S=new d(w,M,h,_,y);this.beginNodes[h].push(S),this.endNodes[h+_].push(S),this.nodes.push(S)}viterbi(){const h=this.len;let _=0;for(;_<=h;){if(this.beginNodes[_].length==0)return[];for(let G of this.beginNodes[_]){G.prev=null;let H=0,B=null;for(let z of this.endNodes[_]){const U=z.backtraceScore+G.score;(B===null||U>H)&&(B=z.clone(),H=U)}if(B!==null)G.prev=B,G.backtraceScore=H;else return[]}++_}const y=[],M=this.beginNodes[h][0].prev;if(M===null)return[];let S=M.clone();for(;S.prev!==null;)y.push(S.clone()),S=S.clone().prev.clone();return y.reverse(),y}piece(h){return this.chars.slice(h.pos,h.pos+h.length).join("")}tokens(){return this.viterbi().map(_=>this.piece(_))}tokenIds(){return this.viterbi().map(_=>_.tokenId)}}class d{constructor(h,_,y,w,M){this.tokenId=h,this.nodeId=_,this.pos=y,this.length=w,this.score=M,this.prev=null,this.backtraceScore=0}clone(){const h=new d(this.tokenId,this.nodeId,this.pos,this.length,this.score);return h.prev=this.prev,h.backtraceScore=this.backtraceScore,h}}},"./src/utils/devices.js":(r,e,t)=>{t.r(e),t.d(e,{DEVICE_TYPES:()=>n});const n=Object.freeze({auto:"auto",gpu:"gpu",cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",webnn:"webnn","webnn-npu":"webnn-npu","webnn-gpu":"webnn-gpu","webnn-cpu":"webnn-cpu"})},"./src/utils/dtypes.js":(r,e,t)=>{t.r(e),t.d(e,{DATA_TYPES:()=>u,DEFAULT_DEVICE_DTYPE_MAPPING:()=>d,DEFAULT_DTYPE_SUFFIX_MAPPING:()=>c,isWebGpuFp16Supported:()=>o});var n=t("./src/env.js"),a=t("./src/utils/devices.js");const o=function(){let h;return async function(){if(h===void 0)if(!n.apis.IS_WEBGPU_AVAILABLE)h=!1;else try{h=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{h=!1}return h}}(),u=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),d=Object.freeze({[a.DEVICE_TYPES.wasm]:u.q8}),c=Object.freeze({[u.fp32]:"",[u.fp16]:"_fp16",[u.int8]:"_int8",[u.uint8]:"_uint8",[u.q8]:"_quantized",[u.q4]:"_q4",[u.q4f16]:"_q4f16",[u.bnb4]:"_bnb4"})},"./src/utils/generic.js":(r,e,t)=>{t.r(e),t.d(e,{Callable:()=>n});const n=class{constructor(){let a=function(...o){return a._call(...o)};return Object.setPrototypeOf(a,new.target.prototype)}_call(...a){throw Error("Must implement _call method in subclass")}}},"./src/utils/hub.js":(r,e,t)=>{t.r(e),t.d(e,{getFile:()=>_,getModelFile:()=>G,getModelJSON:()=>H});var n=t("?7a2c"),a=t("?a42a"),o=t("./src/env.js"),u=t("./src/utils/core.js");const d={txt:"text/plain",html:"text/html",css:"text/css",js:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif"};class c{constructor(F){if(this.filePath=F,this.headers=new Headers,this.exists=n.existsSync(F),this.exists){this.status=200,this.statusText="OK";let I=n.statSync(F);this.headers.set("content-length",I.size.toString()),this.updateContentType();let k=this;this.body=new ReadableStream({start($){k.arrayBuffer().then(j=>{$.enqueue(new Uint8Array(j)),$.close()})}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const F=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",d[F]??"application/octet-stream")}clone(){let F=new c(this.filePath);return F.exists=this.exists,F.status=this.status,F.statusText=this.statusText,F.headers=new Headers(this.headers),F}async arrayBuffer(){return(await n.promises.readFile(this.filePath)).buffer}async blob(){const F=await n.promises.readFile(this.filePath);return new Blob([F],{type:this.headers.get("content-type")})}async text(){return await n.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function h(U,F=null,I=null){let k;try{k=new URL(U)}catch{return!1}return!(F&&!F.includes(k.protocol)||I&&!I.includes(k.hostname))}async function _(U){var F;if(o.env.useFS&&!h(U,["http:","https:","blob:"]))return new c(U);if(typeof process<"u"&&((F=process==null?void 0:process.release)==null?void 0:F.name)==="node"){const I=!!(Ba!=null&&Ba.TESTING_REMOTELY),k=o.env.version,$=new Headers;if($.set("User-Agent",`transformers.js/${k}; is_ci/${I};`),h(U,["http:","https:"],["huggingface.co","hf.co"])){const ce=(Ba==null?void 0:Ba.HF_TOKEN)??(Ba==null?void 0:Ba.HF_ACCESS_TOKEN);ce&&$.set("Authorization",`Bearer ${ce}`)}return fetch(U,{headers:$})}else return fetch(U)}const y={400:"Bad request error occurred while trying to load file",401:"Unauthorized access to file",403:"Forbidden access to file",404:"Could not locate file",408:"Request timeout error occurred while trying to load file",500:"Internal server error error occurred while trying to load file",502:"Bad gateway error occurred while trying to load file",503:"Service unavailable error occurred while trying to load file",504:"Gateway timeout error occurred while trying to load file"};function w(U,F,I){if(!I)return null;const k=y[U]??`Error (${U}) occurred while trying to load file`;throw Error(`${k}: "${F}".`)}class M{constructor(F){this.path=F}async match(F){let I=a.join(this.path,F),k=new c(I);if(k.exists)return k}async put(F,I){const k=Buffer.from(await I.arrayBuffer());let $=a.join(this.path,F);try{await n.promises.mkdir(a.dirname($),{recursive:!0}),await n.promises.writeFile($,k)}catch(j){console.warn("An error occurred while writing the file to cache:",j)}}}async function S(U,...F){for(let I of F)try{let k=await U.match(I);if(k)return k}catch{continue}}async function G(U,F,I=!0,k={}){if(!o.env.allowLocalModels){if(k.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");if(!o.env.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}(0,u.dispatchCallback)(k.progress_callback,{status:"initiate",name:U,file:F});let $;if(!$&&o.env.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{$=await caches.open("transformers-cache")}catch(Le){console.warn("An error occurred while opening the browser cache:",Le)}}if(!$&&o.env.useFSCache&&($=new M(k.cache_dir??o.env.cacheDir)),!$&&o.env.useCustomCache){if(!o.env.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!o.env.customCache.match||!o.env.customCache.put)throw new Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");$=o.env.customCache}const j=k.revision??"main";let ce=z(U,F),ue=z(o.env.localModelPath,ce),Pe=z(o.env.remoteHost,o.env.remotePathTemplate.replaceAll("{model}",U).replaceAll("{revision}",encodeURIComponent(j)),F),Te=j==="main"?ce:z(U,j,F),ie,oe=$ instanceof M?Te:Pe,re=!1,ge;$&&(ge=await S($,ue,oe));const ve=ge!==void 0;if(ge===void 0){if(o.env.allowLocalModels)if(h(ce,["http:","https:"])){if(k.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${ce}.`);if(!o.env.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${ce}.`)}else try{ge=await _(ue),ie=ue}catch($e){console.warn(`Unable to load from local path "${ue}": "${$e}"`)}if(ge===void 0||ge.status===404){if(k.local_files_only||!o.env.allowRemoteModels){if(I)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${ue}".`);return null}if(ge=await _(Pe),ge.status!==200)return w(ge.status,Pe,I);ie=oe}re=$&&typeof Response<"u"&&ge instanceof Response&&ge.status===200}(0,u.dispatchCallback)(k.progress_callback,{status:"download",name:U,file:F});let me;return k.progress_callback?ve&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(me=new Uint8Array(await ge.arrayBuffer()),(0,u.dispatchCallback)(k.progress_callback,{status:"progress",name:U,file:F,progress:100,loaded:me.length,total:me.length})):me=await B(ge,Le=>{(0,u.dispatchCallback)(k.progress_callback,{status:"progress",name:U,file:F,...Le})}):me=new Uint8Array(await ge.arrayBuffer()),re&&ie&&await $.match(ie)===void 0&&await $.put(ie,new Response(me,{headers:ge.headers})).catch(Le=>{console.warn(`Unable to add response to browser cache: ${Le}.`)}),(0,u.dispatchCallback)(k.progress_callback,{status:"done",name:U,file:F}),me}async function H(U,F,I=!0,k={}){let $=await G(U,F,I,k);if($===null)return{};let ce=new TextDecoder("utf-8").decode($);return JSON.parse(ce)}async function B(U,F){const I=U.headers.get("Content-Length");I===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let k=parseInt(I??"0"),$=new Uint8Array(k),j=0;const ce=U.body.getReader();async function ue(){const{done:Pe,value:Te}=await ce.read();if(Pe)return;let ie=j+Te.length;if(ie>k){k=ie;let re=new Uint8Array(k);re.set($),$=re}$.set(Te,j),j=ie;const oe=j/k*100;return F({progress:oe,loaded:j,total:k}),ue()}return await ue(),$}function z(...U){return U=U.map((F,I)=>(I&&(F=F.replace(new RegExp("^/"),"")),I!==U.length-1&&(F=F.replace(new RegExp("/$"),"")),F)),U.join("/")}},"./src/utils/image.js":(r,e,t)=>{t.r(e),t.d(e,{RawImage:()=>S,load_image:()=>G});var n=t("./src/utils/core.js"),a=t("./src/utils/hub.js"),o=t("./src/env.js"),u=t("./src/utils/tensor.js"),d=t("?2b25");let c,h,_;const y=o.apis.IS_BROWSER_ENV||o.apis.IS_WEBWORKER_ENV;if(y)c=(H,B)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(H,B)},_=self.createImageBitmap,h=self.ImageData;else if(d)_=async H=>{const z=(await H.metadata()).channels,{data:U,info:F}=await H.rotate().raw().toBuffer({resolveWithObject:!0}),I=new S(new Uint8ClampedArray(U),F.width,F.height,F.channels);return z!==void 0&&z!==F.channels&&I.convert(z),I};else throw new Error("Unable to load image processing library.");const w={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},M=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class S{constructor(B,z,U,F){this.data=B,this.width=z,this.height=U,this.channels=F}get size(){return[this.width,this.height]}static async read(B){if(B instanceof S)return B;if(typeof B=="string"||B instanceof URL)return await this.fromURL(B);throw new Error(`Unsupported input type: ${typeof B}`)}static fromCanvas(B){if(!y)throw new Error("fromCanvas() is only supported in browser environments.");const U=B.getContext("2d").getImageData(0,0,B.width,B.height).data;return new S(U,B.width,B.height,4)}static async fromURL(B){const z=await(0,a.getFile)(B);if(z.status!==200)throw new Error(`Unable to read image from "${B}" (${z.status} ${z.statusText})`);const U=await z.blob();return this.fromBlob(U)}static async fromBlob(B){if(y){const z=await _(B),U=c(z.width,z.height).getContext("2d");return U.drawImage(z,0,0),new this(U.getImageData(0,0,z.width,z.height).data,z.width,z.height,4)}else{const z=d(await B.arrayBuffer());return await _(z)}}static fromTensor(B,z="CHW"){if(B.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${B.dims.length} dimensions.`);if(z==="CHW")B=B.transpose(1,2,0);else if(z!=="HWC")throw new Error(`Unsupported channel format: ${z}`);if(!(B.data instanceof Uint8ClampedArray||B.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${B.type}`);switch(B.dims[2]){case 1:case 2:case 3:case 4:return new S(B.data,B.dims[1],B.dims[0],B.dims[2]);default:throw new Error(`Unsupported number of channels: ${B.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const B=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let z=0,U=0;z=0?j=U:ue=-U,F>=0?ce=F:Pe=-F,$.drawImage(k,j,ce,B,z,ue,Pe,B,z),new S($.getImageData(0,0,B,z).data,B,z,4).convert(I)}else{let I=this.toSharp();if(U>=0&&F>=0)I=I.extract({left:Math.floor(U),top:Math.floor(F),width:B,height:z});else if(U<=0&&F<=0){const k=Math.floor(-F),$=Math.floor(-U);I=I.extend({top:k,left:$,right:B-this.width-$,bottom:z-this.height-k})}else{let k=[0,0],$=0;F<0?(k[0]=Math.floor(-F),k[1]=z-this.height-k[0]):$=Math.floor(F);let j=[0,0],ce=0;U<0?(j[0]=Math.floor(-U),j[1]=B-this.width-j[0]):ce=Math.floor(U),I=I.extend({top:k[0],bottom:k[1],left:j[0],right:j[1]}).extract({left:ce,top:$,width:B,height:z})}return await _(I)}}async toBlob(B="image/png",z=1){if(!y)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:B,quality:z})}toTensor(B="CHW"){let z=new u.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(B!=="HWC")if(B==="CHW")z=z.permute(2,0,1);else throw new Error(`Unsupported channel format: ${B}`);return z}toCanvas(){if(!y)throw new Error("toCanvas() is only supported in browser environments.");const B=this.clone().rgba(),z=c(B.width,B.height),U=new h(B.data,B.width,B.height);return z.getContext("2d").putImageData(U,0,0),z}split(){const{data:B,width:z,height:U,channels:F}=this,I=B.constructor,k=B.length/F,$=Array.from({length:F},()=>new I(k));for(let j=0;jnew S(j,z,U,1))}_update(B,z,U,F=null){return this.data=B,this.width=z,this.height=U,F!==null&&(this.channels=F),this}clone(){return new S(this.data.slice(),this.width,this.height,this.channels)}convert(B){if(this.channels===B)return this;switch(B){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(B){if(y){if(o.apis.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");const z=B.split(".").pop().toLowerCase(),U=M.get(z)??"image/png",F=await this.toBlob(U);(0,n.saveBlob)(B,F)}else{if(o.apis.IS_FS_AVAILABLE)return await this.toSharp().toFile(B);throw new Error("Unable to save the image because filesystem is disabled in this environment.")}}toSharp(){if(y)throw new Error("toSharp() is only supported in server-side environments.");return d(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}const G=S.read.bind(S)},"./src/utils/maths.js":(r,e,t)=>{t.r(e),t.d(e,{FFT:()=>G,bankers_round:()=>z,cos_sim:()=>c,dot:()=>d,dynamic_time_warping:()=>U,interpolate_data:()=>n,log_softmax:()=>u,magnitude:()=>h,max:()=>y,medianFilter:()=>H,min:()=>_,permute_data:()=>a,round:()=>B,softmax:()=>o});function n(F,[I,k,$],[j,ce],ue="bilinear",Pe=!1){const Te=ce/$,ie=j/k,oe=new F.constructor(j*ce*I),re=k*$,ge=j*ce;for(let ve=0;ve=0;--Pe)j[Pe]=Te,$[Pe]=I[k[Pe]],Te*=$[Pe];const ce=k.map((Pe,Te)=>j[k.indexOf(Te)]),ue=new F.constructor(F.length);for(let Pe=0;Pe=0;--ie)Te+=oe%I[ie]*ce[ie],oe=Math.floor(oe/I[ie]);ue[Te]=F[Pe]}return[ue,$]}function o(F){const I=y(F)[0],k=F.map(ce=>Math.exp(ce-I)),$=k.reduce((ce,ue)=>ce+ue,0);return k.map(ce=>ce/$)}function u(F){const I=y(F)[0];let k=0;for(let ce=0;cece-I-$)}function d(F,I){let k=0;for(let $=0;$I+k*k,0))}function _(F){if(F.length===0)throw Error("Array must not be empty");let I=F[0],k=0;for(let $=1;$I&&(I=F[$],k=$);return[I,k]}function w(F){return F>0&&(F&F-1)===0}class M{constructor(I){if(this.size=I|0,this.size<=1||!w(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=I<<1,this.table=new Float64Array(this.size*2);for(let $=0;$$;$<<=1)++k;this._width=k%2===0?k-1:k,this._bitrev=new Int32Array(1<>>j&3)<>>1);for(let j=0;j>>1]=I[j];return $}toComplexArray(I,k){const $=k||this.createComplexArray();for(let j=0;j<$.length;j+=2)$[j]=I[j>>>1],$[j+1]=0;return $}transform(I,k){if(I===k)throw new Error("Input and output buffers must be different");this._transform4(I,k,1)}realTransform(I,k){if(I===k)throw new Error("Input and output buffers must be different");this._realTransform4(I,k,1)}inverseTransform(I,k){if(I===k)throw new Error("Input and output buffers must be different");this._transform4(I,k,-1);for(let $=0;$>=2;ue>=2;ue>>=2){Pe=j/ue<<1;const ge=Pe>>>2;for(Te=0;Te>>1,ue>>>1)}else for(Te=0,ie=0;Te>>1,ue>>>1,$)}const re=this.table;for(ue>>=2;ue>=2;ue>>=2){Pe=j/ue<<1;const ve=Pe>>>1,me=ve>>>1,Le=me>>>1;for(Te=0;Te>>1;for(let ve=2;ve>1;++oe){const re=(oe+1-I)**2/2,ge=Math.sqrt(Te**2+ie**2)**re,ve=re*Math.atan2(ie,Te),me=2*oe;ce[me]=ge*Math.cos(ve),ce[me+1]=ge*Math.sin(ve),ue[me]=ce[me],ue[me+1]=-ce[me+1]}this._slicedChirpBuffer=ce.subarray(k,$),this._f=new M(j>>1),this._f.transform(this._chirpBuffer,ue)}_transform(I,k,$){const j=this._buffer1,ce=this._buffer2,ue=this._outBuffer1,Pe=this._outBuffer2,Te=this._chirpBuffer,ie=this._slicedChirpBuffer,oe=this._a;if($)for(let re=0;re>1,me=k[ve];j[re]=me*ie[re],j[ge]=me*ie[ge]}else for(let re=0;re=F.length&&(Te=2*(F.length-1)-Te),$[ue++]=F[Te]}$.sort(),k[ce]=$[j]}return k}function B(F,I){const k=Math.pow(10,I);return Math.round(F*k)/k}function z(F){const I=Math.round(F);return Math.abs(F)%1===.5?I%2===0?I:I-1:I}function U(F){const I=F.length,k=F[0].length,$=[I+1,k+1],j=Array.from({length:$[0]},()=>Array($[1]).fill(1/0));j[0][0]=0;const ce=Array.from({length:$[0]},()=>Array($[1]).fill(-1));for(let oe=1;oe<$[1];++oe)for(let re=1;re<$[0];++re){const ge=j[re-1][oe-1],ve=j[re-1][oe],me=j[re][oe-1];let Le,$e;ge0||Pe>0;)switch(Te.push(ue-1),ie.push(Pe-1),ce[ue][Pe]){case 0:--ue,--Pe;break;case 1:--ue;break;case 2:--Pe;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${ue}, ${Pe}]. Please file a bug report.`)}return Te.reverse(),ie.reverse(),[Te,ie]}},"./src/utils/tensor.js":(r,e,t)=>{t.r(e),t.d(e,{Tensor:()=>d,cat:()=>k,full:()=>ie,full_like:()=>oe,interpolate:()=>_,interpolate_4d:()=>y,layer_norm:()=>z,matmul:()=>w,mean:()=>ue,mean_pooling:()=>B,ones:()=>re,ones_like:()=>ge,permute:()=>h,quantize_embeddings:()=>$e,rand:()=>Le,rfft:()=>M,slice:()=>H,stack:()=>$,std_mean:()=>ce,topk:()=>S,zeros:()=>ve,zeros_like:()=>me});var n=t("./src/utils/maths.js"),a=t("./src/backends/onnx.js"),o=t("./src/ops/registry.js");const u=Object.freeze({float32:Float32Array,float16:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array,uint4:Uint8Array,int4:Int8Array});class d{constructor(...X){we(this,"ort_tensor");return(0,a.isONNXTensor)(X[0])?this.ort_tensor=X[0]:this.ort_tensor=new a.Tensor(X[0],X[1],X[2]),new Proxy(this,{get:(le,ke)=>{if(typeof ke=="string"){let Re=Number(ke);if(Number.isInteger(Re))return le._getitem(Re)}return le[ke]},set:(le,ke,Re)=>le[ke]=Re})}get dims(){return this.ort_tensor.dims}set dims(X){this.ort_tensor.dims=X}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}get location(){return this.ort_tensor.location}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){const[X,...le]=this.dims;if(le.length>0){const ke=le.reduce((Re,Xe)=>Re*Xe);for(let Re=0;Re0){const Re=ke.reduce((Xe,ae)=>Xe*ae);return this._subarray(X,Re,ke)}else return new d(this.type,[this.data[X]],ke)}indexOf(X){const le=this.data;for(let ke=0;keqe)throw new Error(`Invalid slice: ${Se}`);const Ge=[Math.max(Ke,0),Math.min(qe,this.dims[he])];ke.push(Ge),le.push(Ge[1]-Ge[0])}else throw new Error(`Invalid slice: ${Se}`)}const Re=ke.map(([he,Se])=>Se-he),Xe=Re.reduce((he,Se)=>he*Se),ae=this.data,He=new ae.constructor(Xe),Ve=this.stride();for(let he=0;he=0;--Ke){const Ge=Re[Ke];Se+=(qe%Ge+ke[Ke][0])*Ve[Ke],qe=Math.floor(qe/Ge)}He[he]=ae[Se]}return new d(this.type,He,le)}permute(...X){return h(this,X)}transpose(...X){return this.permute(...X)}sum(X=null,le=!1){return this.norm(1,X,le)}norm(X="fro",le=null,ke=!1){if(X==="fro")X=2;else if(typeof X=="string")throw Error(`Unsupported norm: ${X}`);const Re=this.data,Xe=(he,Se)=>he+Se**X;if(le===null){const he=Re.reduce(Xe,0)**(1/X);return new d(this.type,[he],[])}const[ae,He,Ve]=j(Xe,this,le,ke);if(X!==1)for(let he=0;he=0;--Ve){const Ke=this.dims[Ve];if(Ve!==le){const qe=he%Ke;He+=qe*Se,Se*=this.dims[Ve]}he=Math.floor(he/Ke)}Re[ae]/=Xe[He]}return this}normalize(X=2,le=1){return this.clone().normalize_(X,le)}stride(){return Pe(this.dims)}squeeze(X=null){return new d(this.type,this.data,U(this.dims,X))}squeeze_(X=null){return this.dims=U(this.dims,X),this}unsqueeze(X=null){return new d(this.type,this.data,F(this.dims,X))}unsqueeze_(X=null){return this.dims=F(this.dims,X),this}flatten_(X=0,le=-1){le=(le+this.dims.length)%this.dims.length;let ke=this.dims.slice(0,X),Re=this.dims.slice(X,le+1),Xe=this.dims.slice(le+1);return this.dims=[...ke,Re.reduce((ae,He)=>ae*He,1),...Xe],this}flatten(X=0,le=-1){return this.clone().flatten_(X,le)}view(...X){let le=-1;for(let Re=0;ReHe!==le?Xe*ae:Xe,1);X[le]=ke.length/Re}return new d(this.type,ke,X)}neg_(){const X=this.data;for(let le=0;leX?1:0;return new d("bool",le,this.dims)}lt(X){const le=new Uint8Array(this.data.length),ke=this.data;for(let Re=0;ReMath.min(ae,He),this,X,le,1/0);return new d(ke,Re,Xe)}max(X=null,le=!1){if(X===null){const ae=(0,n.max)(this.data)[0];return new d(this.type,[ae],[])}const[ke,Re,Xe]=j((ae,He)=>Math.max(ae,He),this,X,le,-1/0);return new d(ke,Re,Xe)}argmin(X=null,le=!1){if(X!==null)throw new Error("`dim !== null` not yet implemented.");const ke=(0,n.min)(this.data)[1];return new d("int64",[BigInt(ke)],[])}argmax(X=null,le=!1){if(X!==null)throw new Error("`dim !== null` not yet implemented.");const ke=(0,n.max)(this.data)[1];return new d("int64",[BigInt(ke)],[])}to(X){if(this.type===X)return this;if(!u.hasOwnProperty(X))throw new Error(`Unsupported type: ${X}`);let le;const ke=["int64","uint64"].includes(this.type),Re=["int64","uint64"].includes(X);return ke&&!Re?le=Number:!ke&&Re&&(le=BigInt),new d(X,u[X].from(this.data,le),this.dims)}}function c(pe,X){const le=pe.length,ke=X.reduce((Xe,ae)=>Xe*ae);if(le!==ke)throw Error(`cannot reshape array of size ${le} into shape (${X})`);let Re=pe;for(let Xe=X.length-1;Xe>=0;Xe--)Re=Re.reduce((ae,He)=>{let Ve=ae[ae.length-1];return Ve.lengthnew d("int64",pe,[pe.length]);async function H(pe,X,le,ke,Re){return await(await o.TensorOpRegistry.slice)({x:pe,s:G(X),e:G(le),a:G(ke),t:G(Re??new Array(ke.length).fill(1))})}function B(pe,X){const le=pe.data,ke=X.data,Re=[pe.dims[0],pe.dims[2]],Xe=new le.constructor(Re[0]*Re[1]),[ae,He,Ve]=pe.dims;let he=0;for(let Se=0;Sele!==1):typeof X=="number"?pe[X]===1&&pe.splice(X,1):Array.isArray(X)&&(pe=pe.filter((le,ke)=>le!==1||!X.includes(ke))),pe}function F(pe,X){return X=I(X,pe.length+1),pe=pe.slice(),pe.splice(X,0,1),pe}function I(pe,X,le=null,ke=!0){if(ke&&(pe<-X||pe>=X))throw new Error(`IndexError: index ${pe} is out of bounds for dimension${le===null?"":" "+le} with size ${X}`);return pe<0&&(pe=(pe%X+X)%X),pe}function k(pe,X=0){X=I(X,pe[0].dims.length);const le=pe[0].dims.slice();le[X]=pe.reduce((ae,He)=>ae+He.dims[X],0);const ke=le.reduce((ae,He)=>ae*He,1),Re=new pe[0].data.constructor(ke),Xe=pe[0].type;if(X===0){let ae=0;for(const He of pe){const Ve=He.data;Re.set(Ve,ae),ae+=Ve.length}}else{let ae=0;for(let He=0;He=0;--qe){const st=he[qe];let ht=Ge%st;qe===X&&(ht+=ae),Ke+=ht*We,We*=le[qe],Ge=Math.floor(Ge/st)}Re[Ke]=Ve[Se]}ae+=he[X]}}return new d(Xe,Re,le)}function $(pe,X=0){return k(pe.map(le=>le.unsqueeze(X)),X)}function j(pe,X,le=null,ke=!1,Re=null){const Xe=X.data,ae=X.dims;le=I(le,ae.length);const He=ae.slice();He[le]=1;const Ve=new Xe.constructor(Xe.length/ae[le]);Re!==null&&Ve.fill(Re);for(let he=0;he=0;--Ke){const We=ae[Ke];if(Ke!==le){const st=qe%We;Se+=st*Ge,Ge*=He[Ke]}qe=Math.floor(qe/We)}Ve[Se]=pe(Ve[Se],Xe[he],he,Se)}return ke||He.splice(le,1),[X.type,Ve,He]}function ce(pe,X=null,le=1,ke=!1){const Re=pe.data,Xe=pe.dims;if(X===null){const Ge=Re.reduce((mt,ct)=>mt+ct,0)/Re.length,We=Math.sqrt(Re.reduce((mt,ct)=>mt+(ct-Ge)**2,0)/(Re.length-le)),st=new d(pe.type,[Ge],[]);return[new d(pe.type,[We],[]),st]}X=I(X,Xe.length);const ae=ue(pe,X,ke),He=ae.data,[Ve,he,Se]=j((qe,Ge,We,st)=>qe+(Ge-He[st])**2,pe,X,ke);for(let qe=0;qehe+Se,0);return new d(pe.type,[Ve/Re.length],[])}X=I(X,ke.length);const[Xe,ae,He]=j((Ve,he)=>Ve+he,pe,X,le);if(ke[X]!==1)for(let Ve=0;Ve=0;--le)X[le]=ke,ke*=pe[le];return X}function Te(pe,X,le,ke){const Re=pe.reduce((Xe,ae)=>Xe*ae,1);return new d(le,new ke(Re).fill(X),pe)}function ie(pe,X){let le,ke;if(typeof X=="number")le="float32",ke=Float32Array;else if(typeof X=="bigint")le="int64",ke=BigInt64Array;else if(typeof X=="boolean")le="bool",ke=Uint8Array;else throw new Error(`Unsupported data type: ${typeof X}`);return Te(pe,X,le,ke)}function oe(pe,X){return ie(pe.dims,X)}function re(pe){return Te(pe,1n,"int64",BigInt64Array)}function ge(pe){return re(pe.dims)}function ve(pe){return Te(pe,0n,"int64",BigInt64Array)}function me(pe){return ve(pe.dims)}function Le(pe){const X=pe.reduce((le,ke)=>le*ke,1);return new d("float32",Float32Array.from({length:X},()=>Math.random()),pe)}function $e(pe,X){if(pe.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(pe.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(X))throw new Error("The precision must be either 'binary' or 'ubinary'");const le=X==="binary",ke=le?"int8":"uint8",Re=le?Int8Array:Uint8Array,Xe=pe.data,ae=new Re(Xe.length/8);for(let He=0;He0?1:0,he=Math.floor(He/8),Se=He%8;ae[he]|=Ve<<7-Se,le&&Se===0&&(ae[he]-=128)}return new d(ke,ae,[pe.dims[0],pe.dims[1]/8])}}},Dy={};function Lr(r){var e=Dy[r];if(e!==void 0)return e.exports;var t=Dy[r]={exports:{}};return tw[r](t,t.exports,Lr),t.exports}Lr.m=tw;(()=>{var r=Object.getPrototypeOf?t=>Object.getPrototypeOf(t):t=>t.__proto__,e;Lr.t=function(t,n){if(n&1&&(t=this(t)),n&8||typeof t=="object"&&t&&(n&4&&t.__esModule||n&16&&typeof t.then=="function"))return t;var a=Object.create(null);Lr.r(a);var o={};e=e||[null,r({}),r([]),r(r)];for(var u=n&2&&t;typeof u=="object"&&!~e.indexOf(u);u=r(u))Object.getOwnPropertyNames(u).forEach(d=>o[d]=()=>t[d]);return o.default=()=>t,Lr.d(a,o),a}})();Lr.d=(r,e)=>{for(var t in e)Lr.o(e,t)&&!Lr.o(r,t)&&Object.defineProperty(r,t,{enumerable:!0,get:e[t]})};Lr.o=(r,e)=>Object.prototype.hasOwnProperty.call(r,e);Lr.r=r=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(r,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(r,"__esModule",{value:!0})};(()=>{var r;if(typeof import.meta.url=="string"&&(r=import.meta.url),!r)throw new Error("Automatic publicPath is not supported in this browser");r=r.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),Lr.p=r})();Lr.b=new URL("./",import.meta.url);var T={};(()=>{/*!*****************************!*\ !*** ./src/transformers.js ***! \*****************************/Lr.r(T),Lr.d(T,{ASTFeatureExtractor:()=>_.ASTFeatureExtractor,ASTForAudioClassification:()=>t.ASTForAudioClassification,ASTModel:()=>t.ASTModel,ASTPreTrainedModel:()=>t.ASTPreTrainedModel,AlbertForMaskedLM:()=>t.AlbertForMaskedLM,AlbertForQuestionAnswering:()=>t.AlbertForQuestionAnswering,AlbertForSequenceClassification:()=>t.AlbertForSequenceClassification,AlbertModel:()=>t.AlbertModel,AlbertPreTrainedModel:()=>t.AlbertPreTrainedModel,AlbertTokenizer:()=>n.AlbertTokenizer,AudioClassificationPipeline:()=>e.AudioClassificationPipeline,AutoConfig:()=>a.AutoConfig,AutoFeatureExtractor:()=>y.AutoFeatureExtractor,AutoImageProcessor:()=>S.AutoImageProcessor,AutoModel:()=>t.AutoModel,AutoModelForAudioClassification:()=>t.AutoModelForAudioClassification,AutoModelForAudioFrameClassification:()=>t.AutoModelForAudioFrameClassification,AutoModelForCTC:()=>t.AutoModelForCTC,AutoModelForCausalLM:()=>t.AutoModelForCausalLM,AutoModelForDepthEstimation:()=>t.AutoModelForDepthEstimation,AutoModelForDocumentQuestionAnswering:()=>t.AutoModelForDocumentQuestionAnswering,AutoModelForImageClassification:()=>t.AutoModelForImageClassification,AutoModelForImageFeatureExtraction:()=>t.AutoModelForImageFeatureExtraction,AutoModelForImageMatting:()=>t.AutoModelForImageMatting,AutoModelForImageSegmentation:()=>t.AutoModelForImageSegmentation,AutoModelForImageToImage:()=>t.AutoModelForImageToImage,AutoModelForMaskGeneration:()=>t.AutoModelForMaskGeneration,AutoModelForMaskedLM:()=>t.AutoModelForMaskedLM,AutoModelForNormalEstimation:()=>t.AutoModelForNormalEstimation,AutoModelForObjectDetection:()=>t.AutoModelForObjectDetection,AutoModelForPoseEstimation:()=>t.AutoModelForPoseEstimation,AutoModelForQuestionAnswering:()=>t.AutoModelForQuestionAnswering,AutoModelForSemanticSegmentation:()=>t.AutoModelForSemanticSegmentation,AutoModelForSeq2SeqLM:()=>t.AutoModelForSeq2SeqLM,AutoModelForSequenceClassification:()=>t.AutoModelForSequenceClassification,AutoModelForSpeechSeq2Seq:()=>t.AutoModelForSpeechSeq2Seq,AutoModelForTextToSpectrogram:()=>t.AutoModelForTextToSpectrogram,AutoModelForTextToWaveform:()=>t.AutoModelForTextToWaveform,AutoModelForTokenClassification:()=>t.AutoModelForTokenClassification,AutoModelForUniversalSegmentation:()=>t.AutoModelForUniversalSegmentation,AutoModelForVision2Seq:()=>t.AutoModelForVision2Seq,AutoModelForXVector:()=>t.AutoModelForXVector,AutoModelForZeroShotObjectDetection:()=>t.AutoModelForZeroShotObjectDetection,AutoProcessor:()=>B.AutoProcessor,AutoTokenizer:()=>n.AutoTokenizer,AutomaticSpeechRecognitionPipeline:()=>e.AutomaticSpeechRecognitionPipeline,BartForConditionalGeneration:()=>t.BartForConditionalGeneration,BartForSequenceClassification:()=>t.BartForSequenceClassification,BartModel:()=>t.BartModel,BartPretrainedModel:()=>t.BartPretrainedModel,BartTokenizer:()=>n.BartTokenizer,BaseModelOutput:()=>t.BaseModelOutput,BaseStreamer:()=>z.BaseStreamer,BeitFeatureExtractor:()=>M.BeitFeatureExtractor,BeitForImageClassification:()=>t.BeitForImageClassification,BeitModel:()=>t.BeitModel,BeitPreTrainedModel:()=>t.BeitPreTrainedModel,BertForMaskedLM:()=>t.BertForMaskedLM,BertForQuestionAnswering:()=>t.BertForQuestionAnswering,BertForSequenceClassification:()=>t.BertForSequenceClassification,BertForTokenClassification:()=>t.BertForTokenClassification,BertModel:()=>t.BertModel,BertPreTrainedModel:()=>t.BertPreTrainedModel,BertTokenizer:()=>n.BertTokenizer,BitImageProcessor:()=>M.BitImageProcessor,BlenderbotForConditionalGeneration:()=>t.BlenderbotForConditionalGeneration,BlenderbotModel:()=>t.BlenderbotModel,BlenderbotPreTrainedModel:()=>t.BlenderbotPreTrainedModel,BlenderbotSmallForConditionalGeneration:()=>t.BlenderbotSmallForConditionalGeneration,BlenderbotSmallModel:()=>t.BlenderbotSmallModel,BlenderbotSmallPreTrainedModel:()=>t.BlenderbotSmallPreTrainedModel,BlenderbotSmallTokenizer:()=>n.BlenderbotSmallTokenizer,BlenderbotTokenizer:()=>n.BlenderbotTokenizer,BloomForCausalLM:()=>t.BloomForCausalLM,BloomModel:()=>t.BloomModel,BloomPreTrainedModel:()=>t.BloomPreTrainedModel,BloomTokenizer:()=>n.BloomTokenizer,CLIPFeatureExtractor:()=>M.CLIPFeatureExtractor,CLIPImageProcessor:()=>M.CLIPImageProcessor,CLIPModel:()=>t.CLIPModel,CLIPPreTrainedModel:()=>t.CLIPPreTrainedModel,CLIPSegForImageSegmentation:()=>t.CLIPSegForImageSegmentation,CLIPSegModel:()=>t.CLIPSegModel,CLIPSegPreTrainedModel:()=>t.CLIPSegPreTrainedModel,CLIPTextModel:()=>t.CLIPTextModel,CLIPTextModelWithProjection:()=>t.CLIPTextModelWithProjection,CLIPTokenizer:()=>n.CLIPTokenizer,CLIPVisionModel:()=>t.CLIPVisionModel,CLIPVisionModelWithProjection:()=>t.CLIPVisionModelWithProjection,CamembertForMaskedLM:()=>t.CamembertForMaskedLM,CamembertForQuestionAnswering:()=>t.CamembertForQuestionAnswering,CamembertForSequenceClassification:()=>t.CamembertForSequenceClassification,CamembertForTokenClassification:()=>t.CamembertForTokenClassification,CamembertModel:()=>t.CamembertModel,CamembertPreTrainedModel:()=>t.CamembertPreTrainedModel,CamembertTokenizer:()=>n.CamembertTokenizer,CausalLMOutput:()=>t.CausalLMOutput,CausalLMOutputWithPast:()=>t.CausalLMOutputWithPast,ChineseCLIPFeatureExtractor:()=>M.ChineseCLIPFeatureExtractor,ChineseCLIPModel:()=>t.ChineseCLIPModel,ChineseCLIPPreTrainedModel:()=>t.ChineseCLIPPreTrainedModel,ClapAudioModelWithProjection:()=>t.ClapAudioModelWithProjection,ClapFeatureExtractor:()=>_.ClapFeatureExtractor,ClapModel:()=>t.ClapModel,ClapPreTrainedModel:()=>t.ClapPreTrainedModel,ClapTextModelWithProjection:()=>t.ClapTextModelWithProjection,ClassifierFreeGuidanceLogitsProcessor:()=>F.ClassifierFreeGuidanceLogitsProcessor,CodeGenForCausalLM:()=>t.CodeGenForCausalLM,CodeGenModel:()=>t.CodeGenModel,CodeGenPreTrainedModel:()=>t.CodeGenPreTrainedModel,CodeGenTokenizer:()=>n.CodeGenTokenizer,CodeLlamaTokenizer:()=>n.CodeLlamaTokenizer,CohereForCausalLM:()=>t.CohereForCausalLM,CohereModel:()=>t.CohereModel,CoherePreTrainedModel:()=>t.CoherePreTrainedModel,CohereTokenizer:()=>n.CohereTokenizer,ConvBertForMaskedLM:()=>t.ConvBertForMaskedLM,ConvBertForQuestionAnswering:()=>t.ConvBertForQuestionAnswering,ConvBertForSequenceClassification:()=>t.ConvBertForSequenceClassification,ConvBertForTokenClassification:()=>t.ConvBertForTokenClassification,ConvBertModel:()=>t.ConvBertModel,ConvBertPreTrainedModel:()=>t.ConvBertPreTrainedModel,ConvBertTokenizer:()=>n.ConvBertTokenizer,ConvNextFeatureExtractor:()=>M.ConvNextFeatureExtractor,ConvNextForImageClassification:()=>t.ConvNextForImageClassification,ConvNextImageProcessor:()=>M.ConvNextImageProcessor,ConvNextModel:()=>t.ConvNextModel,ConvNextPreTrainedModel:()=>t.ConvNextPreTrainedModel,ConvNextV2ForImageClassification:()=>t.ConvNextV2ForImageClassification,ConvNextV2Model:()=>t.ConvNextV2Model,ConvNextV2PreTrainedModel:()=>t.ConvNextV2PreTrainedModel,DPTFeatureExtractor:()=>M.DPTFeatureExtractor,DPTForDepthEstimation:()=>t.DPTForDepthEstimation,DPTImageProcessor:()=>M.DPTImageProcessor,DPTModel:()=>t.DPTModel,DPTPreTrainedModel:()=>t.DPTPreTrainedModel,DebertaForMaskedLM:()=>t.DebertaForMaskedLM,DebertaForQuestionAnswering:()=>t.DebertaForQuestionAnswering,DebertaForSequenceClassification:()=>t.DebertaForSequenceClassification,DebertaForTokenClassification:()=>t.DebertaForTokenClassification,DebertaModel:()=>t.DebertaModel,DebertaPreTrainedModel:()=>t.DebertaPreTrainedModel,DebertaTokenizer:()=>n.DebertaTokenizer,DebertaV2ForMaskedLM:()=>t.DebertaV2ForMaskedLM,DebertaV2ForQuestionAnswering:()=>t.DebertaV2ForQuestionAnswering,DebertaV2ForSequenceClassification:()=>t.DebertaV2ForSequenceClassification,DebertaV2ForTokenClassification:()=>t.DebertaV2ForTokenClassification,DebertaV2Model:()=>t.DebertaV2Model,DebertaV2PreTrainedModel:()=>t.DebertaV2PreTrainedModel,DebertaV2Tokenizer:()=>n.DebertaV2Tokenizer,DecisionTransformerModel:()=>t.DecisionTransformerModel,DecisionTransformerPreTrainedModel:()=>t.DecisionTransformerPreTrainedModel,DeiTFeatureExtractor:()=>M.DeiTFeatureExtractor,DeiTForImageClassification:()=>t.DeiTForImageClassification,DeiTImageProcessor:()=>M.DeiTImageProcessor,DeiTModel:()=>t.DeiTModel,DeiTPreTrainedModel:()=>t.DeiTPreTrainedModel,DepthAnythingForDepthEstimation:()=>t.DepthAnythingForDepthEstimation,DepthAnythingPreTrainedModel:()=>t.DepthAnythingPreTrainedModel,DepthEstimationPipeline:()=>e.DepthEstimationPipeline,DepthProForDepthEstimation:()=>t.DepthProForDepthEstimation,DepthProPreTrainedModel:()=>t.DepthProPreTrainedModel,DetrFeatureExtractor:()=>M.DetrFeatureExtractor,DetrForObjectDetection:()=>t.DetrForObjectDetection,DetrForSegmentation:()=>t.DetrForSegmentation,DetrImageProcessor:()=>M.DetrImageProcessor,DetrModel:()=>t.DetrModel,DetrObjectDetectionOutput:()=>t.DetrObjectDetectionOutput,DetrPreTrainedModel:()=>t.DetrPreTrainedModel,DetrSegmentationOutput:()=>t.DetrSegmentationOutput,Dinov2ForImageClassification:()=>t.Dinov2ForImageClassification,Dinov2Model:()=>t.Dinov2Model,Dinov2PreTrainedModel:()=>t.Dinov2PreTrainedModel,Dinov2WithRegistersForImageClassification:()=>t.Dinov2WithRegistersForImageClassification,Dinov2WithRegistersModel:()=>t.Dinov2WithRegistersModel,Dinov2WithRegistersPreTrainedModel:()=>t.Dinov2WithRegistersPreTrainedModel,DistilBertForMaskedLM:()=>t.DistilBertForMaskedLM,DistilBertForQuestionAnswering:()=>t.DistilBertForQuestionAnswering,DistilBertForSequenceClassification:()=>t.DistilBertForSequenceClassification,DistilBertForTokenClassification:()=>t.DistilBertForTokenClassification,DistilBertModel:()=>t.DistilBertModel,DistilBertPreTrainedModel:()=>t.DistilBertPreTrainedModel,DistilBertTokenizer:()=>n.DistilBertTokenizer,DocumentQuestionAnsweringPipeline:()=>e.DocumentQuestionAnsweringPipeline,DonutFeatureExtractor:()=>M.DonutFeatureExtractor,DonutImageProcessor:()=>M.DonutImageProcessor,DonutSwinModel:()=>t.DonutSwinModel,DonutSwinPreTrainedModel:()=>t.DonutSwinPreTrainedModel,EfficientNetForImageClassification:()=>t.EfficientNetForImageClassification,EfficientNetImageProcessor:()=>M.EfficientNetImageProcessor,EfficientNetModel:()=>t.EfficientNetModel,EfficientNetPreTrainedModel:()=>t.EfficientNetPreTrainedModel,ElectraForMaskedLM:()=>t.ElectraForMaskedLM,ElectraForQuestionAnswering:()=>t.ElectraForQuestionAnswering,ElectraForSequenceClassification:()=>t.ElectraForSequenceClassification,ElectraForTokenClassification:()=>t.ElectraForTokenClassification,ElectraModel:()=>t.ElectraModel,ElectraPreTrainedModel:()=>t.ElectraPreTrainedModel,ElectraTokenizer:()=>n.ElectraTokenizer,EosTokenCriteria:()=>U.EosTokenCriteria,EsmForMaskedLM:()=>t.EsmForMaskedLM,EsmForSequenceClassification:()=>t.EsmForSequenceClassification,EsmForTokenClassification:()=>t.EsmForTokenClassification,EsmModel:()=>t.EsmModel,EsmPreTrainedModel:()=>t.EsmPreTrainedModel,EsmTokenizer:()=>n.EsmTokenizer,ExaoneForCausalLM:()=>t.ExaoneForCausalLM,ExaoneModel:()=>t.ExaoneModel,ExaonePreTrainedModel:()=>t.ExaonePreTrainedModel,FFT:()=>c.FFT,FalconForCausalLM:()=>t.FalconForCausalLM,FalconModel:()=>t.FalconModel,FalconPreTrainedModel:()=>t.FalconPreTrainedModel,FalconTokenizer:()=>n.FalconTokenizer,FastViTForImageClassification:()=>t.FastViTForImageClassification,FastViTModel:()=>t.FastViTModel,FastViTPreTrainedModel:()=>t.FastViTPreTrainedModel,FeatureExtractionPipeline:()=>e.FeatureExtractionPipeline,FeatureExtractor:()=>h.FeatureExtractor,FillMaskPipeline:()=>e.FillMaskPipeline,Florence2ForConditionalGeneration:()=>t.Florence2ForConditionalGeneration,Florence2PreTrainedModel:()=>t.Florence2PreTrainedModel,Florence2Processor:()=>H.Florence2Processor,ForcedBOSTokenLogitsProcessor:()=>F.ForcedBOSTokenLogitsProcessor,ForcedEOSTokenLogitsProcessor:()=>F.ForcedEOSTokenLogitsProcessor,GLPNFeatureExtractor:()=>M.GLPNFeatureExtractor,GLPNForDepthEstimation:()=>t.GLPNForDepthEstimation,GLPNModel:()=>t.GLPNModel,GLPNPreTrainedModel:()=>t.GLPNPreTrainedModel,GPT2LMHeadModel:()=>t.GPT2LMHeadModel,GPT2Model:()=>t.GPT2Model,GPT2PreTrainedModel:()=>t.GPT2PreTrainedModel,GPT2Tokenizer:()=>n.GPT2Tokenizer,GPTBigCodeForCausalLM:()=>t.GPTBigCodeForCausalLM,GPTBigCodeModel:()=>t.GPTBigCodeModel,GPTBigCodePreTrainedModel:()=>t.GPTBigCodePreTrainedModel,GPTJForCausalLM:()=>t.GPTJForCausalLM,GPTJModel:()=>t.GPTJModel,GPTJPreTrainedModel:()=>t.GPTJPreTrainedModel,GPTNeoForCausalLM:()=>t.GPTNeoForCausalLM,GPTNeoModel:()=>t.GPTNeoModel,GPTNeoPreTrainedModel:()=>t.GPTNeoPreTrainedModel,GPTNeoXForCausalLM:()=>t.GPTNeoXForCausalLM,GPTNeoXModel:()=>t.GPTNeoXModel,GPTNeoXPreTrainedModel:()=>t.GPTNeoXPreTrainedModel,GPTNeoXTokenizer:()=>n.GPTNeoXTokenizer,Gemma2ForCausalLM:()=>t.Gemma2ForCausalLM,Gemma2Model:()=>t.Gemma2Model,Gemma2PreTrainedModel:()=>t.Gemma2PreTrainedModel,GemmaForCausalLM:()=>t.GemmaForCausalLM,GemmaModel:()=>t.GemmaModel,GemmaPreTrainedModel:()=>t.GemmaPreTrainedModel,GemmaTokenizer:()=>n.GemmaTokenizer,GraniteForCausalLM:()=>t.GraniteForCausalLM,GraniteModel:()=>t.GraniteModel,GranitePreTrainedModel:()=>t.GranitePreTrainedModel,Grok1Tokenizer:()=>n.Grok1Tokenizer,GroundingDinoForObjectDetection:()=>t.GroundingDinoForObjectDetection,GroundingDinoImageProcessor:()=>M.GroundingDinoImageProcessor,GroundingDinoPreTrainedModel:()=>t.GroundingDinoPreTrainedModel,GroundingDinoProcessor:()=>H.GroundingDinoProcessor,GroupViTModel:()=>t.GroupViTModel,GroupViTPreTrainedModel:()=>t.GroupViTPreTrainedModel,HerbertTokenizer:()=>n.HerbertTokenizer,HieraForImageClassification:()=>t.HieraForImageClassification,HieraModel:()=>t.HieraModel,HieraPreTrainedModel:()=>t.HieraPreTrainedModel,HubertForCTC:()=>t.HubertForCTC,HubertForSequenceClassification:()=>t.HubertForSequenceClassification,HubertModel:()=>t.HubertModel,HubertPreTrainedModel:()=>t.HubertPreTrainedModel,IJepaForImageClassification:()=>t.IJepaForImageClassification,IJepaModel:()=>t.IJepaModel,IJepaPreTrainedModel:()=>t.IJepaPreTrainedModel,Idefics3ForConditionalGeneration:()=>t.Idefics3ForConditionalGeneration,Idefics3ImageProcessor:()=>M.Idefics3ImageProcessor,Idefics3PreTrainedModel:()=>t.Idefics3PreTrainedModel,Idefics3Processor:()=>H.Idefics3Processor,ImageClassificationPipeline:()=>e.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>e.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>_.ImageFeatureExtractor,ImageMattingOutput:()=>t.ImageMattingOutput,ImageProcessor:()=>w.ImageProcessor,ImageSegmentationPipeline:()=>e.ImageSegmentationPipeline,ImageToImagePipeline:()=>e.ImageToImagePipeline,ImageToTextPipeline:()=>e.ImageToTextPipeline,InterruptableStoppingCriteria:()=>U.InterruptableStoppingCriteria,JAISLMHeadModel:()=>t.JAISLMHeadModel,JAISModel:()=>t.JAISModel,JAISPreTrainedModel:()=>t.JAISPreTrainedModel,JinaCLIPImageProcessor:()=>M.JinaCLIPImageProcessor,JinaCLIPModel:()=>t.JinaCLIPModel,JinaCLIPPreTrainedModel:()=>t.JinaCLIPPreTrainedModel,JinaCLIPProcessor:()=>H.JinaCLIPProcessor,JinaCLIPTextModel:()=>t.JinaCLIPTextModel,JinaCLIPVisionModel:()=>t.JinaCLIPVisionModel,LlamaForCausalLM:()=>t.LlamaForCausalLM,LlamaModel:()=>t.LlamaModel,LlamaPreTrainedModel:()=>t.LlamaPreTrainedModel,LlamaTokenizer:()=>n.LlamaTokenizer,LlavaForConditionalGeneration:()=>t.LlavaForConditionalGeneration,LlavaOnevisionForConditionalGeneration:()=>t.LlavaOnevisionForConditionalGeneration,LlavaOnevisionImageProcessor:()=>M.LlavaOnevisionImageProcessor,LlavaPreTrainedModel:()=>t.LlavaPreTrainedModel,LogitsProcessor:()=>F.LogitsProcessor,LogitsProcessorList:()=>F.LogitsProcessorList,LogitsWarper:()=>F.LogitsWarper,LongT5ForConditionalGeneration:()=>t.LongT5ForConditionalGeneration,LongT5Model:()=>t.LongT5Model,LongT5PreTrainedModel:()=>t.LongT5PreTrainedModel,M2M100ForConditionalGeneration:()=>t.M2M100ForConditionalGeneration,M2M100Model:()=>t.M2M100Model,M2M100PreTrainedModel:()=>t.M2M100PreTrainedModel,M2M100Tokenizer:()=>n.M2M100Tokenizer,MBart50Tokenizer:()=>n.MBart50Tokenizer,MBartForCausalLM:()=>t.MBartForCausalLM,MBartForConditionalGeneration:()=>t.MBartForConditionalGeneration,MBartForSequenceClassification:()=>t.MBartForSequenceClassification,MBartModel:()=>t.MBartModel,MBartPreTrainedModel:()=>t.MBartPreTrainedModel,MBartTokenizer:()=>n.MBartTokenizer,MPNetForMaskedLM:()=>t.MPNetForMaskedLM,MPNetForQuestionAnswering:()=>t.MPNetForQuestionAnswering,MPNetForSequenceClassification:()=>t.MPNetForSequenceClassification,MPNetForTokenClassification:()=>t.MPNetForTokenClassification,MPNetModel:()=>t.MPNetModel,MPNetPreTrainedModel:()=>t.MPNetPreTrainedModel,MPNetTokenizer:()=>n.MPNetTokenizer,MT5ForConditionalGeneration:()=>t.MT5ForConditionalGeneration,MT5Model:()=>t.MT5Model,MT5PreTrainedModel:()=>t.MT5PreTrainedModel,MarianMTModel:()=>t.MarianMTModel,MarianModel:()=>t.MarianModel,MarianPreTrainedModel:()=>t.MarianPreTrainedModel,MarianTokenizer:()=>n.MarianTokenizer,Mask2FormerImageProcessor:()=>M.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>M.MaskFormerFeatureExtractor,MaskFormerForInstanceSegmentation:()=>t.MaskFormerForInstanceSegmentation,MaskFormerImageProcessor:()=>M.MaskFormerImageProcessor,MaskFormerModel:()=>t.MaskFormerModel,MaskFormerPreTrainedModel:()=>t.MaskFormerPreTrainedModel,MaskedLMOutput:()=>t.MaskedLMOutput,MaxLengthCriteria:()=>U.MaxLengthCriteria,MgpstrForSceneTextRecognition:()=>t.MgpstrForSceneTextRecognition,MgpstrModelOutput:()=>t.MgpstrModelOutput,MgpstrPreTrainedModel:()=>t.MgpstrPreTrainedModel,MgpstrProcessor:()=>H.MgpstrProcessor,MgpstrTokenizer:()=>n.MgpstrTokenizer,MinLengthLogitsProcessor:()=>F.MinLengthLogitsProcessor,MinNewTokensLengthLogitsProcessor:()=>F.MinNewTokensLengthLogitsProcessor,MistralForCausalLM:()=>t.MistralForCausalLM,MistralModel:()=>t.MistralModel,MistralPreTrainedModel:()=>t.MistralPreTrainedModel,MobileBertForMaskedLM:()=>t.MobileBertForMaskedLM,MobileBertForQuestionAnswering:()=>t.MobileBertForQuestionAnswering,MobileBertForSequenceClassification:()=>t.MobileBertForSequenceClassification,MobileBertModel:()=>t.MobileBertModel,MobileBertPreTrainedModel:()=>t.MobileBertPreTrainedModel,MobileBertTokenizer:()=>n.MobileBertTokenizer,MobileLLMForCausalLM:()=>t.MobileLLMForCausalLM,MobileLLMModel:()=>t.MobileLLMModel,MobileLLMPreTrainedModel:()=>t.MobileLLMPreTrainedModel,MobileNetV1FeatureExtractor:()=>M.MobileNetV1FeatureExtractor,MobileNetV1ForImageClassification:()=>t.MobileNetV1ForImageClassification,MobileNetV1ImageProcessor:()=>M.MobileNetV1ImageProcessor,MobileNetV1Model:()=>t.MobileNetV1Model,MobileNetV1PreTrainedModel:()=>t.MobileNetV1PreTrainedModel,MobileNetV2FeatureExtractor:()=>M.MobileNetV2FeatureExtractor,MobileNetV2ForImageClassification:()=>t.MobileNetV2ForImageClassification,MobileNetV2ImageProcessor:()=>M.MobileNetV2ImageProcessor,MobileNetV2Model:()=>t.MobileNetV2Model,MobileNetV2PreTrainedModel:()=>t.MobileNetV2PreTrainedModel,MobileNetV3FeatureExtractor:()=>M.MobileNetV3FeatureExtractor,MobileNetV3ForImageClassification:()=>t.MobileNetV3ForImageClassification,MobileNetV3ImageProcessor:()=>M.MobileNetV3ImageProcessor,MobileNetV3Model:()=>t.MobileNetV3Model,MobileNetV3PreTrainedModel:()=>t.MobileNetV3PreTrainedModel,MobileNetV4FeatureExtractor:()=>M.MobileNetV4FeatureExtractor,MobileNetV4ForImageClassification:()=>t.MobileNetV4ForImageClassification,MobileNetV4ImageProcessor:()=>M.MobileNetV4ImageProcessor,MobileNetV4Model:()=>t.MobileNetV4Model,MobileNetV4PreTrainedModel:()=>t.MobileNetV4PreTrainedModel,MobileViTFeatureExtractor:()=>M.MobileViTFeatureExtractor,MobileViTForImageClassification:()=>t.MobileViTForImageClassification,MobileViTImageProcessor:()=>M.MobileViTImageProcessor,MobileViTModel:()=>t.MobileViTModel,MobileViTPreTrainedModel:()=>t.MobileViTPreTrainedModel,MobileViTV2ForImageClassification:()=>t.MobileViTV2ForImageClassification,MobileViTV2Model:()=>t.MobileViTV2Model,MobileViTV2PreTrainedModel:()=>t.MobileViTV2PreTrainedModel,ModelOutput:()=>t.ModelOutput,ModernBertForMaskedLM:()=>t.ModernBertForMaskedLM,ModernBertForSequenceClassification:()=>t.ModernBertForSequenceClassification,ModernBertForTokenClassification:()=>t.ModernBertForTokenClassification,ModernBertModel:()=>t.ModernBertModel,ModernBertPreTrainedModel:()=>t.ModernBertPreTrainedModel,Moondream1ForConditionalGeneration:()=>t.Moondream1ForConditionalGeneration,MoonshineFeatureExtractor:()=>_.MoonshineFeatureExtractor,MoonshineForConditionalGeneration:()=>t.MoonshineForConditionalGeneration,MoonshineModel:()=>t.MoonshineModel,MoonshinePreTrainedModel:()=>t.MoonshinePreTrainedModel,MoonshineProcessor:()=>H.MoonshineProcessor,MptForCausalLM:()=>t.MptForCausalLM,MptModel:()=>t.MptModel,MptPreTrainedModel:()=>t.MptPreTrainedModel,MultiModalityCausalLM:()=>t.MultiModalityCausalLM,MultiModalityPreTrainedModel:()=>t.MultiModalityPreTrainedModel,MusicgenForCausalLM:()=>t.MusicgenForCausalLM,MusicgenForConditionalGeneration:()=>t.MusicgenForConditionalGeneration,MusicgenModel:()=>t.MusicgenModel,MusicgenPreTrainedModel:()=>t.MusicgenPreTrainedModel,NllbTokenizer:()=>n.NllbTokenizer,NoBadWordsLogitsProcessor:()=>F.NoBadWordsLogitsProcessor,NoRepeatNGramLogitsProcessor:()=>F.NoRepeatNGramLogitsProcessor,NomicBertModel:()=>t.NomicBertModel,NomicBertPreTrainedModel:()=>t.NomicBertPreTrainedModel,NougatImageProcessor:()=>M.NougatImageProcessor,NougatTokenizer:()=>n.NougatTokenizer,OPTForCausalLM:()=>t.OPTForCausalLM,OPTModel:()=>t.OPTModel,OPTPreTrainedModel:()=>t.OPTPreTrainedModel,ObjectDetectionPipeline:()=>e.ObjectDetectionPipeline,Olmo2ForCausalLM:()=>t.Olmo2ForCausalLM,Olmo2Model:()=>t.Olmo2Model,Olmo2PreTrainedModel:()=>t.Olmo2PreTrainedModel,OlmoForCausalLM:()=>t.OlmoForCausalLM,OlmoModel:()=>t.OlmoModel,OlmoPreTrainedModel:()=>t.OlmoPreTrainedModel,OpenELMForCausalLM:()=>t.OpenELMForCausalLM,OpenELMModel:()=>t.OpenELMModel,OpenELMPreTrainedModel:()=>t.OpenELMPreTrainedModel,OwlViTFeatureExtractor:()=>M.OwlViTFeatureExtractor,OwlViTForObjectDetection:()=>t.OwlViTForObjectDetection,OwlViTImageProcessor:()=>M.OwlViTImageProcessor,OwlViTModel:()=>t.OwlViTModel,OwlViTPreTrainedModel:()=>t.OwlViTPreTrainedModel,OwlViTProcessor:()=>H.OwlViTProcessor,Owlv2ForObjectDetection:()=>t.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>M.Owlv2ImageProcessor,Owlv2Model:()=>t.Owlv2Model,Owlv2PreTrainedModel:()=>t.Owlv2PreTrainedModel,PaliGemmaForConditionalGeneration:()=>t.PaliGemmaForConditionalGeneration,PaliGemmaPreTrainedModel:()=>t.PaliGemmaPreTrainedModel,PaliGemmaProcessor:()=>H.PaliGemmaProcessor,PatchTSMixerForPrediction:()=>t.PatchTSMixerForPrediction,PatchTSMixerModel:()=>t.PatchTSMixerModel,PatchTSMixerPreTrainedModel:()=>t.PatchTSMixerPreTrainedModel,PatchTSTForPrediction:()=>t.PatchTSTForPrediction,PatchTSTModel:()=>t.PatchTSTModel,PatchTSTPreTrainedModel:()=>t.PatchTSTPreTrainedModel,Phi3ForCausalLM:()=>t.Phi3ForCausalLM,Phi3Model:()=>t.Phi3Model,Phi3PreTrainedModel:()=>t.Phi3PreTrainedModel,Phi3VForCausalLM:()=>t.Phi3VForCausalLM,Phi3VImageProcessor:()=>M.Phi3VImageProcessor,Phi3VPreTrainedModel:()=>t.Phi3VPreTrainedModel,Phi3VProcessor:()=>H.Phi3VProcessor,PhiForCausalLM:()=>t.PhiForCausalLM,PhiModel:()=>t.PhiModel,PhiPreTrainedModel:()=>t.PhiPreTrainedModel,Pipeline:()=>e.Pipeline,PreTrainedModel:()=>t.PreTrainedModel,PreTrainedTokenizer:()=>n.PreTrainedTokenizer,PretrainedConfig:()=>a.PretrainedConfig,PretrainedMixin:()=>t.PretrainedMixin,Processor:()=>G.Processor,PvtForImageClassification:()=>t.PvtForImageClassification,PvtImageProcessor:()=>M.PvtImageProcessor,PvtModel:()=>t.PvtModel,PvtPreTrainedModel:()=>t.PvtPreTrainedModel,PyAnnoteFeatureExtractor:()=>_.PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification:()=>t.PyAnnoteForAudioFrameClassification,PyAnnoteModel:()=>t.PyAnnoteModel,PyAnnotePreTrainedModel:()=>t.PyAnnotePreTrainedModel,PyAnnoteProcessor:()=>H.PyAnnoteProcessor,QuestionAnsweringModelOutput:()=>t.QuestionAnsweringModelOutput,QuestionAnsweringPipeline:()=>e.QuestionAnsweringPipeline,Qwen2ForCausalLM:()=>t.Qwen2ForCausalLM,Qwen2Model:()=>t.Qwen2Model,Qwen2PreTrainedModel:()=>t.Qwen2PreTrainedModel,Qwen2Tokenizer:()=>n.Qwen2Tokenizer,Qwen2VLForConditionalGeneration:()=>t.Qwen2VLForConditionalGeneration,Qwen2VLImageProcessor:()=>M.Qwen2VLImageProcessor,Qwen2VLPreTrainedModel:()=>t.Qwen2VLPreTrainedModel,Qwen2VLProcessor:()=>H.Qwen2VLProcessor,RTDetrForObjectDetection:()=>t.RTDetrForObjectDetection,RTDetrImageProcessor:()=>M.RTDetrImageProcessor,RTDetrModel:()=>t.RTDetrModel,RTDetrObjectDetectionOutput:()=>t.RTDetrObjectDetectionOutput,RTDetrPreTrainedModel:()=>t.RTDetrPreTrainedModel,RawAudio:()=>o.RawAudio,RawImage:()=>u.RawImage,RepetitionPenaltyLogitsProcessor:()=>F.RepetitionPenaltyLogitsProcessor,ResNetForImageClassification:()=>t.ResNetForImageClassification,ResNetModel:()=>t.ResNetModel,ResNetPreTrainedModel:()=>t.ResNetPreTrainedModel,RoFormerForMaskedLM:()=>t.RoFormerForMaskedLM,RoFormerForQuestionAnswering:()=>t.RoFormerForQuestionAnswering,RoFormerForSequenceClassification:()=>t.RoFormerForSequenceClassification,RoFormerForTokenClassification:()=>t.RoFormerForTokenClassification,RoFormerModel:()=>t.RoFormerModel,RoFormerPreTrainedModel:()=>t.RoFormerPreTrainedModel,RoFormerTokenizer:()=>n.RoFormerTokenizer,RobertaForMaskedLM:()=>t.RobertaForMaskedLM,RobertaForQuestionAnswering:()=>t.RobertaForQuestionAnswering,RobertaForSequenceClassification:()=>t.RobertaForSequenceClassification,RobertaForTokenClassification:()=>t.RobertaForTokenClassification,RobertaModel:()=>t.RobertaModel,RobertaPreTrainedModel:()=>t.RobertaPreTrainedModel,RobertaTokenizer:()=>n.RobertaTokenizer,SamImageProcessor:()=>M.SamImageProcessor,SamImageSegmentationOutput:()=>t.SamImageSegmentationOutput,SamModel:()=>t.SamModel,SamPreTrainedModel:()=>t.SamPreTrainedModel,SamProcessor:()=>H.SamProcessor,SapiensForDepthEstimation:()=>t.SapiensForDepthEstimation,SapiensForNormalEstimation:()=>t.SapiensForNormalEstimation,SapiensForSemanticSegmentation:()=>t.SapiensForSemanticSegmentation,SapiensPreTrainedModel:()=>t.SapiensPreTrainedModel,SeamlessM4TFeatureExtractor:()=>_.SeamlessM4TFeatureExtractor,SegformerFeatureExtractor:()=>M.SegformerFeatureExtractor,SegformerForImageClassification:()=>t.SegformerForImageClassification,SegformerForSemanticSegmentation:()=>t.SegformerForSemanticSegmentation,SegformerImageProcessor:()=>M.SegformerImageProcessor,SegformerModel:()=>t.SegformerModel,SegformerPreTrainedModel:()=>t.SegformerPreTrainedModel,Seq2SeqLMOutput:()=>t.Seq2SeqLMOutput,SequenceClassifierOutput:()=>t.SequenceClassifierOutput,SiglipImageProcessor:()=>M.SiglipImageProcessor,SiglipModel:()=>t.SiglipModel,SiglipPreTrainedModel:()=>t.SiglipPreTrainedModel,SiglipTextModel:()=>t.SiglipTextModel,SiglipTokenizer:()=>n.SiglipTokenizer,SiglipVisionModel:()=>t.SiglipVisionModel,SpeechT5FeatureExtractor:()=>_.SpeechT5FeatureExtractor,SpeechT5ForSpeechToText:()=>t.SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech:()=>t.SpeechT5ForTextToSpeech,SpeechT5HifiGan:()=>t.SpeechT5HifiGan,SpeechT5Model:()=>t.SpeechT5Model,SpeechT5PreTrainedModel:()=>t.SpeechT5PreTrainedModel,SpeechT5Processor:()=>H.SpeechT5Processor,SpeechT5Tokenizer:()=>n.SpeechT5Tokenizer,SqueezeBertForMaskedLM:()=>t.SqueezeBertForMaskedLM,SqueezeBertForQuestionAnswering:()=>t.SqueezeBertForQuestionAnswering,SqueezeBertForSequenceClassification:()=>t.SqueezeBertForSequenceClassification,SqueezeBertModel:()=>t.SqueezeBertModel,SqueezeBertPreTrainedModel:()=>t.SqueezeBertPreTrainedModel,SqueezeBertTokenizer:()=>n.SqueezeBertTokenizer,StableLmForCausalLM:()=>t.StableLmForCausalLM,StableLmModel:()=>t.StableLmModel,StableLmPreTrainedModel:()=>t.StableLmPreTrainedModel,Starcoder2ForCausalLM:()=>t.Starcoder2ForCausalLM,Starcoder2Model:()=>t.Starcoder2Model,Starcoder2PreTrainedModel:()=>t.Starcoder2PreTrainedModel,StoppingCriteria:()=>U.StoppingCriteria,StoppingCriteriaList:()=>U.StoppingCriteriaList,StyleTextToSpeech2Model:()=>t.StyleTextToSpeech2Model,StyleTextToSpeech2PreTrainedModel:()=>t.StyleTextToSpeech2PreTrainedModel,SummarizationPipeline:()=>e.SummarizationPipeline,SuppressTokensAtBeginLogitsProcessor:()=>F.SuppressTokensAtBeginLogitsProcessor,Swin2SRForImageSuperResolution:()=>t.Swin2SRForImageSuperResolution,Swin2SRImageProcessor:()=>M.Swin2SRImageProcessor,Swin2SRModel:()=>t.Swin2SRModel,Swin2SRPreTrainedModel:()=>t.Swin2SRPreTrainedModel,SwinForImageClassification:()=>t.SwinForImageClassification,SwinModel:()=>t.SwinModel,SwinPreTrainedModel:()=>t.SwinPreTrainedModel,T5ForConditionalGeneration:()=>t.T5ForConditionalGeneration,T5Model:()=>t.T5Model,T5PreTrainedModel:()=>t.T5PreTrainedModel,T5Tokenizer:()=>n.T5Tokenizer,TableTransformerForObjectDetection:()=>t.TableTransformerForObjectDetection,TableTransformerModel:()=>t.TableTransformerModel,TableTransformerObjectDetectionOutput:()=>t.TableTransformerObjectDetectionOutput,TableTransformerPreTrainedModel:()=>t.TableTransformerPreTrainedModel,TemperatureLogitsWarper:()=>F.TemperatureLogitsWarper,Tensor:()=>d.Tensor,Text2TextGenerationPipeline:()=>e.Text2TextGenerationPipeline,TextClassificationPipeline:()=>e.TextClassificationPipeline,TextGenerationPipeline:()=>e.TextGenerationPipeline,TextStreamer:()=>z.TextStreamer,TextToAudioPipeline:()=>e.TextToAudioPipeline,TokenClassificationPipeline:()=>e.TokenClassificationPipeline,TokenClassifierOutput:()=>t.TokenClassifierOutput,TokenizerModel:()=>n.TokenizerModel,TopKLogitsWarper:()=>F.TopKLogitsWarper,TopPLogitsWarper:()=>F.TopPLogitsWarper,TrOCRForCausalLM:()=>t.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>t.TrOCRPreTrainedModel,TranslationPipeline:()=>e.TranslationPipeline,UniSpeechForCTC:()=>t.UniSpeechForCTC,UniSpeechForSequenceClassification:()=>t.UniSpeechForSequenceClassification,UniSpeechModel:()=>t.UniSpeechModel,UniSpeechPreTrainedModel:()=>t.UniSpeechPreTrainedModel,UniSpeechSatForAudioFrameClassification:()=>t.UniSpeechSatForAudioFrameClassification,UniSpeechSatForCTC:()=>t.UniSpeechSatForCTC,UniSpeechSatForSequenceClassification:()=>t.UniSpeechSatForSequenceClassification,UniSpeechSatModel:()=>t.UniSpeechSatModel,UniSpeechSatPreTrainedModel:()=>t.UniSpeechSatPreTrainedModel,VLChatProcessor:()=>H.VLChatProcessor,VLMImageProcessor:()=>M.VLMImageProcessor,ViTFeatureExtractor:()=>M.ViTFeatureExtractor,ViTForImageClassification:()=>t.ViTForImageClassification,ViTImageProcessor:()=>M.ViTImageProcessor,ViTMAEModel:()=>t.ViTMAEModel,ViTMAEPreTrainedModel:()=>t.ViTMAEPreTrainedModel,ViTMSNForImageClassification:()=>t.ViTMSNForImageClassification,ViTMSNModel:()=>t.ViTMSNModel,ViTMSNPreTrainedModel:()=>t.ViTMSNPreTrainedModel,ViTModel:()=>t.ViTModel,ViTPreTrainedModel:()=>t.ViTPreTrainedModel,VisionEncoderDecoderModel:()=>t.VisionEncoderDecoderModel,VitMatteForImageMatting:()=>t.VitMatteForImageMatting,VitMatteImageProcessor:()=>M.VitMatteImageProcessor,VitMattePreTrainedModel:()=>t.VitMattePreTrainedModel,VitPoseForPoseEstimation:()=>t.VitPoseForPoseEstimation,VitPoseImageProcessor:()=>M.VitPoseImageProcessor,VitPosePreTrainedModel:()=>t.VitPosePreTrainedModel,VitsModel:()=>t.VitsModel,VitsModelOutput:()=>t.VitsModelOutput,VitsPreTrainedModel:()=>t.VitsPreTrainedModel,VitsTokenizer:()=>n.VitsTokenizer,Wav2Vec2BertForCTC:()=>t.Wav2Vec2BertForCTC,Wav2Vec2BertForSequenceClassification:()=>t.Wav2Vec2BertForSequenceClassification,Wav2Vec2BertModel:()=>t.Wav2Vec2BertModel,Wav2Vec2BertPreTrainedModel:()=>t.Wav2Vec2BertPreTrainedModel,Wav2Vec2CTCTokenizer:()=>n.Wav2Vec2CTCTokenizer,Wav2Vec2FeatureExtractor:()=>_.Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification:()=>t.Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC:()=>t.Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification:()=>t.Wav2Vec2ForSequenceClassification,Wav2Vec2Model:()=>t.Wav2Vec2Model,Wav2Vec2PreTrainedModel:()=>t.Wav2Vec2PreTrainedModel,Wav2Vec2ProcessorWithLM:()=>H.Wav2Vec2ProcessorWithLM,WavLMForAudioFrameClassification:()=>t.WavLMForAudioFrameClassification,WavLMForCTC:()=>t.WavLMForCTC,WavLMForSequenceClassification:()=>t.WavLMForSequenceClassification,WavLMForXVector:()=>t.WavLMForXVector,WavLMModel:()=>t.WavLMModel,WavLMPreTrainedModel:()=>t.WavLMPreTrainedModel,WeSpeakerFeatureExtractor:()=>_.WeSpeakerFeatureExtractor,WeSpeakerResNetModel:()=>t.WeSpeakerResNetModel,WeSpeakerResNetPreTrainedModel:()=>t.WeSpeakerResNetPreTrainedModel,WhisperFeatureExtractor:()=>_.WhisperFeatureExtractor,WhisperForConditionalGeneration:()=>t.WhisperForConditionalGeneration,WhisperModel:()=>t.WhisperModel,WhisperPreTrainedModel:()=>t.WhisperPreTrainedModel,WhisperProcessor:()=>H.WhisperProcessor,WhisperTextStreamer:()=>z.WhisperTextStreamer,WhisperTimeStampLogitsProcessor:()=>F.WhisperTimeStampLogitsProcessor,WhisperTokenizer:()=>n.WhisperTokenizer,XLMForQuestionAnswering:()=>t.XLMForQuestionAnswering,XLMForSequenceClassification:()=>t.XLMForSequenceClassification,XLMForTokenClassification:()=>t.XLMForTokenClassification,XLMModel:()=>t.XLMModel,XLMPreTrainedModel:()=>t.XLMPreTrainedModel,XLMRobertaForMaskedLM:()=>t.XLMRobertaForMaskedLM,XLMRobertaForQuestionAnswering:()=>t.XLMRobertaForQuestionAnswering,XLMRobertaForSequenceClassification:()=>t.XLMRobertaForSequenceClassification,XLMRobertaForTokenClassification:()=>t.XLMRobertaForTokenClassification,XLMRobertaModel:()=>t.XLMRobertaModel,XLMRobertaPreTrainedModel:()=>t.XLMRobertaPreTrainedModel,XLMRobertaTokenizer:()=>n.XLMRobertaTokenizer,XLMTokenizer:()=>n.XLMTokenizer,XLMWithLMHeadModel:()=>t.XLMWithLMHeadModel,XVectorOutput:()=>t.XVectorOutput,YolosFeatureExtractor:()=>M.YolosFeatureExtractor,YolosForObjectDetection:()=>t.YolosForObjectDetection,YolosImageProcessor:()=>M.YolosImageProcessor,YolosModel:()=>t.YolosModel,YolosObjectDetectionOutput:()=>t.YolosObjectDetectionOutput,YolosPreTrainedModel:()=>t.YolosPreTrainedModel,ZeroShotAudioClassificationPipeline:()=>e.ZeroShotAudioClassificationPipeline,ZeroShotClassificationPipeline:()=>e.ZeroShotClassificationPipeline,ZeroShotImageClassificationPipeline:()=>e.ZeroShotImageClassificationPipeline,ZeroShotObjectDetectionPipeline:()=>e.ZeroShotObjectDetectionPipeline,bankers_round:()=>c.bankers_round,cat:()=>d.cat,cos_sim:()=>c.cos_sim,dot:()=>c.dot,dynamic_time_warping:()=>c.dynamic_time_warping,env:()=>r.env,full:()=>d.full,full_like:()=>d.full_like,getKeyValueShapes:()=>a.getKeyValueShapes,hamming:()=>o.hamming,hanning:()=>o.hanning,interpolate:()=>d.interpolate,interpolate_4d:()=>d.interpolate_4d,interpolate_data:()=>c.interpolate_data,is_chinese_char:()=>n.is_chinese_char,layer_norm:()=>d.layer_norm,load_image:()=>u.load_image,log_softmax:()=>c.log_softmax,magnitude:()=>c.magnitude,matmul:()=>d.matmul,max:()=>c.max,mean:()=>d.mean,mean_pooling:()=>d.mean_pooling,medianFilter:()=>c.medianFilter,mel_filter_bank:()=>o.mel_filter_bank,min:()=>c.min,ones:()=>d.ones,ones_like:()=>d.ones_like,permute:()=>d.permute,permute_data:()=>c.permute_data,pipeline:()=>e.pipeline,quantize_embeddings:()=>d.quantize_embeddings,rand:()=>d.rand,read_audio:()=>o.read_audio,rfft:()=>d.rfft,round:()=>c.round,slice:()=>d.slice,softmax:()=>c.softmax,spectrogram:()=>o.spectrogram,stack:()=>d.stack,std_mean:()=>d.std_mean,topk:()=>d.topk,window_function:()=>o.window_function,zeros:()=>d.zeros,zeros_like:()=>d.zeros_like});var r=Lr("./src/env.js"),e=Lr("./src/pipelines.js"),t=Lr("./src/models.js"),n=Lr("./src/tokenizers.js"),a=Lr("./src/configs.js"),o=Lr("./src/utils/audio.js"),u=Lr("./src/utils/image.js"),d=Lr("./src/utils/tensor.js"),c=Lr("./src/utils/maths.js"),h=Lr("./src/base/feature_extraction_utils.js"),_=Lr("./src/models/feature_extractors.js"),y=Lr("./src/models/auto/feature_extraction_auto.js"),w=Lr("./src/base/image_processors_utils.js"),M=Lr("./src/models/image_processors.js"),S=Lr("./src/models/auto/image_processing_auto.js"),G=Lr("./src/base/processing_utils.js"),H=Lr("./src/models/processors.js"),B=Lr("./src/models/auto/processing_auto.js"),z=Lr("./src/generation/streamers.js"),U=Lr("./src/generation/stopping_criteria.js"),F=Lr("./src/generation/logits_process.js")})();T.ASTFeatureExtractor;T.ASTForAudioClassification;T.ASTModel;T.ASTPreTrainedModel;T.AlbertForMaskedLM;T.AlbertForQuestionAnswering;T.AlbertForSequenceClassification;T.AlbertModel;T.AlbertPreTrainedModel;T.AlbertTokenizer;T.AudioClassificationPipeline;T.AutoConfig;T.AutoFeatureExtractor;T.AutoImageProcessor;T.AutoModel;T.AutoModelForAudioClassification;T.AutoModelForAudioFrameClassification;T.AutoModelForCTC;var h2=T.AutoModelForCausalLM;T.AutoModelForDepthEstimation;T.AutoModelForDocumentQuestionAnswering;T.AutoModelForImageClassification;T.AutoModelForImageFeatureExtraction;T.AutoModelForImageMatting;T.AutoModelForImageSegmentation;T.AutoModelForImageToImage;T.AutoModelForMaskGeneration;T.AutoModelForMaskedLM;T.AutoModelForNormalEstimation;T.AutoModelForObjectDetection;T.AutoModelForPoseEstimation;T.AutoModelForQuestionAnswering;T.AutoModelForSemanticSegmentation;T.AutoModelForSeq2SeqLM;T.AutoModelForSequenceClassification;T.AutoModelForSpeechSeq2Seq;T.AutoModelForTextToSpectrogram;T.AutoModelForTextToWaveform;T.AutoModelForTokenClassification;T.AutoModelForUniversalSegmentation;T.AutoModelForVision2Seq;T.AutoModelForXVector;T.AutoModelForZeroShotObjectDetection;T.AutoProcessor;var f2=T.AutoTokenizer;T.AutomaticSpeechRecognitionPipeline;T.BartForConditionalGeneration;T.BartForSequenceClassification;T.BartModel;T.BartPretrainedModel;T.BartTokenizer;T.BaseModelOutput;T.BaseStreamer;T.BeitFeatureExtractor;T.BeitForImageClassification;T.BeitModel;T.BeitPreTrainedModel;T.BertForMaskedLM;T.BertForQuestionAnswering;T.BertForSequenceClassification;T.BertForTokenClassification;T.BertModel;T.BertPreTrainedModel;T.BertTokenizer;T.BitImageProcessor;T.BlenderbotForConditionalGeneration;T.BlenderbotModel;T.BlenderbotPreTrainedModel;T.BlenderbotSmallForConditionalGeneration;T.BlenderbotSmallModel;T.BlenderbotSmallPreTrainedModel;T.BlenderbotSmallTokenizer;T.BlenderbotTokenizer;T.BloomForCausalLM;T.BloomModel;T.BloomPreTrainedModel;T.BloomTokenizer;T.CLIPFeatureExtractor;T.CLIPImageProcessor;T.CLIPModel;T.CLIPPreTrainedModel;T.CLIPSegForImageSegmentation;T.CLIPSegModel;T.CLIPSegPreTrainedModel;T.CLIPTextModel;T.CLIPTextModelWithProjection;T.CLIPTokenizer;T.CLIPVisionModel;T.CLIPVisionModelWithProjection;T.CamembertForMaskedLM;T.CamembertForQuestionAnswering;T.CamembertForSequenceClassification;T.CamembertForTokenClassification;T.CamembertModel;T.CamembertPreTrainedModel;T.CamembertTokenizer;T.CausalLMOutput;T.CausalLMOutputWithPast;T.ChineseCLIPFeatureExtractor;T.ChineseCLIPModel;T.ChineseCLIPPreTrainedModel;T.ClapAudioModelWithProjection;T.ClapFeatureExtractor;T.ClapModel;T.ClapPreTrainedModel;T.ClapTextModelWithProjection;T.ClassifierFreeGuidanceLogitsProcessor;T.CodeGenForCausalLM;T.CodeGenModel;T.CodeGenPreTrainedModel;T.CodeGenTokenizer;T.CodeLlamaTokenizer;T.CohereForCausalLM;T.CohereModel;T.CoherePreTrainedModel;T.CohereTokenizer;T.ConvBertForMaskedLM;T.ConvBertForQuestionAnswering;T.ConvBertForSequenceClassification;T.ConvBertForTokenClassification;T.ConvBertModel;T.ConvBertPreTrainedModel;T.ConvBertTokenizer;T.ConvNextFeatureExtractor;T.ConvNextForImageClassification;T.ConvNextImageProcessor;T.ConvNextModel;T.ConvNextPreTrainedModel;T.ConvNextV2ForImageClassification;T.ConvNextV2Model;T.ConvNextV2PreTrainedModel;T.DPTFeatureExtractor;T.DPTForDepthEstimation;T.DPTImageProcessor;T.DPTModel;T.DPTPreTrainedModel;T.DebertaForMaskedLM;T.DebertaForQuestionAnswering;T.DebertaForSequenceClassification;T.DebertaForTokenClassification;T.DebertaModel;T.DebertaPreTrainedModel;T.DebertaTokenizer;T.DebertaV2ForMaskedLM;T.DebertaV2ForQuestionAnswering;T.DebertaV2ForSequenceClassification;T.DebertaV2ForTokenClassification;T.DebertaV2Model;T.DebertaV2PreTrainedModel;T.DebertaV2Tokenizer;T.DecisionTransformerModel;T.DecisionTransformerPreTrainedModel;T.DeiTFeatureExtractor;T.DeiTForImageClassification;T.DeiTImageProcessor;T.DeiTModel;T.DeiTPreTrainedModel;T.DepthAnythingForDepthEstimation;T.DepthAnythingPreTrainedModel;T.DepthEstimationPipeline;T.DepthProForDepthEstimation;T.DepthProPreTrainedModel;T.DetrFeatureExtractor;T.DetrForObjectDetection;T.DetrForSegmentation;T.DetrImageProcessor;T.DetrModel;T.DetrObjectDetectionOutput;T.DetrPreTrainedModel;T.DetrSegmentationOutput;T.Dinov2ForImageClassification;T.Dinov2Model;T.Dinov2PreTrainedModel;T.Dinov2WithRegistersForImageClassification;T.Dinov2WithRegistersModel;T.Dinov2WithRegistersPreTrainedModel;T.DistilBertForMaskedLM;T.DistilBertForQuestionAnswering;T.DistilBertForSequenceClassification;T.DistilBertForTokenClassification;T.DistilBertModel;T.DistilBertPreTrainedModel;T.DistilBertTokenizer;T.DocumentQuestionAnsweringPipeline;T.DonutFeatureExtractor;T.DonutImageProcessor;T.DonutSwinModel;T.DonutSwinPreTrainedModel;T.EfficientNetForImageClassification;T.EfficientNetImageProcessor;T.EfficientNetModel;T.EfficientNetPreTrainedModel;T.ElectraForMaskedLM;T.ElectraForQuestionAnswering;T.ElectraForSequenceClassification;T.ElectraForTokenClassification;T.ElectraModel;T.ElectraPreTrainedModel;T.ElectraTokenizer;T.EosTokenCriteria;T.EsmForMaskedLM;T.EsmForSequenceClassification;T.EsmForTokenClassification;T.EsmModel;T.EsmPreTrainedModel;T.EsmTokenizer;T.ExaoneForCausalLM;T.ExaoneModel;T.ExaonePreTrainedModel;T.FFT;T.FalconForCausalLM;T.FalconModel;T.FalconPreTrainedModel;T.FalconTokenizer;T.FastViTForImageClassification;T.FastViTModel;T.FastViTPreTrainedModel;T.FeatureExtractionPipeline;T.FeatureExtractor;T.FillMaskPipeline;T.Florence2ForConditionalGeneration;T.Florence2PreTrainedModel;T.Florence2Processor;T.ForcedBOSTokenLogitsProcessor;T.ForcedEOSTokenLogitsProcessor;T.GLPNFeatureExtractor;T.GLPNForDepthEstimation;T.GLPNModel;T.GLPNPreTrainedModel;T.GPT2LMHeadModel;T.GPT2Model;T.GPT2PreTrainedModel;T.GPT2Tokenizer;T.GPTBigCodeForCausalLM;T.GPTBigCodeModel;T.GPTBigCodePreTrainedModel;T.GPTJForCausalLM;T.GPTJModel;T.GPTJPreTrainedModel;T.GPTNeoForCausalLM;T.GPTNeoModel;T.GPTNeoPreTrainedModel;T.GPTNeoXForCausalLM;T.GPTNeoXModel;T.GPTNeoXPreTrainedModel;T.GPTNeoXTokenizer;T.Gemma2ForCausalLM;T.Gemma2Model;T.Gemma2PreTrainedModel;T.GemmaForCausalLM;T.GemmaModel;T.GemmaPreTrainedModel;T.GemmaTokenizer;T.GraniteForCausalLM;T.GraniteModel;T.GranitePreTrainedModel;T.Grok1Tokenizer;T.GroundingDinoForObjectDetection;T.GroundingDinoImageProcessor;T.GroundingDinoPreTrainedModel;T.GroundingDinoProcessor;T.GroupViTModel;T.GroupViTPreTrainedModel;T.HerbertTokenizer;T.HieraForImageClassification;T.HieraModel;T.HieraPreTrainedModel;T.HubertForCTC;T.HubertForSequenceClassification;T.HubertModel;T.HubertPreTrainedModel;T.IJepaForImageClassification;T.IJepaModel;T.IJepaPreTrainedModel;T.Idefics3ForConditionalGeneration;T.Idefics3ImageProcessor;T.Idefics3PreTrainedModel;T.Idefics3Processor;T.ImageClassificationPipeline;T.ImageFeatureExtractionPipeline;T.ImageFeatureExtractor;T.ImageMattingOutput;T.ImageProcessor;T.ImageSegmentationPipeline;T.ImageToImagePipeline;T.ImageToTextPipeline;var p2=T.InterruptableStoppingCriteria;T.JAISLMHeadModel;T.JAISModel;T.JAISPreTrainedModel;T.JinaCLIPImageProcessor;T.JinaCLIPModel;T.JinaCLIPPreTrainedModel;T.JinaCLIPProcessor;T.JinaCLIPTextModel;T.JinaCLIPVisionModel;T.LlamaForCausalLM;T.LlamaModel;T.LlamaPreTrainedModel;T.LlamaTokenizer;T.LlavaForConditionalGeneration;T.LlavaOnevisionForConditionalGeneration;T.LlavaOnevisionImageProcessor;T.LlavaPreTrainedModel;T.LogitsProcessor;T.LogitsProcessorList;T.LogitsWarper;T.LongT5ForConditionalGeneration;T.LongT5Model;T.LongT5PreTrainedModel;T.M2M100ForConditionalGeneration;T.M2M100Model;T.M2M100PreTrainedModel;T.M2M100Tokenizer;T.MBart50Tokenizer;T.MBartForCausalLM;T.MBartForConditionalGeneration;T.MBartForSequenceClassification;T.MBartModel;T.MBartPreTrainedModel;T.MBartTokenizer;T.MPNetForMaskedLM;T.MPNetForQuestionAnswering;T.MPNetForSequenceClassification;T.MPNetForTokenClassification;T.MPNetModel;T.MPNetPreTrainedModel;T.MPNetTokenizer;T.MT5ForConditionalGeneration;T.MT5Model;T.MT5PreTrainedModel;T.MarianMTModel;T.MarianModel;T.MarianPreTrainedModel;T.MarianTokenizer;T.Mask2FormerImageProcessor;T.MaskFormerFeatureExtractor;T.MaskFormerForInstanceSegmentation;T.MaskFormerImageProcessor;T.MaskFormerModel;T.MaskFormerPreTrainedModel;T.MaskedLMOutput;T.MaxLengthCriteria;T.MgpstrForSceneTextRecognition;T.MgpstrModelOutput;T.MgpstrPreTrainedModel;T.MgpstrProcessor;T.MgpstrTokenizer;T.MinLengthLogitsProcessor;T.MinNewTokensLengthLogitsProcessor;T.MistralForCausalLM;T.MistralModel;T.MistralPreTrainedModel;T.MobileBertForMaskedLM;T.MobileBertForQuestionAnswering;T.MobileBertForSequenceClassification;T.MobileBertModel;T.MobileBertPreTrainedModel;T.MobileBertTokenizer;T.MobileLLMForCausalLM;T.MobileLLMModel;T.MobileLLMPreTrainedModel;T.MobileNetV1FeatureExtractor;T.MobileNetV1ForImageClassification;T.MobileNetV1ImageProcessor;T.MobileNetV1Model;T.MobileNetV1PreTrainedModel;T.MobileNetV2FeatureExtractor;T.MobileNetV2ForImageClassification;T.MobileNetV2ImageProcessor;T.MobileNetV2Model;T.MobileNetV2PreTrainedModel;T.MobileNetV3FeatureExtractor;T.MobileNetV3ForImageClassification;T.MobileNetV3ImageProcessor;T.MobileNetV3Model;T.MobileNetV3PreTrainedModel;T.MobileNetV4FeatureExtractor;T.MobileNetV4ForImageClassification;T.MobileNetV4ImageProcessor;T.MobileNetV4Model;T.MobileNetV4PreTrainedModel;T.MobileViTFeatureExtractor;T.MobileViTForImageClassification;T.MobileViTImageProcessor;T.MobileViTModel;T.MobileViTPreTrainedModel;T.MobileViTV2ForImageClassification;T.MobileViTV2Model;T.MobileViTV2PreTrainedModel;T.ModelOutput;T.ModernBertForMaskedLM;T.ModernBertForSequenceClassification;T.ModernBertForTokenClassification;T.ModernBertModel;T.ModernBertPreTrainedModel;T.Moondream1ForConditionalGeneration;T.MoonshineFeatureExtractor;T.MoonshineForConditionalGeneration;T.MoonshineModel;T.MoonshinePreTrainedModel;T.MoonshineProcessor;T.MptForCausalLM;T.MptModel;T.MptPreTrainedModel;T.MultiModalityCausalLM;T.MultiModalityPreTrainedModel;T.MusicgenForCausalLM;T.MusicgenForConditionalGeneration;T.MusicgenModel;T.MusicgenPreTrainedModel;T.NllbTokenizer;T.NoBadWordsLogitsProcessor;T.NoRepeatNGramLogitsProcessor;T.NomicBertModel;T.NomicBertPreTrainedModel;T.NougatImageProcessor;T.NougatTokenizer;T.OPTForCausalLM;T.OPTModel;T.OPTPreTrainedModel;T.ObjectDetectionPipeline;T.Olmo2ForCausalLM;T.Olmo2Model;T.Olmo2PreTrainedModel;T.OlmoForCausalLM;T.OlmoModel;T.OlmoPreTrainedModel;T.OpenELMForCausalLM;T.OpenELMModel;T.OpenELMPreTrainedModel;T.OwlViTFeatureExtractor;T.OwlViTForObjectDetection;T.OwlViTImageProcessor;T.OwlViTModel;T.OwlViTPreTrainedModel;T.OwlViTProcessor;T.Owlv2ForObjectDetection;T.Owlv2ImageProcessor;T.Owlv2Model;T.Owlv2PreTrainedModel;T.PaliGemmaForConditionalGeneration;T.PaliGemmaPreTrainedModel;T.PaliGemmaProcessor;T.PatchTSMixerForPrediction;T.PatchTSMixerModel;T.PatchTSMixerPreTrainedModel;T.PatchTSTForPrediction;T.PatchTSTModel;T.PatchTSTPreTrainedModel;T.Phi3ForCausalLM;T.Phi3Model;T.Phi3PreTrainedModel;T.Phi3VForCausalLM;T.Phi3VImageProcessor;T.Phi3VPreTrainedModel;T.Phi3VProcessor;T.PhiForCausalLM;T.PhiModel;T.PhiPreTrainedModel;T.Pipeline;T.PreTrainedModel;T.PreTrainedTokenizer;T.PretrainedConfig;T.PretrainedMixin;T.Processor;T.PvtForImageClassification;T.PvtImageProcessor;T.PvtModel;T.PvtPreTrainedModel;T.PyAnnoteFeatureExtractor;T.PyAnnoteForAudioFrameClassification;T.PyAnnoteModel;T.PyAnnotePreTrainedModel;T.PyAnnoteProcessor;T.QuestionAnsweringModelOutput;T.QuestionAnsweringPipeline;T.Qwen2ForCausalLM;T.Qwen2Model;T.Qwen2PreTrainedModel;T.Qwen2Tokenizer;T.Qwen2VLForConditionalGeneration;T.Qwen2VLImageProcessor;T.Qwen2VLPreTrainedModel;T.Qwen2VLProcessor;T.RTDetrForObjectDetection;T.RTDetrImageProcessor;T.RTDetrModel;T.RTDetrObjectDetectionOutput;T.RTDetrPreTrainedModel;T.RawAudio;T.RawImage;T.RepetitionPenaltyLogitsProcessor;T.ResNetForImageClassification;T.ResNetModel;T.ResNetPreTrainedModel;T.RoFormerForMaskedLM;T.RoFormerForQuestionAnswering;T.RoFormerForSequenceClassification;T.RoFormerForTokenClassification;T.RoFormerModel;T.RoFormerPreTrainedModel;T.RoFormerTokenizer;T.RobertaForMaskedLM;T.RobertaForQuestionAnswering;T.RobertaForSequenceClassification;T.RobertaForTokenClassification;T.RobertaModel;T.RobertaPreTrainedModel;T.RobertaTokenizer;T.SamImageProcessor;T.SamImageSegmentationOutput;T.SamModel;T.SamPreTrainedModel;T.SamProcessor;T.SapiensForDepthEstimation;T.SapiensForNormalEstimation;T.SapiensForSemanticSegmentation;T.SapiensPreTrainedModel;T.SeamlessM4TFeatureExtractor;T.SegformerFeatureExtractor;T.SegformerForImageClassification;T.SegformerForSemanticSegmentation;T.SegformerImageProcessor;T.SegformerModel;T.SegformerPreTrainedModel;T.Seq2SeqLMOutput;T.SequenceClassifierOutput;T.SiglipImageProcessor;T.SiglipModel;T.SiglipPreTrainedModel;T.SiglipTextModel;T.SiglipTokenizer;T.SiglipVisionModel;T.SpeechT5FeatureExtractor;T.SpeechT5ForSpeechToText;T.SpeechT5ForTextToSpeech;T.SpeechT5HifiGan;T.SpeechT5Model;T.SpeechT5PreTrainedModel;T.SpeechT5Processor;T.SpeechT5Tokenizer;T.SqueezeBertForMaskedLM;T.SqueezeBertForQuestionAnswering;T.SqueezeBertForSequenceClassification;T.SqueezeBertModel;T.SqueezeBertPreTrainedModel;T.SqueezeBertTokenizer;T.StableLmForCausalLM;T.StableLmModel;T.StableLmPreTrainedModel;T.Starcoder2ForCausalLM;T.Starcoder2Model;T.Starcoder2PreTrainedModel;T.StoppingCriteria;T.StoppingCriteriaList;T.StyleTextToSpeech2Model;T.StyleTextToSpeech2PreTrainedModel;T.SummarizationPipeline;T.SuppressTokensAtBeginLogitsProcessor;T.Swin2SRForImageSuperResolution;T.Swin2SRImageProcessor;T.Swin2SRModel;T.Swin2SRPreTrainedModel;T.SwinForImageClassification;T.SwinModel;T.SwinPreTrainedModel;T.T5ForConditionalGeneration;T.T5Model;T.T5PreTrainedModel;T.T5Tokenizer;T.TableTransformerForObjectDetection;T.TableTransformerModel;T.TableTransformerObjectDetectionOutput;T.TableTransformerPreTrainedModel;T.TemperatureLogitsWarper;T.Tensor;T.Text2TextGenerationPipeline;T.TextClassificationPipeline;T.TextGenerationPipeline;var m2=T.TextStreamer;T.TextToAudioPipeline;T.TokenClassificationPipeline;T.TokenClassifierOutput;T.TokenizerModel;T.TopKLogitsWarper;T.TopPLogitsWarper;T.TrOCRForCausalLM;T.TrOCRPreTrainedModel;T.TranslationPipeline;T.UniSpeechForCTC;T.UniSpeechForSequenceClassification;T.UniSpeechModel;T.UniSpeechPreTrainedModel;T.UniSpeechSatForAudioFrameClassification;T.UniSpeechSatForCTC;T.UniSpeechSatForSequenceClassification;T.UniSpeechSatModel;T.UniSpeechSatPreTrainedModel;T.VLChatProcessor;T.VLMImageProcessor;T.ViTFeatureExtractor;T.ViTForImageClassification;T.ViTImageProcessor;T.ViTMAEModel;T.ViTMAEPreTrainedModel;T.ViTMSNForImageClassification;T.ViTMSNModel;T.ViTMSNPreTrainedModel;T.ViTModel;T.ViTPreTrainedModel;T.VisionEncoderDecoderModel;T.VitMatteForImageMatting;T.VitMatteImageProcessor;T.VitMattePreTrainedModel;T.VitPoseForPoseEstimation;T.VitPoseImageProcessor;T.VitPosePreTrainedModel;T.VitsModel;T.VitsModelOutput;T.VitsPreTrainedModel;T.VitsTokenizer;T.Wav2Vec2BertForCTC;T.Wav2Vec2BertForSequenceClassification;T.Wav2Vec2BertModel;T.Wav2Vec2BertPreTrainedModel;T.Wav2Vec2CTCTokenizer;T.Wav2Vec2FeatureExtractor;T.Wav2Vec2ForAudioFrameClassification;T.Wav2Vec2ForCTC;T.Wav2Vec2ForSequenceClassification;T.Wav2Vec2Model;T.Wav2Vec2PreTrainedModel;T.Wav2Vec2ProcessorWithLM;T.WavLMForAudioFrameClassification;T.WavLMForCTC;T.WavLMForSequenceClassification;T.WavLMForXVector;T.WavLMModel;T.WavLMPreTrainedModel;T.WeSpeakerFeatureExtractor;T.WeSpeakerResNetModel;T.WeSpeakerResNetPreTrainedModel;T.WhisperFeatureExtractor;T.WhisperForConditionalGeneration;T.WhisperModel;T.WhisperPreTrainedModel;T.WhisperProcessor;T.WhisperTextStreamer;T.WhisperTimeStampLogitsProcessor;T.WhisperTokenizer;T.XLMForQuestionAnswering;T.XLMForSequenceClassification;T.XLMForTokenClassification;T.XLMModel;T.XLMPreTrainedModel;T.XLMRobertaForMaskedLM;T.XLMRobertaForQuestionAnswering;T.XLMRobertaForSequenceClassification;T.XLMRobertaForTokenClassification;T.XLMRobertaModel;T.XLMRobertaPreTrainedModel;T.XLMRobertaTokenizer;T.XLMTokenizer;T.XLMWithLMHeadModel;T.XVectorOutput;T.YolosFeatureExtractor;T.YolosForObjectDetection;T.YolosImageProcessor;T.YolosModel;T.YolosObjectDetectionOutput;T.YolosPreTrainedModel;T.ZeroShotAudioClassificationPipeline;T.ZeroShotClassificationPipeline;T.ZeroShotImageClassificationPipeline;T.ZeroShotObjectDetectionPipeline;T.bankers_round;T.cat;T.cos_sim;T.dot;T.dynamic_time_warping;T.env;T.full;T.full_like;T.getKeyValueShapes;T.hamming;T.hanning;T.interpolate;T.interpolate_4d;T.interpolate_data;T.is_chinese_char;T.layer_norm;T.load_image;T.log_softmax;T.magnitude;T.matmul;T.max;T.mean;T.mean_pooling;T.medianFilter;T.mel_filter_bank;T.min;T.ones;T.ones_like;T.permute;T.permute_data;var _2=T.pipeline;T.quantize_embeddings;T.rand;T.read_audio;T.rfft;T.round;T.slice;T.softmax;T.spectrogram;T.stack;T.std_mean;T.topk;T.window_function;T.zeros;T.zeros_like;var Zr;(function(r){r.Root="root",r.Text="text",r.Directive="directive",r.Comment="comment",r.Script="script",r.Style="style",r.Tag="tag",r.CDATA="cdata",r.Doctype="doctype"})(Zr||(Zr={}));function g2(r){return r.type===Zr.Tag||r.type===Zr.Script||r.type===Zr.Style}const b2=Zr.Root,y2=Zr.Text,w2=Zr.Directive,v2=Zr.Comment,E2=Zr.Script,T2=Zr.Style,x2=Zr.Tag,M2=Zr.CDATA,P2=Zr.Doctype;class sw{constructor(){this.parent=null,this.prev=null,this.next=null,this.startIndex=null,this.endIndex=null}get parentNode(){return this.parent}set parentNode(e){this.parent=e}get previousSibling(){return this.prev}set previousSibling(e){this.prev=e}get nextSibling(){return this.next}set nextSibling(e){this.next=e}cloneNode(e=!1){return hp(this,e)}}class T0 extends sw{constructor(e){super(),this.data=e}get nodeValue(){return this.data}set nodeValue(e){this.data=e}}class aw extends T0{constructor(){super(...arguments),this.type=Zr.Text}get nodeType(){return 3}}class C2 extends T0{constructor(){super(...arguments),this.type=Zr.Comment}get nodeType(){return 8}}class S2 extends T0{constructor(e,t){super(t),this.name=e,this.type=Zr.Directive}get nodeType(){return 1}}class x0 extends sw{constructor(e){super(),this.children=e}get firstChild(){var e;return(e=this.children[0])!==null&&e!==void 0?e:null}get lastChild(){return this.children.length>0?this.children[this.children.length-1]:null}get childNodes(){return this.children}set childNodes(e){this.children=e}}class A2 extends x0{constructor(){super(...arguments),this.type=Zr.CDATA}get nodeType(){return 4}}let iw=class extends x0{constructor(){super(...arguments),this.type=Zr.Root}get nodeType(){return 9}};class k2 extends x0{constructor(e,t,n=[],a=e==="script"?Zr.Script:e==="style"?Zr.Style:Zr.Tag){super(n),this.name=e,this.attribs=t,this.type=a}get nodeType(){return 1}get tagName(){return this.name}set tagName(e){this.name=e}get attributes(){return Object.keys(this.attribs).map(e=>{var t,n;return{name:e,value:this.attribs[e],namespace:(t=this["x-attribsNamespace"])===null||t===void 0?void 0:t[e],prefix:(n=this["x-attribsPrefix"])===null||n===void 0?void 0:n[e]}})}}function dr(r){return g2(r)}function M_(r){return r.type===Zr.CDATA}function Eo(r){return r.type===Zr.Text}function M0(r){return r.type===Zr.Comment}function I2(r){return r.type===Zr.Directive}function Bl(r){return r.type===Zr.Root}function Tn(r){return Object.prototype.hasOwnProperty.call(r,"children")}function hp(r,e=!1){let t;if(Eo(r))t=new aw(r.data);else if(M0(r))t=new C2(r.data);else if(dr(r)){const n=e?Mg(r.children):[],a=new k2(r.name,{...r.attribs},n);n.forEach(o=>o.parent=a),r.namespace!=null&&(a.namespace=r.namespace),r["x-attribsNamespace"]&&(a["x-attribsNamespace"]={...r["x-attribsNamespace"]}),r["x-attribsPrefix"]&&(a["x-attribsPrefix"]={...r["x-attribsPrefix"]}),t=a}else if(M_(r)){const n=e?Mg(r.children):[],a=new A2(n);n.forEach(o=>o.parent=a),t=a}else if(Bl(r)){const n=e?Mg(r.children):[],a=new iw(n);n.forEach(o=>o.parent=a),r["x-mode"]&&(a["x-mode"]=r["x-mode"]),t=a}else if(I2(r)){const n=new S2(r.name,r.data);r["x-name"]!=null&&(n["x-name"]=r["x-name"],n["x-publicId"]=r["x-publicId"],n["x-systemId"]=r["x-systemId"]),t=n}else throw new Error(`Not implemented yet: ${r.type}`);return t.startIndex=r.startIndex,t.endIndex=r.endIndex,r.sourceCodeLocation!=null&&(t.sourceCodeLocation=r.sourceCodeLocation),t}function Mg(r){const e=r.map(t=>hp(t,!0));for(let t=1;t䀾mmaĀ;d׷׸䎓;䏜reve;䄞ƀeiy؇،ؐdil;䄢rc;䄜;䐓ot;䄠r;쀀𝔊;拙pf;쀀𝔾eater̀EFGLSTصلَٖٛ٦qualĀ;Lؾؿ扥ess;招ullEqual;执reater;檢ess;扷lantEqual;橾ilde;扳cr;쀀𝒢;扫ЀAacfiosuڅڋږڛڞڪھۊRDcy;䐪Āctڐڔek;䋇;䁞irc;䄤r;愌lbertSpace;愋ǰگ\0ڲf;愍izontalLine;攀Āctۃۅòکrok;䄦mpńېۘownHumðįqual;扏܀EJOacdfgmnostuۺ۾܃܇܎ܚܞܡܨ݄ݸދޏޕcy;䐕lig;䄲cy;䐁cute耻Í䃍Āiyܓܘrc耻Î䃎;䐘ot;䄰r;愑rave耻Ì䃌ƀ;apܠܯܿĀcgܴܷr;䄪inaryI;慈lieóϝǴ݉\0ݢĀ;eݍݎ戬Āgrݓݘral;戫section;拂isibleĀCTݬݲomma;恣imes;恢ƀgptݿރވon;䄮f;쀀𝕀a;䎙cr;愐ilde;䄨ǫޚ\0ޞcy;䐆l耻Ï䃏ʀcfosuެ޷޼߂ߐĀiyޱ޵rc;䄴;䐙r;쀀𝔍pf;쀀𝕁ǣ߇\0ߌr;쀀𝒥rcy;䐈kcy;䐄΀HJacfosߤߨ߽߬߱ࠂࠈcy;䐥cy;䐌ppa;䎚Āey߶߻dil;䄶;䐚r;쀀𝔎pf;쀀𝕂cr;쀀𝒦րJTaceflmostࠥࠩࠬࡐࡣ঳সে্਷ੇcy;䐉耻<䀼ʀcmnpr࠷࠼ࡁࡄࡍute;䄹bda;䎛g;柪lacetrf;愒r;憞ƀaeyࡗ࡜ࡡron;䄽dil;䄻;䐛Āfsࡨ॰tԀACDFRTUVarࡾࢩࢱࣦ࣠ࣼयज़ΐ४Ānrࢃ࢏gleBracket;柨rowƀ;BR࢙࢚࢞憐ar;懤ightArrow;懆eiling;挈oǵࢷ\0ࣃbleBracket;柦nǔࣈ\0࣒eeVector;楡ectorĀ;Bࣛࣜ懃ar;楙loor;挊ightĀAV࣯ࣵrrow;憔ector;楎Āerँगeƀ;AVउऊऐ抣rrow;憤ector;楚iangleƀ;BEतथऩ抲ar;槏qual;抴pƀDTVषूौownVector;楑eeVector;楠ectorĀ;Bॖॗ憿ar;楘ectorĀ;B॥०憼ar;楒ightáΜs̀EFGLSTॾঋকঝঢভqualGreater;拚ullEqual;扦reater;扶ess;檡lantEqual;橽ilde;扲r;쀀𝔏Ā;eঽা拘ftarrow;懚idot;䄿ƀnpw৔ਖਛgȀLRlr৞৷ਂਐeftĀAR০৬rrow;柵ightArrow;柷ightArrow;柶eftĀarγਊightáοightáϊf;쀀𝕃erĀLRਢਬeftArrow;憙ightArrow;憘ƀchtਾੀੂòࡌ;憰rok;䅁;扪Ѐacefiosuਗ਼੝੠੷੼અઋ઎p;椅y;䐜Ādl੥੯iumSpace;恟lintrf;愳r;쀀𝔐nusPlus;戓pf;쀀𝕄cò੶;䎜ҀJacefostuણધભીଔଙඑ඗ඞcy;䐊cute;䅃ƀaey઴હાron;䅇dil;䅅;䐝ƀgswે૰଎ativeƀMTV૓૟૨ediumSpace;怋hiĀcn૦૘ë૙eryThiî૙tedĀGL૸ଆreaterGreateòٳessLesóੈLine;䀊r;쀀𝔑ȀBnptଢନଷ଺reak;恠BreakingSpace;䂠f;愕ڀ;CDEGHLNPRSTV୕ୖ୪୼஡௫ఄ౞಄ದ೘ൡඅ櫬Āou୛୤ngruent;扢pCap;扭oubleVerticalBar;戦ƀlqxஃஊ஛ement;戉ualĀ;Tஒஓ扠ilde;쀀≂̸ists;戄reater΀;EFGLSTஶஷ஽௉௓௘௥扯qual;扱ullEqual;쀀≧̸reater;쀀≫̸ess;批lantEqual;쀀⩾̸ilde;扵umpń௲௽ownHump;쀀≎̸qual;쀀≏̸eĀfsఊధtTriangleƀ;BEచఛడ拪ar;쀀⧏̸qual;括s̀;EGLSTవశ఼ౄోౘ扮qual;扰reater;扸ess;쀀≪̸lantEqual;쀀⩽̸ilde;扴estedĀGL౨౹reaterGreater;쀀⪢̸essLess;쀀⪡̸recedesƀ;ESಒಓಛ技qual;쀀⪯̸lantEqual;拠ĀeiಫಹverseElement;戌ghtTriangleƀ;BEೋೌ೒拫ar;쀀⧐̸qual;拭ĀquೝഌuareSuĀbp೨೹setĀ;E೰ೳ쀀⊏̸qual;拢ersetĀ;Eഃആ쀀⊐̸qual;拣ƀbcpഓതൎsetĀ;Eഛഞ쀀⊂⃒qual;抈ceedsȀ;ESTലള഻െ抁qual;쀀⪰̸lantEqual;拡ilde;쀀≿̸ersetĀ;E൘൛쀀⊃⃒qual;抉ildeȀ;EFT൮൯൵ൿ扁qual;扄ullEqual;扇ilde;扉erticalBar;戤cr;쀀𝒩ilde耻Ñ䃑;䎝܀Eacdfgmoprstuvලෂ෉෕ෛ෠෧෼ขภยา฿ไlig;䅒cute耻Ó䃓Āiy෎ීrc耻Ô䃔;䐞blac;䅐r;쀀𝔒rave耻Ò䃒ƀaei෮ෲ෶cr;䅌ga;䎩cron;䎟pf;쀀𝕆enCurlyĀDQฎบoubleQuote;怜uote;怘;橔Āclวฬr;쀀𝒪ash耻Ø䃘iŬื฼de耻Õ䃕es;樷ml耻Ö䃖erĀBP๋๠Āar๐๓r;怾acĀek๚๜;揞et;掴arenthesis;揜Ҁacfhilors๿ງຊຏຒດຝະ໼rtialD;戂y;䐟r;쀀𝔓i;䎦;䎠usMinus;䂱Āipຢອncareplanåڝf;愙Ȁ;eio຺ູ໠໤檻cedesȀ;EST່້໏໚扺qual;檯lantEqual;扼ilde;找me;怳Ādp໩໮uct;戏ortionĀ;aȥ໹l;戝Āci༁༆r;쀀𝒫;䎨ȀUfos༑༖༛༟OT耻"䀢r;쀀𝔔pf;愚cr;쀀𝒬؀BEacefhiorsu༾གྷཇའཱིྦྷྪྭ႖ႩႴႾarr;椐G耻®䂮ƀcnrཎནབute;䅔g;柫rĀ;tཛྷཝ憠l;椖ƀaeyཧཬཱron;䅘dil;䅖;䐠Ā;vླྀཹ愜erseĀEUྂྙĀlq྇ྎement;戋uilibrium;懋pEquilibrium;楯r»ཹo;䎡ghtЀACDFTUVa࿁࿫࿳ဢဨၛႇϘĀnr࿆࿒gleBracket;柩rowƀ;BL࿜࿝࿡憒ar;懥eftArrow;懄eiling;按oǵ࿹\0စbleBracket;柧nǔည\0နeeVector;楝ectorĀ;Bဝသ懂ar;楕loor;挋Āerိ၃eƀ;AVဵံြ抢rrow;憦ector;楛iangleƀ;BEၐၑၕ抳ar;槐qual;抵pƀDTVၣၮၸownVector;楏eeVector;楜ectorĀ;Bႂႃ憾ar;楔ectorĀ;B႑႒懀ar;楓Āpuႛ႞f;愝ndImplies;楰ightarrow;懛ĀchႹႼr;愛;憱leDelayed;槴ڀHOacfhimoqstuფჱჷჽᄙᄞᅑᅖᅡᅧᆵᆻᆿĀCcჩხHcy;䐩y;䐨FTcy;䐬cute;䅚ʀ;aeiyᄈᄉᄎᄓᄗ檼ron;䅠dil;䅞rc;䅜;䐡r;쀀𝔖ortȀDLRUᄪᄴᄾᅉownArrow»ОeftArrow»࢚ightArrow»࿝pArrow;憑gma;䎣allCircle;战pf;쀀𝕊ɲᅭ\0\0ᅰt;戚areȀ;ISUᅻᅼᆉᆯ斡ntersection;抓uĀbpᆏᆞsetĀ;Eᆗᆘ抏qual;抑ersetĀ;Eᆨᆩ抐qual;抒nion;抔cr;쀀𝒮ar;拆ȀbcmpᇈᇛሉላĀ;sᇍᇎ拐etĀ;Eᇍᇕqual;抆ĀchᇠህeedsȀ;ESTᇭᇮᇴᇿ扻qual;檰lantEqual;扽ilde;承Tháྌ;我ƀ;esሒሓሣ拑rsetĀ;Eሜም抃qual;抇et»ሓրHRSacfhiorsሾቄ቉ቕ቞ቱቶኟዂወዑORN耻Þ䃞ADE;愢ĀHc቎ቒcy;䐋y;䐦Ābuቚቜ;䀉;䎤ƀaeyብቪቯron;䅤dil;䅢;䐢r;쀀𝔗Āeiቻ኉Dzኀ\0ኇefore;戴a;䎘Ācn኎ኘkSpace;쀀  Space;怉ldeȀ;EFTካኬኲኼ戼qual;扃ullEqual;扅ilde;扈pf;쀀𝕋ipleDot;惛Āctዖዛr;쀀𝒯rok;䅦ૡዷጎጚጦ\0ጬጱ\0\0\0\0\0ጸጽ፷ᎅ\0᏿ᐄᐊᐐĀcrዻጁute耻Ú䃚rĀ;oጇገ憟cir;楉rǣጓ\0጖y;䐎ve;䅬Āiyጞጣrc耻Û䃛;䐣blac;䅰r;쀀𝔘rave耻Ù䃙acr;䅪Ādiፁ፩erĀBPፈ፝Āarፍፐr;䁟acĀekፗፙ;揟et;掵arenthesis;揝onĀ;P፰፱拃lus;抎Āgp፻፿on;䅲f;쀀𝕌ЀADETadps᎕ᎮᎸᏄϨᏒᏗᏳrrowƀ;BDᅐᎠᎤar;椒ownArrow;懅ownArrow;憕quilibrium;楮eeĀ;AᏋᏌ报rrow;憥ownáϳerĀLRᏞᏨeftArrow;憖ightArrow;憗iĀ;lᏹᏺ䏒on;䎥ing;䅮cr;쀀𝒰ilde;䅨ml耻Ü䃜ҀDbcdefosvᐧᐬᐰᐳᐾᒅᒊᒐᒖash;披ar;櫫y;䐒ashĀ;lᐻᐼ抩;櫦Āerᑃᑅ;拁ƀbtyᑌᑐᑺar;怖Ā;iᑏᑕcalȀBLSTᑡᑥᑪᑴar;戣ine;䁼eparator;杘ilde;所ThinSpace;怊r;쀀𝔙pf;쀀𝕍cr;쀀𝒱dash;抪ʀcefosᒧᒬᒱᒶᒼirc;䅴dge;拀r;쀀𝔚pf;쀀𝕎cr;쀀𝒲Ȁfiosᓋᓐᓒᓘr;쀀𝔛;䎞pf;쀀𝕏cr;쀀𝒳ҀAIUacfosuᓱᓵᓹᓽᔄᔏᔔᔚᔠcy;䐯cy;䐇cy;䐮cute耻Ý䃝Āiyᔉᔍrc;䅶;䐫r;쀀𝔜pf;쀀𝕐cr;쀀𝒴ml;䅸ЀHacdefosᔵᔹᔿᕋᕏᕝᕠᕤcy;䐖cute;䅹Āayᕄᕉron;䅽;䐗ot;䅻Dzᕔ\0ᕛoWidtè૙a;䎖r;愨pf;愤cr;쀀𝒵௡ᖃᖊᖐ\0ᖰᖶᖿ\0\0\0\0ᗆᗛᗫᙟ᙭\0ᚕ᚛ᚲᚹ\0ᚾcute耻á䃡reve;䄃̀;Ediuyᖜᖝᖡᖣᖨᖭ戾;쀀∾̳;房rc耻â䃢te肻´̆;䐰lig耻æ䃦Ā;r²ᖺ;쀀𝔞rave耻à䃠ĀepᗊᗖĀfpᗏᗔsym;愵èᗓha;䎱ĀapᗟcĀclᗤᗧr;䄁g;樿ɤᗰ\0\0ᘊʀ;adsvᗺᗻᗿᘁᘇ戧nd;橕;橜lope;橘;橚΀;elmrszᘘᘙᘛᘞᘿᙏᙙ戠;榤e»ᘙsdĀ;aᘥᘦ戡ѡᘰᘲᘴᘶᘸᘺᘼᘾ;榨;榩;榪;榫;榬;榭;榮;榯tĀ;vᙅᙆ戟bĀ;dᙌᙍ抾;榝Āptᙔᙗh;戢»¹arr;捼Āgpᙣᙧon;䄅f;쀀𝕒΀;Eaeiop዁ᙻᙽᚂᚄᚇᚊ;橰cir;橯;扊d;手s;䀧roxĀ;e዁ᚒñᚃing耻å䃥ƀctyᚡᚦᚨr;쀀𝒶;䀪mpĀ;e዁ᚯñʈilde耻ã䃣ml耻ä䃤Āciᛂᛈoninôɲnt;樑ࠀNabcdefiklnoprsu᛭ᛱᜰ᜼ᝃᝈ᝸᝽០៦ᠹᡐᜍ᤽᥈ᥰot;櫭Ācrᛶ᜞kȀcepsᜀᜅᜍᜓong;扌psilon;䏶rime;怵imĀ;e᜚᜛戽q;拍Ŷᜢᜦee;抽edĀ;gᜬᜭ挅e»ᜭrkĀ;t፜᜷brk;掶Āoyᜁᝁ;䐱quo;怞ʀcmprtᝓ᝛ᝡᝤᝨausĀ;eĊĉptyv;榰séᜌnoõēƀahwᝯ᝱ᝳ;䎲;愶een;扬r;쀀𝔟g΀costuvwឍឝឳេ៕៛៞ƀaiuបពរðݠrc;旯p»፱ƀdptឤឨឭot;樀lus;樁imes;樂ɱឹ\0\0ើcup;樆ar;昅riangleĀdu៍្own;施p;斳plus;樄eåᑄåᒭarow;植ƀako៭ᠦᠵĀcn៲ᠣkƀlst៺֫᠂ozenge;槫riangleȀ;dlr᠒᠓᠘᠝斴own;斾eft;旂ight;斸k;搣Ʊᠫ\0ᠳƲᠯ\0ᠱ;斒;斑4;斓ck;斈ĀeoᠾᡍĀ;qᡃᡆ쀀=⃥uiv;쀀≡⃥t;挐Ȁptwxᡙᡞᡧᡬf;쀀𝕓Ā;tᏋᡣom»Ꮜtie;拈؀DHUVbdhmptuvᢅᢖᢪᢻᣗᣛᣬ᣿ᤅᤊᤐᤡȀLRlrᢎᢐᢒᢔ;敗;敔;敖;敓ʀ;DUduᢡᢢᢤᢦᢨ敐;敦;敩;敤;敧ȀLRlrᢳᢵᢷᢹ;敝;敚;敜;教΀;HLRhlrᣊᣋᣍᣏᣑᣓᣕ救;敬;散;敠;敫;敢;敟ox;槉ȀLRlrᣤᣦᣨᣪ;敕;敒;攐;攌ʀ;DUduڽ᣷᣹᣻᣽;敥;敨;攬;攴inus;抟lus;択imes;抠ȀLRlrᤙᤛᤝ᤟;敛;敘;攘;攔΀;HLRhlrᤰᤱᤳᤵᤷ᤻᤹攂;敪;敡;敞;攼;攤;攜Āevģ᥂bar耻¦䂦Ȁceioᥑᥖᥚᥠr;쀀𝒷mi;恏mĀ;e᜚᜜lƀ;bhᥨᥩᥫ䁜;槅sub;柈Ŭᥴ᥾lĀ;e᥹᥺怢t»᥺pƀ;Eeįᦅᦇ;檮Ā;qۜۛೡᦧ\0᧨ᨑᨕᨲ\0ᨷᩐ\0\0᪴\0\0᫁\0\0ᬡᬮ᭍᭒\0᯽\0ᰌƀcpr᦭ᦲ᧝ute;䄇̀;abcdsᦿᧀᧄ᧊᧕᧙戩nd;橄rcup;橉Āau᧏᧒p;橋p;橇ot;橀;쀀∩︀Āeo᧢᧥t;恁îړȀaeiu᧰᧻ᨁᨅǰ᧵\0᧸s;橍on;䄍dil耻ç䃧rc;䄉psĀ;sᨌᨍ橌m;橐ot;䄋ƀdmnᨛᨠᨦil肻¸ƭptyv;榲t脀¢;eᨭᨮ䂢räƲr;쀀𝔠ƀceiᨽᩀᩍy;䑇ckĀ;mᩇᩈ朓ark»ᩈ;䏇r΀;Ecefms᩟᩠ᩢᩫ᪤᪪᪮旋;槃ƀ;elᩩᩪᩭ䋆q;扗eɡᩴ\0\0᪈rrowĀlr᩼᪁eft;憺ight;憻ʀRSacd᪒᪔᪖᪚᪟»ཇ;擈st;抛irc;抚ash;抝nint;樐id;櫯cir;槂ubsĀ;u᪻᪼晣it»᪼ˬ᫇᫔᫺\0ᬊonĀ;eᫍᫎ䀺Ā;qÇÆɭ᫙\0\0᫢aĀ;t᫞᫟䀬;䁀ƀ;fl᫨᫩᫫戁îᅠeĀmx᫱᫶ent»᫩eóɍǧ᫾\0ᬇĀ;dኻᬂot;橭nôɆƀfryᬐᬔᬗ;쀀𝕔oäɔ脀©;sŕᬝr;愗Āaoᬥᬩrr;憵ss;朗Ācuᬲᬷr;쀀𝒸Ābpᬼ᭄Ā;eᭁᭂ櫏;櫑Ā;eᭉᭊ櫐;櫒dot;拯΀delprvw᭠᭬᭷ᮂᮬᯔ᯹arrĀlr᭨᭪;椸;椵ɰ᭲\0\0᭵r;拞c;拟arrĀ;p᭿ᮀ憶;椽̀;bcdosᮏᮐᮖᮡᮥᮨ截rcap;橈Āauᮛᮞp;橆p;橊ot;抍r;橅;쀀∪︀Ȁalrv᮵ᮿᯞᯣrrĀ;mᮼᮽ憷;椼yƀevwᯇᯔᯘqɰᯎ\0\0ᯒreã᭳uã᭵ee;拎edge;拏en耻¤䂤earrowĀlrᯮ᯳eft»ᮀight»ᮽeäᯝĀciᰁᰇoninôǷnt;戱lcty;挭ঀAHabcdefhijlorstuwz᰸᰻᰿ᱝᱩᱵᲊᲞᲬᲷ᳻᳿ᴍᵻᶑᶫᶻ᷆᷍rò΁ar;楥Ȁglrs᱈ᱍ᱒᱔ger;怠eth;愸òᄳhĀ;vᱚᱛ怐»ऊūᱡᱧarow;椏aã̕Āayᱮᱳron;䄏;䐴ƀ;ao̲ᱼᲄĀgrʿᲁr;懊tseq;橷ƀglmᲑᲔᲘ耻°䂰ta;䎴ptyv;榱ĀirᲣᲨsht;楿;쀀𝔡arĀlrᲳᲵ»ࣜ»သʀaegsv᳂͸᳖᳜᳠mƀ;oș᳊᳔ndĀ;ș᳑uit;晦amma;䏝in;拲ƀ;io᳧᳨᳸䃷de脀÷;o᳧ᳰntimes;拇nø᳷cy;䑒cɯᴆ\0\0ᴊrn;挞op;挍ʀlptuwᴘᴝᴢᵉᵕlar;䀤f;쀀𝕕ʀ;emps̋ᴭᴷᴽᵂqĀ;d͒ᴳot;扑inus;戸lus;戔quare;抡blebarwedgåúnƀadhᄮᵝᵧownarrowóᲃarpoonĀlrᵲᵶefôᲴighôᲶŢᵿᶅkaro÷གɯᶊ\0\0ᶎrn;挟op;挌ƀcotᶘᶣᶦĀryᶝᶡ;쀀𝒹;䑕l;槶rok;䄑Ādrᶰᶴot;拱iĀ;fᶺ᠖斿Āah᷀᷃ròЩaòྦangle;榦Āci᷒ᷕy;䑟grarr;柿ऀDacdefglmnopqrstuxḁḉḙḸոḼṉṡṾấắẽỡἪἷὄ὎὚ĀDoḆᴴoôᲉĀcsḎḔute耻é䃩ter;橮ȀaioyḢḧḱḶron;䄛rĀ;cḭḮ扖耻ê䃪lon;払;䑍ot;䄗ĀDrṁṅot;扒;쀀𝔢ƀ;rsṐṑṗ檚ave耻è䃨Ā;dṜṝ檖ot;檘Ȁ;ilsṪṫṲṴ檙nters;揧;愓Ā;dṹṺ檕ot;檗ƀapsẅẉẗcr;䄓tyƀ;svẒẓẕ戅et»ẓpĀ1;ẝẤijạả;怄;怅怃ĀgsẪẬ;䅋p;怂ĀgpẴẸon;䄙f;쀀𝕖ƀalsỄỎỒrĀ;sỊị拕l;槣us;橱iƀ;lvỚớở䎵on»ớ;䏵ȀcsuvỪỳἋἣĀioữḱrc»Ḯɩỹ\0\0ỻíՈantĀglἂἆtr»ṝess»Ṻƀaeiἒ἖Ἒls;䀽st;扟vĀ;DȵἠD;橸parsl;槥ĀDaἯἳot;打rr;楱ƀcdiἾὁỸr;愯oô͒ĀahὉὋ;䎷耻ð䃰Āmrὓὗl耻ë䃫o;悬ƀcipὡὤὧl;䀡sôծĀeoὬὴctatioîՙnentialåչৡᾒ\0ᾞ\0ᾡᾧ\0\0ῆῌ\0ΐ\0ῦῪ \0 ⁚llingdotseñṄy;䑄male;晀ƀilrᾭᾳ῁lig;耀ffiɩᾹ\0\0᾽g;耀ffig;耀ffl;쀀𝔣lig;耀filig;쀀fjƀaltῙ῜ῡt;晭ig;耀flns;斱of;䆒ǰ΅\0ῳf;쀀𝕗ĀakֿῷĀ;vῼ´拔;櫙artint;樍Āao‌⁕Ācs‑⁒ႉ‸⁅⁈\0⁐β•‥‧‪‬\0‮耻½䂽;慓耻¼䂼;慕;慙;慛Ƴ‴\0‶;慔;慖ʴ‾⁁\0\0⁃耻¾䂾;慗;慜5;慘ƶ⁌\0⁎;慚;慝8;慞l;恄wn;挢cr;쀀𝒻ࢀEabcdefgijlnorstv₂₉₟₥₰₴⃰⃵⃺⃿℃ℒℸ̗ℾ⅒↞Ā;lٍ₇;檌ƀcmpₐₕ₝ute;䇵maĀ;dₜ᳚䎳;檆reve;䄟Āiy₪₮rc;䄝;䐳ot;䄡Ȁ;lqsؾق₽⃉ƀ;qsؾٌ⃄lanô٥Ȁ;cdl٥⃒⃥⃕c;檩otĀ;o⃜⃝檀Ā;l⃢⃣檂;檄Ā;e⃪⃭쀀⋛︀s;檔r;쀀𝔤Ā;gٳ؛mel;愷cy;䑓Ȁ;Eajٚℌℎℐ;檒;檥;檤ȀEaesℛℝ℩ℴ;扩pĀ;p℣ℤ檊rox»ℤĀ;q℮ℯ檈Ā;q℮ℛim;拧pf;쀀𝕘Āci⅃ⅆr;愊mƀ;el٫ⅎ⅐;檎;檐茀>;cdlqr׮ⅠⅪⅮⅳⅹĀciⅥⅧ;檧r;橺ot;拗Par;榕uest;橼ʀadelsↄⅪ←ٖ↛ǰ↉\0↎proø₞r;楸qĀlqؿ↖lesó₈ií٫Āen↣↭rtneqq;쀀≩︀Å↪ԀAabcefkosy⇄⇇⇱⇵⇺∘∝∯≨≽ròΠȀilmr⇐⇔⇗⇛rsðᒄf»․ilôکĀdr⇠⇤cy;䑊ƀ;cwࣴ⇫⇯ir;楈;憭ar;意irc;䄥ƀalr∁∎∓rtsĀ;u∉∊晥it»∊lip;怦con;抹r;쀀𝔥sĀew∣∩arow;椥arow;椦ʀamopr∺∾≃≞≣rr;懿tht;戻kĀlr≉≓eftarrow;憩ightarrow;憪f;쀀𝕙bar;怕ƀclt≯≴≸r;쀀𝒽asè⇴rok;䄧Ābp⊂⊇ull;恃hen»ᱛૡ⊣\0⊪\0⊸⋅⋎\0⋕⋳\0\0⋸⌢⍧⍢⍿\0⎆⎪⎴cute耻í䃭ƀ;iyݱ⊰⊵rc耻î䃮;䐸Ācx⊼⊿y;䐵cl耻¡䂡ĀfrΟ⋉;쀀𝔦rave耻ì䃬Ȁ;inoܾ⋝⋩⋮Āin⋢⋦nt;樌t;戭fin;槜ta;愩lig;䄳ƀaop⋾⌚⌝ƀcgt⌅⌈⌗r;䄫ƀelpܟ⌏⌓inåގarôܠh;䄱f;抷ed;䆵ʀ;cfotӴ⌬⌱⌽⍁are;愅inĀ;t⌸⌹戞ie;槝doô⌙ʀ;celpݗ⍌⍐⍛⍡al;抺Āgr⍕⍙eróᕣã⍍arhk;樗rod;樼Ȁcgpt⍯⍲⍶⍻y;䑑on;䄯f;쀀𝕚a;䎹uest耻¿䂿Āci⎊⎏r;쀀𝒾nʀ;EdsvӴ⎛⎝⎡ӳ;拹ot;拵Ā;v⎦⎧拴;拳Ā;iݷ⎮lde;䄩ǫ⎸\0⎼cy;䑖l耻ï䃯̀cfmosu⏌⏗⏜⏡⏧⏵Āiy⏑⏕rc;䄵;䐹r;쀀𝔧ath;䈷pf;쀀𝕛ǣ⏬\0⏱r;쀀𝒿rcy;䑘kcy;䑔Ѐacfghjos␋␖␢␧␭␱␵␻ppaĀ;v␓␔䎺;䏰Āey␛␠dil;䄷;䐺r;쀀𝔨reen;䄸cy;䑅cy;䑜pf;쀀𝕜cr;쀀𝓀஀ABEHabcdefghjlmnoprstuv⑰⒁⒆⒍⒑┎┽╚▀♎♞♥♹♽⚚⚲⛘❝❨➋⟀⠁⠒ƀart⑷⑺⑼rò৆òΕail;椛arr;椎Ā;gঔ⒋;檋ar;楢ॣ⒥\0⒪\0⒱\0\0\0\0\0⒵Ⓔ\0ⓆⓈⓍ\0⓹ute;䄺mptyv;榴raîࡌbda;䎻gƀ;dlࢎⓁⓃ;榑åࢎ;檅uo耻«䂫rЀ;bfhlpst࢙ⓞⓦⓩ⓫⓮⓱⓵Ā;f࢝ⓣs;椟s;椝ë≒p;憫l;椹im;楳l;憢ƀ;ae⓿─┄檫il;椙Ā;s┉┊檭;쀀⪭︀ƀabr┕┙┝rr;椌rk;杲Āak┢┬cĀek┨┪;䁻;䁛Āes┱┳;榋lĀdu┹┻;榏;榍Ȁaeuy╆╋╖╘ron;䄾Ādi═╔il;䄼ìࢰâ┩;䐻Ȁcqrs╣╦╭╽a;椶uoĀ;rนᝆĀdu╲╷har;楧shar;楋h;憲ʀ;fgqs▋▌উ◳◿扤tʀahlrt▘▤▷◂◨rrowĀ;t࢙□aé⓶arpoonĀdu▯▴own»њp»०eftarrows;懇ightƀahs◍◖◞rrowĀ;sࣴࢧarpoonó྘quigarro÷⇰hreetimes;拋ƀ;qs▋ও◺lanôবʀ;cdgsব☊☍☝☨c;檨otĀ;o☔☕橿Ā;r☚☛檁;檃Ā;e☢☥쀀⋚︀s;檓ʀadegs☳☹☽♉♋pproøⓆot;拖qĀgq♃♅ôউgtò⒌ôছiíলƀilr♕࣡♚sht;楼;쀀𝔩Ā;Eজ♣;檑š♩♶rĀdu▲♮Ā;l॥♳;楪lk;斄cy;䑙ʀ;achtੈ⚈⚋⚑⚖rò◁orneòᴈard;楫ri;旺Āio⚟⚤dot;䅀ustĀ;a⚬⚭掰che»⚭ȀEaes⚻⚽⛉⛔;扨pĀ;p⛃⛄檉rox»⛄Ā;q⛎⛏檇Ā;q⛎⚻im;拦Ѐabnoptwz⛩⛴⛷✚✯❁❇❐Ānr⛮⛱g;柬r;懽rëࣁgƀlmr⛿✍✔eftĀar০✇ightá৲apsto;柼ightá৽parrowĀlr✥✩efô⓭ight;憬ƀafl✶✹✽r;榅;쀀𝕝us;樭imes;樴š❋❏st;戗áፎƀ;ef❗❘᠀旊nge»❘arĀ;l❤❥䀨t;榓ʀachmt❳❶❼➅➇ròࢨorneòᶌarĀ;d྘➃;業;怎ri;抿̀achiqt➘➝ੀ➢➮➻quo;怹r;쀀𝓁mƀ;egল➪➬;檍;檏Ābu┪➳oĀ;rฟ➹;怚rok;䅂萀<;cdhilqrࠫ⟒☹⟜⟠⟥⟪⟰Āci⟗⟙;檦r;橹reå◲mes;拉arr;楶uest;橻ĀPi⟵⟹ar;榖ƀ;ef⠀भ᠛旃rĀdu⠇⠍shar;楊har;楦Āen⠗⠡rtneqq;쀀≨︀Å⠞܀Dacdefhilnopsu⡀⡅⢂⢎⢓⢠⢥⢨⣚⣢⣤ઃ⣳⤂Dot;戺Ȁclpr⡎⡒⡣⡽r耻¯䂯Āet⡗⡙;時Ā;e⡞⡟朠se»⡟Ā;sျ⡨toȀ;dluျ⡳⡷⡻owîҌefôएðᏑker;斮Āoy⢇⢌mma;権;䐼ash;怔asuredangle»ᘦr;쀀𝔪o;愧ƀcdn⢯⢴⣉ro耻µ䂵Ȁ;acdᑤ⢽⣀⣄sôᚧir;櫰ot肻·Ƶusƀ;bd⣒ᤃ⣓戒Ā;uᴼ⣘;横ţ⣞⣡p;櫛ò−ðઁĀdp⣩⣮els;抧f;쀀𝕞Āct⣸⣽r;쀀𝓂pos»ᖝƀ;lm⤉⤊⤍䎼timap;抸ఀGLRVabcdefghijlmoprstuvw⥂⥓⥾⦉⦘⧚⧩⨕⨚⩘⩝⪃⪕⪤⪨⬄⬇⭄⭿⮮ⰴⱧⱼ⳩Āgt⥇⥋;쀀⋙̸Ā;v⥐௏쀀≫⃒ƀelt⥚⥲⥶ftĀar⥡⥧rrow;懍ightarrow;懎;쀀⋘̸Ā;v⥻ే쀀≪⃒ightarrow;懏ĀDd⦎⦓ash;抯ash;抮ʀbcnpt⦣⦧⦬⦱⧌la»˞ute;䅄g;쀀∠⃒ʀ;Eiop඄⦼⧀⧅⧈;쀀⩰̸d;쀀≋̸s;䅉roø඄urĀ;a⧓⧔普lĀ;s⧓ସdz⧟\0⧣p肻 ଷmpĀ;e௹ఀʀaeouy⧴⧾⨃⨐⨓ǰ⧹\0⧻;橃on;䅈dil;䅆ngĀ;dൾ⨊ot;쀀⩭̸p;橂;䐽ash;怓΀;Aadqsxஒ⨩⨭⨻⩁⩅⩐rr;懗rĀhr⨳⨶k;椤Ā;oᏲᏰot;쀀≐̸uiöୣĀei⩊⩎ar;椨í஘istĀ;s஠டr;쀀𝔫ȀEest௅⩦⩹⩼ƀ;qs஼⩭௡ƀ;qs஼௅⩴lanô௢ií௪Ā;rஶ⪁»ஷƀAap⪊⪍⪑rò⥱rr;憮ar;櫲ƀ;svྍ⪜ྌĀ;d⪡⪢拼;拺cy;䑚΀AEadest⪷⪺⪾⫂⫅⫶⫹rò⥦;쀀≦̸rr;憚r;急Ȁ;fqs఻⫎⫣⫯tĀar⫔⫙rro÷⫁ightarro÷⪐ƀ;qs఻⪺⫪lanôౕĀ;sౕ⫴»శiíౝĀ;rవ⫾iĀ;eచథiäඐĀpt⬌⬑f;쀀𝕟膀¬;in⬙⬚⬶䂬nȀ;Edvஉ⬤⬨⬮;쀀⋹̸ot;쀀⋵̸ǡஉ⬳⬵;拷;拶iĀ;vಸ⬼ǡಸ⭁⭃;拾;拽ƀaor⭋⭣⭩rȀ;ast୻⭕⭚⭟lleì୻l;쀀⫽⃥;쀀∂̸lint;樔ƀ;ceಒ⭰⭳uåಥĀ;cಘ⭸Ā;eಒ⭽ñಘȀAait⮈⮋⮝⮧rò⦈rrƀ;cw⮔⮕⮙憛;쀀⤳̸;쀀↝̸ghtarrow»⮕riĀ;eೋೖ΀chimpqu⮽⯍⯙⬄୸⯤⯯Ȁ;cerല⯆ഷ⯉uå൅;쀀𝓃ortɭ⬅\0\0⯖ará⭖mĀ;e൮⯟Ā;q൴൳suĀbp⯫⯭å೸åഋƀbcp⯶ⰑⰙȀ;Ees⯿ⰀഢⰄ抄;쀀⫅̸etĀ;eഛⰋqĀ;qണⰀcĀ;eലⰗñസȀ;EesⰢⰣൟⰧ抅;쀀⫆̸etĀ;e൘ⰮqĀ;qൠⰣȀgilrⰽⰿⱅⱇìௗlde耻ñ䃱çృiangleĀlrⱒⱜeftĀ;eచⱚñదightĀ;eೋⱥñ೗Ā;mⱬⱭ䎽ƀ;esⱴⱵⱹ䀣ro;愖p;怇ҀDHadgilrsⲏⲔⲙⲞⲣⲰⲶⳓⳣash;抭arr;椄p;쀀≍⃒ash;抬ĀetⲨⲬ;쀀≥⃒;쀀>⃒nfin;槞ƀAetⲽⳁⳅrr;椂;쀀≤⃒Ā;rⳊⳍ쀀<⃒ie;쀀⊴⃒ĀAtⳘⳜrr;椃rie;쀀⊵⃒im;쀀∼⃒ƀAan⳰⳴ⴂrr;懖rĀhr⳺⳽k;椣Ā;oᏧᏥear;椧ቓ᪕\0\0\0\0\0\0\0\0\0\0\0\0\0ⴭ\0ⴸⵈⵠⵥ⵲ⶄᬇ\0\0ⶍⶫ\0ⷈⷎ\0ⷜ⸙⸫⸾⹃Ācsⴱ᪗ute耻ó䃳ĀiyⴼⵅrĀ;c᪞ⵂ耻ô䃴;䐾ʀabios᪠ⵒⵗLjⵚlac;䅑v;樸old;榼lig;䅓Ācr⵩⵭ir;榿;쀀𝔬ͯ⵹\0\0⵼\0ⶂn;䋛ave耻ò䃲;槁Ābmⶈ෴ar;榵Ȁacitⶕ⶘ⶥⶨrò᪀Āir⶝ⶠr;榾oss;榻nå๒;槀ƀaeiⶱⶵⶹcr;䅍ga;䏉ƀcdnⷀⷅǍron;䎿;榶pf;쀀𝕠ƀaelⷔ⷗ǒr;榷rp;榹΀;adiosvⷪⷫⷮ⸈⸍⸐⸖戨rò᪆Ȁ;efmⷷⷸ⸂⸅橝rĀ;oⷾⷿ愴f»ⷿ耻ª䂪耻º䂺gof;抶r;橖lope;橗;橛ƀclo⸟⸡⸧ò⸁ash耻ø䃸l;折iŬⸯ⸴de耻õ䃵esĀ;aǛ⸺s;樶ml耻ö䃶bar;挽ૡ⹞\0⹽\0⺀⺝\0⺢⺹\0\0⻋ຜ\0⼓\0\0⼫⾼\0⿈rȀ;astЃ⹧⹲຅脀¶;l⹭⹮䂶leìЃɩ⹸\0\0⹻m;櫳;櫽y;䐿rʀcimpt⺋⺏⺓ᡥ⺗nt;䀥od;䀮il;怰enk;怱r;쀀𝔭ƀimo⺨⺰⺴Ā;v⺭⺮䏆;䏕maô੶ne;明ƀ;tv⺿⻀⻈䏀chfork»´;䏖Āau⻏⻟nĀck⻕⻝kĀ;h⇴⻛;愎ö⇴sҀ;abcdemst⻳⻴ᤈ⻹⻽⼄⼆⼊⼎䀫cir;樣ir;樢Āouᵀ⼂;樥;橲n肻±ຝim;樦wo;樧ƀipu⼙⼠⼥ntint;樕f;쀀𝕡nd耻£䂣Ԁ;Eaceinosu່⼿⽁⽄⽇⾁⾉⾒⽾⾶;檳p;檷uå໙Ā;c໎⽌̀;acens່⽙⽟⽦⽨⽾pproø⽃urlyeñ໙ñ໎ƀaes⽯⽶⽺pprox;檹qq;檵im;拨iíໟmeĀ;s⾈ຮ怲ƀEas⽸⾐⽺ð⽵ƀdfp໬⾙⾯ƀals⾠⾥⾪lar;挮ine;挒urf;挓Ā;t໻⾴ï໻rel;抰Āci⿀⿅r;쀀𝓅;䏈ncsp;怈̀fiopsu⿚⋢⿟⿥⿫⿱r;쀀𝔮pf;쀀𝕢rime;恗cr;쀀𝓆ƀaeo⿸〉〓tĀei⿾々rnionóڰnt;樖stĀ;e【】䀿ñἙô༔઀ABHabcdefhilmnoprstux぀けさすムㄎㄫㅇㅢㅲㆎ㈆㈕㈤㈩㉘㉮㉲㊐㊰㊷ƀartぇおがròႳòϝail;検aròᱥar;楤΀cdenqrtとふへみわゔヌĀeuねぱ;쀀∽̱te;䅕iãᅮmptyv;榳gȀ;del࿑らるろ;榒;榥å࿑uo耻»䂻rր;abcfhlpstw࿜ガクシスゼゾダッデナp;極Ā;f࿠ゴs;椠;椳s;椞ë≝ð✮l;楅im;楴l;憣;憝Āaiパフil;椚oĀ;nホボ戶aló༞ƀabrョリヮrò៥rk;杳ĀakンヽcĀekヹ・;䁽;䁝Āes㄂㄄;榌lĀduㄊㄌ;榎;榐Ȁaeuyㄗㄜㄧㄩron;䅙Ādiㄡㄥil;䅗ì࿲âヺ;䑀Ȁclqsㄴㄷㄽㅄa;椷dhar;楩uoĀ;rȎȍh;憳ƀacgㅎㅟངlȀ;ipsླྀㅘㅛႜnåႻarôྩt;断ƀilrㅩဣㅮsht;楽;쀀𝔯ĀaoㅷㆆrĀduㅽㅿ»ѻĀ;l႑ㆄ;楬Ā;vㆋㆌ䏁;䏱ƀgns㆕ㇹㇼht̀ahlrstㆤㆰ㇂㇘㇤㇮rrowĀ;t࿜ㆭaéトarpoonĀduㆻㆿowîㅾp»႒eftĀah㇊㇐rrowó࿪arpoonóՑightarrows;應quigarro÷ニhreetimes;拌g;䋚ingdotseñἲƀahm㈍㈐㈓rò࿪aòՑ;怏oustĀ;a㈞㈟掱che»㈟mid;櫮Ȁabpt㈲㈽㉀㉒Ānr㈷㈺g;柭r;懾rëဃƀafl㉇㉊㉎r;榆;쀀𝕣us;樮imes;樵Āap㉝㉧rĀ;g㉣㉤䀩t;榔olint;樒arò㇣Ȁachq㉻㊀Ⴜ㊅quo;怺r;쀀𝓇Ābu・㊊oĀ;rȔȓƀhir㊗㊛㊠reåㇸmes;拊iȀ;efl㊪ၙᠡ㊫方tri;槎luhar;楨;愞ൡ㋕㋛㋟㌬㌸㍱\0㍺㎤\0\0㏬㏰\0㐨㑈㑚㒭㒱㓊㓱\0㘖\0\0㘳cute;䅛quï➺Ԁ;Eaceinpsyᇭ㋳㋵㋿㌂㌋㌏㌟㌦㌩;檴ǰ㋺\0㋼;檸on;䅡uåᇾĀ;dᇳ㌇il;䅟rc;䅝ƀEas㌖㌘㌛;檶p;檺im;择olint;樓iíሄ;䑁otƀ;be㌴ᵇ㌵担;橦΀Aacmstx㍆㍊㍗㍛㍞㍣㍭rr;懘rĀhr㍐㍒ë∨Ā;oਸ਼਴t耻§䂧i;䀻war;椩mĀin㍩ðnuóñt;朶rĀ;o㍶⁕쀀𝔰Ȁacoy㎂㎆㎑㎠rp;景Āhy㎋㎏cy;䑉;䑈rtɭ㎙\0\0㎜iäᑤaraì⹯耻­䂭Āgm㎨㎴maƀ;fv㎱㎲㎲䏃;䏂Ѐ;deglnprካ㏅㏉㏎㏖㏞㏡㏦ot;橪Ā;q኱ኰĀ;E㏓㏔檞;檠Ā;E㏛㏜檝;檟e;扆lus;樤arr;楲aròᄽȀaeit㏸㐈㐏㐗Āls㏽㐄lsetmé㍪hp;樳parsl;槤Ādlᑣ㐔e;挣Ā;e㐜㐝檪Ā;s㐢㐣檬;쀀⪬︀ƀflp㐮㐳㑂tcy;䑌Ā;b㐸㐹䀯Ā;a㐾㐿槄r;挿f;쀀𝕤aĀdr㑍ЂesĀ;u㑔㑕晠it»㑕ƀcsu㑠㑹㒟Āau㑥㑯pĀ;sᆈ㑫;쀀⊓︀pĀ;sᆴ㑵;쀀⊔︀uĀbp㑿㒏ƀ;esᆗᆜ㒆etĀ;eᆗ㒍ñᆝƀ;esᆨᆭ㒖etĀ;eᆨ㒝ñᆮƀ;afᅻ㒦ְrť㒫ֱ»ᅼaròᅈȀcemt㒹㒾㓂㓅r;쀀𝓈tmîñiì㐕aræᆾĀar㓎㓕rĀ;f㓔ឿ昆Āan㓚㓭ightĀep㓣㓪psiloîỠhé⺯s»⡒ʀbcmnp㓻㕞ሉ㖋㖎Ҁ;Edemnprs㔎㔏㔑㔕㔞㔣㔬㔱㔶抂;櫅ot;檽Ā;dᇚ㔚ot;櫃ult;櫁ĀEe㔨㔪;櫋;把lus;檿arr;楹ƀeiu㔽㕒㕕tƀ;en㔎㕅㕋qĀ;qᇚ㔏eqĀ;q㔫㔨m;櫇Ābp㕚㕜;櫕;櫓c̀;acensᇭ㕬㕲㕹㕻㌦pproø㋺urlyeñᇾñᇳƀaes㖂㖈㌛pproø㌚qñ㌗g;晪ڀ123;Edehlmnps㖩㖬㖯ሜ㖲㖴㗀㗉㗕㗚㗟㗨㗭耻¹䂹耻²䂲耻³䂳;櫆Āos㖹㖼t;檾ub;櫘Ā;dሢ㗅ot;櫄sĀou㗏㗒l;柉b;櫗arr;楻ult;櫂ĀEe㗤㗦;櫌;抋lus;櫀ƀeiu㗴㘉㘌tƀ;enሜ㗼㘂qĀ;qሢ㖲eqĀ;q㗧㗤m;櫈Ābp㘑㘓;櫔;櫖ƀAan㘜㘠㘭rr;懙rĀhr㘦㘨ë∮Ā;oਫ਩war;椪lig耻ß䃟௡㙑㙝㙠ዎ㙳㙹\0㙾㛂\0\0\0\0\0㛛㜃\0㜉㝬\0\0\0㞇ɲ㙖\0\0㙛get;挖;䏄rë๟ƀaey㙦㙫㙰ron;䅥dil;䅣;䑂lrec;挕r;쀀𝔱Ȁeiko㚆㚝㚵㚼Dz㚋\0㚑eĀ4fኄኁaƀ;sv㚘㚙㚛䎸ym;䏑Ācn㚢㚲kĀas㚨㚮pproø዁im»ኬsðኞĀas㚺㚮ð዁rn耻þ䃾Ǭ̟㛆⋧es膀×;bd㛏㛐㛘䃗Ā;aᤏ㛕r;樱;樰ƀeps㛡㛣㜀á⩍Ȁ;bcf҆㛬㛰㛴ot;挶ir;櫱Ā;o㛹㛼쀀𝕥rk;櫚á㍢rime;怴ƀaip㜏㜒㝤dåቈ΀adempst㜡㝍㝀㝑㝗㝜㝟ngleʀ;dlqr㜰㜱㜶㝀㝂斵own»ᶻeftĀ;e⠀㜾ñम;扜ightĀ;e㊪㝋ñၚot;旬inus;樺lus;樹b;槍ime;樻ezium;揢ƀcht㝲㝽㞁Āry㝷㝻;쀀𝓉;䑆cy;䑛rok;䅧Āio㞋㞎xô᝷headĀlr㞗㞠eftarro÷ࡏightarrow»ཝऀAHabcdfghlmoprstuw㟐㟓㟗㟤㟰㟼㠎㠜㠣㠴㡑㡝㡫㢩㣌㣒㣪㣶ròϭar;楣Ācr㟜㟢ute耻ú䃺òᅐrǣ㟪\0㟭y;䑞ve;䅭Āiy㟵㟺rc耻û䃻;䑃ƀabh㠃㠆㠋ròᎭlac;䅱aòᏃĀir㠓㠘sht;楾;쀀𝔲rave耻ù䃹š㠧㠱rĀlr㠬㠮»ॗ»ႃlk;斀Āct㠹㡍ɯ㠿\0\0㡊rnĀ;e㡅㡆挜r»㡆op;挏ri;旸Āal㡖㡚cr;䅫肻¨͉Āgp㡢㡦on;䅳f;쀀𝕦̀adhlsuᅋ㡸㡽፲㢑㢠ownáᎳarpoonĀlr㢈㢌efô㠭ighô㠯iƀ;hl㢙㢚㢜䏅»ᏺon»㢚parrows;懈ƀcit㢰㣄㣈ɯ㢶\0\0㣁rnĀ;e㢼㢽挝r»㢽op;挎ng;䅯ri;旹cr;쀀𝓊ƀdir㣙㣝㣢ot;拰lde;䅩iĀ;f㜰㣨»᠓Āam㣯㣲rò㢨l耻ü䃼angle;榧ހABDacdeflnoprsz㤜㤟㤩㤭㦵㦸㦽㧟㧤㧨㧳㧹㧽㨁㨠ròϷarĀ;v㤦㤧櫨;櫩asèϡĀnr㤲㤷grt;榜΀eknprst㓣㥆㥋㥒㥝㥤㦖appá␕othinçẖƀhir㓫⻈㥙opô⾵Ā;hᎷ㥢ïㆍĀiu㥩㥭gmá㎳Ābp㥲㦄setneqĀ;q㥽㦀쀀⊊︀;쀀⫋︀setneqĀ;q㦏㦒쀀⊋︀;쀀⫌︀Āhr㦛㦟etá㚜iangleĀlr㦪㦯eft»थight»ၑy;䐲ash»ံƀelr㧄㧒㧗ƀ;beⷪ㧋㧏ar;抻q;扚lip;拮Ābt㧜ᑨaòᑩr;쀀𝔳tré㦮suĀbp㧯㧱»ജ»൙pf;쀀𝕧roð໻tré㦴Ācu㨆㨋r;쀀𝓋Ābp㨐㨘nĀEe㦀㨖»㥾nĀEe㦒㨞»㦐igzag;榚΀cefoprs㨶㨻㩖㩛㩔㩡㩪irc;䅵Ādi㩀㩑Ābg㩅㩉ar;機eĀ;qᗺ㩏;扙erp;愘r;쀀𝔴pf;쀀𝕨Ā;eᑹ㩦atèᑹcr;쀀𝓌ૣណ㪇\0㪋\0㪐㪛\0\0㪝㪨㪫㪯\0\0㫃㫎\0㫘ៜ៟tré៑r;쀀𝔵ĀAa㪔㪗ròσrò৶;䎾ĀAa㪡㪤ròθrò৫að✓is;拻ƀdptឤ㪵㪾Āfl㪺ឩ;쀀𝕩imåឲĀAa㫇㫊ròώròਁĀcq㫒ីr;쀀𝓍Āpt៖㫜ré។Ѐacefiosu㫰㫽㬈㬌㬑㬕㬛㬡cĀuy㫶㫻te耻ý䃽;䑏Āiy㬂㬆rc;䅷;䑋n耻¥䂥r;쀀𝔶cy;䑗pf;쀀𝕪cr;쀀𝓎Ācm㬦㬩y;䑎l耻ÿ䃿Ԁacdefhiosw㭂㭈㭔㭘㭤㭩㭭㭴㭺㮀cute;䅺Āay㭍㭒ron;䅾;䐷ot;䅼Āet㭝㭡træᕟa;䎶r;쀀𝔷cy;䐶grarr;懝pf;쀀𝕫cr;쀀𝓏Ājn㮅㮇;怍j;怌'.split("").map(r=>r.charCodeAt(0))),O2=new Uint16Array("Ȁaglq \x1Bɭ\0\0p;䀦os;䀧t;䀾t;䀼uot;䀢".split("").map(r=>r.charCodeAt(0))),Pg;const L2=new Map([[0,65533],[128,8364],[130,8218],[131,402],[132,8222],[133,8230],[134,8224],[135,8225],[136,710],[137,8240],[138,352],[139,8249],[140,338],[142,381],[145,8216],[146,8217],[147,8220],[148,8221],[149,8226],[150,8211],[151,8212],[152,732],[153,8482],[154,353],[155,8250],[156,339],[158,382],[159,376]]),R2=(Pg=String.fromCodePoint)!==null&&Pg!==void 0?Pg:function(r){let e="";return r>65535&&(r-=65536,e+=String.fromCharCode(r>>>10&1023|55296),r=56320|r&1023),e+=String.fromCharCode(r),e};function F2(r){var e;return r>=55296&&r<=57343||r>1114111?65533:(e=L2.get(r))!==null&&e!==void 0?e:r}var Fn;(function(r){r[r.NUM=35]="NUM",r[r.SEMI=59]="SEMI",r[r.EQUALS=61]="EQUALS",r[r.ZERO=48]="ZERO",r[r.NINE=57]="NINE",r[r.LOWER_A=97]="LOWER_A",r[r.LOWER_F=102]="LOWER_F",r[r.LOWER_X=120]="LOWER_X",r[r.LOWER_Z=122]="LOWER_Z",r[r.UPPER_A=65]="UPPER_A",r[r.UPPER_F=70]="UPPER_F",r[r.UPPER_Z=90]="UPPER_Z"})(Fn||(Fn={}));const N2=32;var vi;(function(r){r[r.VALUE_LENGTH=49152]="VALUE_LENGTH",r[r.BRANCH_LENGTH=16256]="BRANCH_LENGTH",r[r.JUMP_TABLE=127]="JUMP_TABLE"})(vi||(vi={}));function n0(r){return r>=Fn.ZERO&&r<=Fn.NINE}function D2(r){return r>=Fn.UPPER_A&&r<=Fn.UPPER_F||r>=Fn.LOWER_A&&r<=Fn.LOWER_F}function B2(r){return r>=Fn.UPPER_A&&r<=Fn.UPPER_Z||r>=Fn.LOWER_A&&r<=Fn.LOWER_Z||n0(r)}function j2(r){return r===Fn.EQUALS||B2(r)}var Ln;(function(r){r[r.EntityStart=0]="EntityStart",r[r.NumericStart=1]="NumericStart",r[r.NumericDecimal=2]="NumericDecimal",r[r.NumericHex=3]="NumericHex",r[r.NamedEntity=4]="NamedEntity"})(Ln||(Ln={}));var mo;(function(r){r[r.Legacy=0]="Legacy",r[r.Strict=1]="Strict",r[r.Attribute=2]="Attribute"})(mo||(mo={}));class z2{constructor(e,t,n){this.decodeTree=e,this.emitCodePoint=t,this.errors=n,this.state=Ln.EntityStart,this.consumed=1,this.result=0,this.treeIndex=0,this.excess=1,this.decodeMode=mo.Strict}startEntity(e){this.decodeMode=e,this.state=Ln.EntityStart,this.result=0,this.treeIndex=0,this.excess=1,this.consumed=1}write(e,t){switch(this.state){case Ln.EntityStart:return e.charCodeAt(t)===Fn.NUM?(this.state=Ln.NumericStart,this.consumed+=1,this.stateNumericStart(e,t+1)):(this.state=Ln.NamedEntity,this.stateNamedEntity(e,t));case Ln.NumericStart:return this.stateNumericStart(e,t);case Ln.NumericDecimal:return this.stateNumericDecimal(e,t);case Ln.NumericHex:return this.stateNumericHex(e,t);case Ln.NamedEntity:return this.stateNamedEntity(e,t)}}stateNumericStart(e,t){return t>=e.length?-1:(e.charCodeAt(t)|N2)===Fn.LOWER_X?(this.state=Ln.NumericHex,this.consumed+=1,this.stateNumericHex(e,t+1)):(this.state=Ln.NumericDecimal,this.stateNumericDecimal(e,t))}addToNumericResult(e,t,n,a){if(t!==n){const o=n-t;this.result=this.result*Math.pow(a,o)+parseInt(e.substr(t,o),a),this.consumed+=o}}stateNumericHex(e,t){const n=t;for(;t>14;for(;t>14,o!==0){if(u===Fn.SEMI)return this.emitNamedEntityData(this.treeIndex,o,this.consumed+this.excess);this.decodeMode!==mo.Strict&&(this.result=this.treeIndex,this.consumed+=this.excess,this.excess=0)}}return-1}emitNotTerminatedNamedEntity(){var e;const{result:t,decodeTree:n}=this,a=(n[t]&vi.VALUE_LENGTH)>>14;return this.emitNamedEntityData(t,a,this.consumed),(e=this.errors)===null||e===void 0||e.missingSemicolonAfterCharacterReference(),this.consumed}emitNamedEntityData(e,t,n){const{decodeTree:a}=this;return this.emitCodePoint(t===1?a[e]&~vi.VALUE_LENGTH:a[e+1],n),t===3&&this.emitCodePoint(a[e+2],n),n}end(){var e;switch(this.state){case Ln.NamedEntity:return this.result!==0&&(this.decodeMode!==mo.Attribute||this.result===this.treeIndex)?this.emitNotTerminatedNamedEntity():0;case Ln.NumericDecimal:return this.emitNumericEntity(0,2);case Ln.NumericHex:return this.emitNumericEntity(0,3);case Ln.NumericStart:return(e=this.errors)===null||e===void 0||e.absenceOfDigitsInNumericCharacterReference(this.consumed),0;case Ln.EntityStart:return 0}}}function ow(r){let e="";const t=new z2(r,n=>e+=R2(n));return function(a,o){let u=0,d=0;for(;(d=a.indexOf("&",d))>=0;){e+=a.slice(u,d),t.startEntity(o);const h=t.write(a,d+1);if(h<0){u=d+t.end();break}u=d+h,d=h===0?u+1:u}const c=e+a.slice(u);return e="",c}}function U2(r,e,t,n){const a=(e&vi.BRANCH_LENGTH)>>7,o=e&vi.JUMP_TABLE;if(a===0)return o!==0&&n===o?t:-1;if(o){const c=n-o;return c<0||c>=a?-1:r[t+c]-1}let u=t,d=u+a-1;for(;u<=d;){const c=u+d>>>1,h=r[c];if(hn)d=c-1;else return r[c+a]}return-1}ow($2);ow(O2);const By=/["&'<>$\x80-\uFFFF]/g,V2=new Map([[34,"""],[38,"&"],[39,"'"],[60,"<"],[62,">"]]),W2=String.prototype.codePointAt!=null?(r,e)=>r.codePointAt(e):(r,e)=>(r.charCodeAt(e)&64512)===55296?(r.charCodeAt(e)-55296)*1024+r.charCodeAt(e+1)-56320+65536:r.charCodeAt(e);function uw(r){let e="",t=0,n;for(;(n=By.exec(r))!==null;){const a=n.index,o=r.charCodeAt(a),u=V2.get(o);u!==void 0?(e+=r.substring(t,a)+u,t=a+1):(e+=`${r.substring(t,a)}&#x${W2(r,a).toString(16)};`,t=By.lastIndex+=+((o&64512)===55296))}return e+r.substr(t)}function lw(r,e){return function(n){let a,o=0,u="";for(;a=r.exec(n);)o!==a.index&&(u+=n.substring(o,a.index)),u+=e.get(a[0].charCodeAt(0)),o=a.index+1;return u+n.substring(o)}}const G2=lw(/["&\u00A0]/g,new Map([[34,"""],[38,"&"],[160," "]])),H2=lw(/[&<>\u00A0]/g,new Map([[38,"&"],[60,"<"],[62,">"],[160," "]])),K2=new Map(["altGlyph","altGlyphDef","altGlyphItem","animateColor","animateMotion","animateTransform","clipPath","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","foreignObject","glyphRef","linearGradient","radialGradient","textPath"].map(r=>[r.toLowerCase(),r])),q2=new Map(["definitionURL","attributeName","attributeType","baseFrequency","baseProfile","calcMode","clipPathUnits","diffuseConstant","edgeMode","filterUnits","glyphRef","gradientTransform","gradientUnits","kernelMatrix","kernelUnitLength","keyPoints","keySplines","keyTimes","lengthAdjust","limitingConeAngle","markerHeight","markerUnits","markerWidth","maskContentUnits","maskUnits","numOctaves","pathLength","patternContentUnits","patternTransform","patternUnits","pointsAtX","pointsAtY","pointsAtZ","preserveAlpha","preserveAspectRatio","primitiveUnits","refX","refY","repeatCount","repeatDur","requiredExtensions","requiredFeatures","specularConstant","specularExponent","spreadMethod","startOffset","stdDeviation","stitchTiles","surfaceScale","systemLanguage","tableValues","targetX","targetY","textLength","viewBox","viewTarget","xChannelSelector","yChannelSelector","zoomAndPan"].map(r=>[r.toLowerCase(),r])),Z2=new Set(["style","script","xmp","iframe","noembed","noframes","plaintext","noscript"]);function Y2(r){return r.replace(/"/g,""")}function X2(r,e){var t;if(!r)return;const n=((t=e.encodeEntities)!==null&&t!==void 0?t:e.decodeEntities)===!1?Y2:e.xmlMode||e.encodeEntities!=="utf8"?uw:G2;return Object.keys(r).map(a=>{var o,u;const d=(o=r[a])!==null&&o!==void 0?o:"";return e.xmlMode==="foreign"&&(a=(u=q2.get(a))!==null&&u!==void 0?u:a),!e.emptyAttrs&&!e.xmlMode&&d===""?a:`${a}="${n(d)}"`}).join(" ")}const jy=new Set(["area","base","basefont","br","col","command","embed","frame","hr","img","input","isindex","keygen","link","meta","param","source","track","wbr"]);function P0(r,e={}){const t="length"in r?r:[r];let n="";for(let a=0;a0&&(n+=P0(r.children,e)),(e.xmlMode||!jy.has(r.name))&&(n+=``)),n}function rT(r){return`<${r.data}>`}function nT(r,e){var t;let n=r.data||"";return((t=e.encodeEntities)!==null&&t!==void 0?t:e.decodeEntities)!==!1&&!(!e.xmlMode&&r.parent&&Z2.has(r.parent.name))&&(n=e.xmlMode||e.encodeEntities!=="utf8"?uw(n):H2(n)),n}function sT(r){return``}function aT(r){return``}function cw(r,e){return P0(r,e)}function iT(r,e){return Tn(r)?r.children.map(t=>cw(t,e)).join(""):""}function Zm(r){return Array.isArray(r)?r.map(Zm).join(""):dr(r)?r.name==="br"?` `:Zm(r.children):M_(r)?Zm(r.children):Eo(r)?r.data:""}function Il(r){return Array.isArray(r)?r.map(Il).join(""):Tn(r)&&!M0(r)?Il(r.children):Eo(r)?r.data:""}function Qm(r){return Array.isArray(r)?r.map(Qm).join(""):Tn(r)&&(r.type===Zr.Tag||M_(r))?Qm(r.children):Eo(r)?r.data:""}function P_(r){return Tn(r)?r.children:[]}function dw(r){return r.parent||null}function hw(r){const e=dw(r);if(e!=null)return P_(e);const t=[r];let{prev:n,next:a}=r;for(;n!=null;)t.unshift(n),{prev:n}=n;for(;a!=null;)t.push(a),{next:a}=a;return t}function oT(r,e){var t;return(t=r.attribs)===null||t===void 0?void 0:t[e]}function uT(r,e){return r.attribs!=null&&Object.prototype.hasOwnProperty.call(r.attribs,e)&&r.attribs[e]!=null}function lT(r){return r.name}function C0(r){let{next:e}=r;for(;e!==null&&!dr(e);)({next:e}=e);return e}function S0(r){let{prev:e}=r;for(;e!==null&&!dr(e);)({prev:e}=e);return e}function Po(r){if(r.prev&&(r.prev.next=r.next),r.next&&(r.next.prev=r.prev),r.parent){const e=r.parent.children,t=e.lastIndexOf(r);t>=0&&e.splice(t,1)}r.next=null,r.prev=null,r.parent=null}function cT(r,e){const t=e.prev=r.prev;t&&(t.next=e);const n=e.next=r.next;n&&(n.prev=e);const a=e.parent=r.parent;if(a){const o=a.children;o[o.lastIndexOf(r)]=e,r.parent=null}}function dT(r,e){if(Po(e),e.next=null,e.parent=r,r.children.push(e)>1){const t=r.children[r.children.length-2];t.next=e,e.prev=t}else e.prev=null}function hT(r,e){Po(e);const{parent:t}=r,n=r.next;if(e.next=n,e.prev=r,r.next=e,e.parent=t,n){if(n.prev=e,t){const a=t.children;a.splice(a.lastIndexOf(n),0,e)}}else t&&t.children.push(e)}function fT(r,e){if(Po(e),e.parent=r,e.prev=null,r.children.unshift(e)!==1){const t=r.children[1];t.prev=e,e.next=t}else e.next=null}function pT(r,e){Po(e);const{parent:t}=r;if(t){const n=t.children;n.splice(n.indexOf(r),0,e)}r.prev&&(r.prev.next=e),e.parent=t,e.prev=r.prev,e.next=r,r.prev=e}function Ip(r,e,t=!0,n=1/0){return A0(r,Array.isArray(e)?e:[e],t,n)}function A0(r,e,t,n){const a=[],o=[Array.isArray(e)?e:[e]],u=[0];for(;;){if(u[0]>=o[0].length){if(u.length===1)return a;o.shift(),u.shift();continue}const d=o[0][u[0]++];if(r(d)&&(a.push(d),--n<=0))return a;t&&Tn(d)&&d.children.length>0&&(u.unshift(0),o.unshift(d.children))}}function mT(r,e){return e.find(r)}function k0(r,e,t=!0){const n=Array.isArray(e)?e:[e];for(let a=0;a0){const u=k0(r,o.children,!0);if(u)return u}}return null}function fw(r,e){return(Array.isArray(e)?e:[e]).some(t=>dr(t)&&r(t)||Tn(t)&&fw(r,t.children))}function _T(r,e){const t=[],n=[Array.isArray(e)?e:[e]],a=[0];for(;;){if(a[0]>=n[0].length){if(n.length===1)return t;n.shift(),a.shift();continue}const o=n[0][a[0]++];dr(o)&&r(o)&&t.push(o),Tn(o)&&o.children.length>0&&(a.unshift(0),n.unshift(o.children))}}const Jm={tag_name(r){return typeof r=="function"?e=>dr(e)&&r(e.name):r==="*"?dr:e=>dr(e)&&e.name===r},tag_type(r){return typeof r=="function"?e=>r(e.type):e=>e.type===r},tag_contains(r){return typeof r=="function"?e=>Eo(e)&&r(e.data):e=>Eo(e)&&e.data===r}};function I0(r,e){return typeof e=="function"?t=>dr(t)&&e(t.attribs[r]):t=>dr(t)&&t.attribs[r]===e}function gT(r,e){return t=>r(t)||e(t)}function pw(r){const e=Object.keys(r).map(t=>{const n=r[t];return Object.prototype.hasOwnProperty.call(Jm,t)?Jm[t](n):I0(t,n)});return e.length===0?null:e.reduce(gT)}function bT(r,e){const t=pw(r);return t?t(e):!0}function yT(r,e,t,n=1/0){const a=pw(r);return a?Ip(a,e,t,n):[]}function wT(r,e,t=!0){return Array.isArray(e)||(e=[e]),k0(I0("id",r),e,t)}function jl(r,e,t=!0,n=1/0){return Ip(Jm.tag_name(r),e,t,n)}function vT(r,e,t=!0,n=1/0){return Ip(I0("class",r),e,t,n)}function ET(r,e,t=!0,n=1/0){return Ip(Jm.tag_type(r),e,t,n)}function TT(r){let e=r.length;for(;--e>=0;){const t=r[e];if(e>0&&r.lastIndexOf(t,e-1)>=0){r.splice(e,1);continue}for(let n=t.parent;n;n=n.parent)if(r.includes(n)){r.splice(e,1);break}}return r}var Ls;(function(r){r[r.DISCONNECTED=1]="DISCONNECTED",r[r.PRECEDING=2]="PRECEDING",r[r.FOLLOWING=4]="FOLLOWING",r[r.CONTAINS=8]="CONTAINS",r[r.CONTAINED_BY=16]="CONTAINED_BY"})(Ls||(Ls={}));function mw(r,e){const t=[],n=[];if(r===e)return 0;let a=Tn(r)?r:r.parent;for(;a;)t.unshift(a),a=a.parent;for(a=Tn(e)?e:e.parent;a;)n.unshift(a),a=a.parent;const o=Math.min(t.length,n.length);let u=0;for(;uc.indexOf(_)?d===e?Ls.FOLLOWING|Ls.CONTAINED_BY:Ls.FOLLOWING:d===r?Ls.PRECEDING|Ls.CONTAINS:Ls.PRECEDING}function zl(r){return r=r.filter((e,t,n)=>!n.includes(e,t+1)),r.sort((e,t)=>{const n=mw(e,t);return n&Ls.PRECEDING?-1:n&Ls.FOLLOWING?1:0}),r}function xT(r){const e=e_(AT,r);return e?e.name==="feed"?MT(e):PT(e):null}function MT(r){var e;const t=r.children,n={type:"atom",items:jl("entry",t).map(u=>{var d;const{children:c}=u,h={media:_w(c)};ds(h,"id","id",c),ds(h,"title","title",c);const _=(d=e_("link",c))===null||d===void 0?void 0:d.attribs.href;_&&(h.link=_);const y=Ei("summary",c)||Ei("content",c);y&&(h.description=y);const w=Ei("updated",c);return w&&(h.pubDate=new Date(w)),h})};ds(n,"id","id",t),ds(n,"title","title",t);const a=(e=e_("link",t))===null||e===void 0?void 0:e.attribs.href;a&&(n.link=a),ds(n,"description","subtitle",t);const o=Ei("updated",t);return o&&(n.updated=new Date(o)),ds(n,"author","email",t,!0),n}function PT(r){var e,t;const n=(t=(e=e_("channel",r.children))===null||e===void 0?void 0:e.children)!==null&&t!==void 0?t:[],a={type:r.name.substr(0,3),id:"",items:jl("item",r.children).map(u=>{const{children:d}=u,c={media:_w(d)};ds(c,"id","guid",d),ds(c,"title","title",d),ds(c,"link","link",d),ds(c,"description","description",d);const h=Ei("pubDate",d)||Ei("dc:date",d);return h&&(c.pubDate=new Date(h)),c})};ds(a,"title","title",n),ds(a,"link","link",n),ds(a,"description","description",n);const o=Ei("lastBuildDate",n);return o&&(a.updated=new Date(o)),ds(a,"author","managingEditor",n,!0),a}const CT=["url","type","lang"],ST=["fileSize","bitrate","framerate","samplingrate","channels","duration","height","width"];function _w(r){return jl("media:content",r).map(e=>{const{attribs:t}=e,n={medium:t.medium,isDefault:!!t.isDefault};for(const a of CT)t[a]&&(n[a]=t[a]);for(const a of ST)t[a]&&(n[a]=parseInt(t[a],10));return t.expression&&(n.expression=t.expression),n})}function e_(r,e){return jl(r,e,!0,1)[0]}function Ei(r,e,t=!1){return Il(jl(r,e,t,1)).trim()}function ds(r,e,t,n,a=!1){const o=Ei(t,n,a);o&&(r[e]=o)}function AT(r){return r==="rss"||r==="feed"||r==="rdf:RDF"}var C_=Object.freeze({__proto__:null,get DocumentPosition(){return Ls},append:hT,appendChild:dT,compareDocumentPosition:mw,existsOne:fw,filter:Ip,find:A0,findAll:_T,findOne:k0,findOneChild:mT,getAttributeValue:oT,getChildren:P_,getElementById:wT,getElements:yT,getElementsByClassName:vT,getElementsByTagName:jl,getElementsByTagType:ET,getFeed:xT,getInnerHTML:iT,getName:lT,getOuterHTML:cw,getParent:dw,getSiblings:hw,getText:Zm,hasAttrib:uT,hasChildren:Tn,innerText:Qm,isCDATA:M_,isComment:M0,isDocument:Bl,isTag:dr,isText:Eo,nextElementSibling:C0,prepend:pT,prependChild:fT,prevElementSibling:S0,removeElement:Po,removeSubsets:TT,replaceElement:cT,testElement:bT,textContent:Il,uniqueSort:zl});function t_(r){const e=r??(this?this.root():[]);let t="";for(let n=0;nt.toUpperCase())}function $T(r){return r.replace(/[A-Z]/g,"-$&").toLowerCase()}function hn(r,e){const t=r.length;for(let n=0;nr.length-3)return!1;const t=r.charCodeAt(e+1);return(t>=_o.LowerA&&t<=_o.LowerZ||t>=_o.UpperA&&t<=_o.UpperZ||t===_o.Exclamation)&&r.includes(">",e+2)}const fp=Object.prototype.hasOwnProperty,pp=/\s+/,s0="data-",$0=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,LT=/^{[^]*}$|^\[[^]*]$/;function r_(r,e,t){var n;if(!(!r||!dr(r))){if((n=r.attribs)!==null&&n!==void 0||(r.attribs={}),!e)return r.attribs;if(fp.call(r.attribs,e))return!t&&$0.test(e)?e:r.attribs[e];if(r.name==="option"&&e==="value")return t_(r.children);if(r.name==="input"&&(r.attribs.type==="radio"||r.attribs.type==="checkbox")&&e==="value")return"on"}}function Al(r,e,t){t===null?bw(r,e):r.attribs[e]=`${t}`}function RT(r,e){if(typeof r=="object"||e!==void 0){if(typeof e=="function"){if(typeof r!="string")throw new Error("Bad combination of arguments.");return hn(this,(t,n)=>{dr(t)&&Al(t,r,e.call(t,n,t.attribs[r]))})}return hn(this,t=>{if(dr(t))if(typeof r=="object")for(const n of Object.keys(r)){const a=r[n];Al(t,n,a)}else Al(t,r,e)})}return arguments.length>1?this:r_(this[0],r,this.options.xmlMode)}function zy(r,e,t){return e in r?r[e]:!t&&$0.test(e)?r_(r,e,!1)!==void 0:r_(r,e,t)}function Cg(r,e,t,n){e in r?r[e]=t:Al(r,e,!n&&$0.test(e)?t?"":null:`${t}`)}function FT(r,e){var t;if(typeof r=="string"&&e===void 0){const n=this[0];if(!n||!dr(n))return;switch(r){case"style":{const a=this.css(),o=Object.keys(a);for(let u=0;u").parent().html();case"innerHTML":return this.html();default:return zy(n,r,this.options.xmlMode)}}if(typeof r=="object"||e!==void 0){if(typeof e=="function"){if(typeof r=="object")throw new TypeError("Bad combination of arguments.");return hn(this,(n,a)=>{dr(n)&&Cg(n,r,e.call(n,a,zy(n,r,this.options.xmlMode)),this.options.xmlMode)})}return hn(this,n=>{if(dr(n))if(typeof r=="object")for(const a of Object.keys(r)){const o=r[a];Cg(n,a,o,this.options.xmlMode)}else Cg(n,r,e,this.options.xmlMode)})}}function Uy(r,e,t){var n;(n=r.data)!==null&&n!==void 0||(r.data={}),typeof e=="object"?Object.assign(r.data,e):typeof e=="string"&&t!==void 0&&(r.data[e]=t)}function NT(r){for(const e of Object.keys(r.attribs)){if(!e.startsWith(s0))continue;const t=IT(e.slice(s0.length));fp.call(r.data,t)||(r.data[t]=gw(r.attribs[e]))}return r.data}function DT(r,e){const t=s0+$T(e),n=r.data;if(fp.call(n,e))return n[e];if(fp.call(r.attribs,t))return n[e]=gw(r.attribs[t])}function gw(r){if(r==="null")return null;if(r==="true")return!0;if(r==="false")return!1;const e=Number(r);if(r===String(e))return e;if(LT.test(r))try{return JSON.parse(r)}catch{}return r}function BT(r,e){var t;const n=this[0];if(!n||!dr(n))return;const a=n;return(t=a.data)!==null&&t!==void 0||(a.data={}),r==null?NT(a):typeof r=="object"||e!==void 0?(hn(this,o=>{dr(o)&&(typeof r=="object"?Uy(o,r):Uy(o,r,e))}),this):DT(a,r)}function jT(r){const e=arguments.length===0,t=this[0];if(!t||!dr(t))return e?void 0:this;switch(t.name){case"textarea":return this.text(r);case"select":{const n=this.find("option:selected");if(!e){if(this.attr("multiple")==null&&typeof r=="object")return this;this.find("option").removeAttr("selected");const a=typeof r=="object"?r:[r];for(const o of a)this.find(`option[value="${o}"]`).attr("selected","");return this}return this.attr("multiple")?n.toArray().map(a=>t_(a.children)):n.attr("value")}case"input":case"option":return e?this.attr("value"):this.attr("value",r)}}function bw(r,e){!r.attribs||!fp.call(r.attribs,e)||delete r.attribs[e]}function n_(r){return r?r.trim().split(pp):[]}function zT(r){const e=n_(r);for(const t of e)hn(this,n=>{dr(n)&&bw(n,t)});return this}function UT(r){return this.toArray().some(e=>{const t=dr(e)&&e.attribs.class;let n=-1;if(t&&r.length>0)for(;(n=t.indexOf(r,n+1))>-1;){const a=n+r.length;if((n===0||pp.test(t[n-1]))&&(a===t.length||pp.test(t[a])))return!0}return!1})}function yw(r){if(typeof r=="function")return hn(this,(n,a)=>{if(dr(n)){const o=n.attribs.class||"";yw.call([n],r.call(n,a,o))}});if(!r||typeof r!="string")return this;const e=r.split(pp),t=this.length;for(let n=0;n{dr(a)&&ww.call([a],r.call(a,o,a.attribs.class||""))});const e=n_(r),t=e.length,n=arguments.length===0;return hn(this,a=>{if(dr(a))if(n)a.attribs.class="";else{const o=n_(a.attribs.class);let u=!1;for(let d=0;d=0&&(o.splice(c,1),u=!0,d--)}u&&(a.attribs.class=o.join(" "))}})}function vw(r,e){if(typeof r=="function")return hn(this,(u,d)=>{dr(u)&&vw.call([u],r.call(u,d,u.attribs.class||"",e),e)});if(!r||typeof r!="string")return this;const t=r.split(pp),n=t.length,a=typeof e=="boolean"?e?1:-1:0,o=this.length;for(let u=0;u=0&&_<0?c.push(t[h]):a<=0&&_>=0&&c.splice(_,1)}d.attribs.class=c.join(" ")}return this}var VT=Object.freeze({__proto__:null,addClass:yw,attr:RT,data:BT,hasClass:UT,prop:FT,removeAttr:zT,removeClass:ww,toggleClass:vw,val:jT}),nr;(function(r){r.Attribute="attribute",r.Pseudo="pseudo",r.PseudoElement="pseudo-element",r.Tag="tag",r.Universal="universal",r.Adjacent="adjacent",r.Child="child",r.Descendant="descendant",r.Parent="parent",r.Sibling="sibling",r.ColumnCombinator="column-combinator"})(nr||(nr={}));var kn;(function(r){r.Any="any",r.Element="element",r.End="end",r.Equals="equals",r.Exists="exists",r.Hyphen="hyphen",r.Not="not",r.Start="start"})(kn||(kn={}));const Vy=/^[^\\#]?(?:\\(?:[\da-f]{1,6}\s?|.)|[\w\-\u00b0-\uFFFF])+/,WT=/\\([\da-f]{1,6}\s?|(\s)|.)/gi,GT=new Map([[126,kn.Element],[94,kn.Start],[36,kn.End],[42,kn.Any],[33,kn.Not],[124,kn.Hyphen]]),HT=new Set(["has","not","matches","is","where","host","host-context"]);function np(r){switch(r.type){case nr.Adjacent:case nr.Child:case nr.Descendant:case nr.Parent:case nr.Sibling:case nr.ColumnCombinator:return!0;default:return!1}}const KT=new Set(["contains","icontains"]);function qT(r,e,t){const n=parseInt(e,16)-65536;return n!==n||t?e:n<0?String.fromCharCode(n+65536):String.fromCharCode(n>>10|55296,n&1023|56320)}function Xf(r){return r.replace(WT,qT)}function Sg(r){return r===39||r===34}function Wy(r){return r===32||r===9||r===10||r===12||r===13}function S_(r){const e=[],t=Ew(e,`${r}`,0);if(t0&&t0&&np(n[n.length-1]))throw new Error("Did not expect successive traversals.")}function h(w){if(n.length>0&&n[n.length-1].type===nr.Descendant){n[n.length-1].type=w;return}c(),n.push({type:w})}function _(w,M){n.push({type:nr.Attribute,name:w,action:M,value:a(1),namespace:null,ignoreCase:"quirks"})}function y(){if(n.length&&n[n.length-1].type===nr.Descendant&&n.pop(),n.length===0)throw new Error("Empty sub-selector");r.push(n)}if(o(0),e.length===t)return t;e:for(;t=0&&n>=1)):r.type===nr.Pseudo&&(r.data?r.name==="has"||r.name==="contains"?n=0:Array.isArray(r.data)?(n=Math.min(...r.data.map(a=>Math.min(...a.map(xw)))),n<0&&(n=0)):n=2:n=3),n}const XT=/[-[\]{}()*+?.,\\^$|#\s]/g;function Gy(r){return r.replace(XT,"\\$&")}const QT=new Set(["accept","accept-charset","align","alink","axis","bgcolor","charset","checked","clear","codetype","color","compact","declare","defer","dir","direction","disabled","enctype","face","frame","hreflang","http-equiv","lang","language","link","media","method","multiple","nohref","noresize","noshade","nowrap","readonly","rel","rev","rules","scope","scrolling","selected","shape","target","text","type","valign","valuetype","vlink"]);function po(r,e){return typeof r.ignoreCase=="boolean"?r.ignoreCase:r.ignoreCase==="quirks"?!!e.quirksMode:!e.xmlMode&&QT.has(r.name)}const JT={equals(r,e,t){const{adapter:n}=t,{name:a}=e;let{value:o}=e;return po(e,t)?(o=o.toLowerCase(),u=>{const d=n.getAttributeValue(u,a);return d!=null&&d.length===o.length&&d.toLowerCase()===o&&r(u)}):u=>n.getAttributeValue(u,a)===o&&r(u)},hyphen(r,e,t){const{adapter:n}=t,{name:a}=e;let{value:o}=e;const u=o.length;return po(e,t)?(o=o.toLowerCase(),function(c){const h=n.getAttributeValue(c,a);return h!=null&&(h.length===u||h.charAt(u)==="-")&&h.substr(0,u).toLowerCase()===o&&r(c)}):function(c){const h=n.getAttributeValue(c,a);return h!=null&&(h.length===u||h.charAt(u)==="-")&&h.substr(0,u)===o&&r(c)}},element(r,e,t){const{adapter:n}=t,{name:a,value:o}=e;if(/\s/.test(o))return Mr.falseFunc;const u=new RegExp(`(?:^|\\s)${Gy(o)}(?:$|\\s)`,po(e,t)?"i":"");return function(c){const h=n.getAttributeValue(c,a);return h!=null&&h.length>=o.length&&u.test(h)&&r(c)}},exists(r,{name:e},{adapter:t}){return n=>t.hasAttrib(n,e)&&r(n)},start(r,e,t){const{adapter:n}=t,{name:a}=e;let{value:o}=e;const u=o.length;return u===0?Mr.falseFunc:po(e,t)?(o=o.toLowerCase(),d=>{const c=n.getAttributeValue(d,a);return c!=null&&c.length>=u&&c.substr(0,u).toLowerCase()===o&&r(d)}):d=>{var c;return!!(!((c=n.getAttributeValue(d,a))===null||c===void 0)&&c.startsWith(o))&&r(d)}},end(r,e,t){const{adapter:n}=t,{name:a}=e;let{value:o}=e;const u=-o.length;return u===0?Mr.falseFunc:po(e,t)?(o=o.toLowerCase(),d=>{var c;return((c=n.getAttributeValue(d,a))===null||c===void 0?void 0:c.substr(u).toLowerCase())===o&&r(d)}):d=>{var c;return!!(!((c=n.getAttributeValue(d,a))===null||c===void 0)&&c.endsWith(o))&&r(d)}},any(r,e,t){const{adapter:n}=t,{name:a,value:o}=e;if(o==="")return Mr.falseFunc;if(po(e,t)){const u=new RegExp(Gy(o),"i");return function(c){const h=n.getAttributeValue(c,a);return h!=null&&h.length>=o.length&&u.test(h)&&r(c)}}return u=>{var d;return!!(!((d=n.getAttributeValue(u,a))===null||d===void 0)&&d.includes(o))&&r(u)}},not(r,e,t){const{adapter:n}=t,{name:a}=e;let{value:o}=e;return o===""?u=>!!n.getAttributeValue(u,a)&&r(u):po(e,t)?(o=o.toLowerCase(),u=>{const d=n.getAttributeValue(u,a);return(d==null||d.length!==o.length||d.toLowerCase()!==o)&&r(u)}):u=>n.getAttributeValue(u,a)!==o&&r(u)}},ex=new Set([9,10,12,13,32]),Hy=48,tx=57;function rx(r){if(r=r.trim().toLowerCase(),r==="even")return[2,0];if(r==="odd")return[2,1];let e=0,t=0,n=o(),a=u();if(e=Hy&&r.charCodeAt(e)<=tx;)h=h*10+(r.charCodeAt(e)-Hy),e++;return e===c?null:h}function d(){for(;eo<=t;if(e===0)return o=>o===t;if(e===1)return t<0?Mr.trueFunc:o=>o>=t;const n=Math.abs(e),a=(t%n+n)%n;return e>1?o=>o>=t&&o%n===a:o=>o<=t&&o%n===a}function Bm(r){return nx(rx(r))}function jm(r,e){return t=>{const n=e.getParent(t);return n!=null&&e.isTag(n)&&r(t)}}const a0={contains(r,e,{adapter:t}){return function(a){return r(a)&&t.getText(a).includes(e)}},icontains(r,e,{adapter:t}){const n=e.toLowerCase();return function(o){return r(o)&&t.getText(o).toLowerCase().includes(n)}},"nth-child"(r,e,{adapter:t,equals:n}){const a=Bm(e);return a===Mr.falseFunc?Mr.falseFunc:a===Mr.trueFunc?jm(r,t):function(u){const d=t.getSiblings(u);let c=0;for(let h=0;h=0&&!n(u,d[h]);h--)t.isTag(d[h])&&c++;return a(c)&&r(u)}},"nth-of-type"(r,e,{adapter:t,equals:n}){const a=Bm(e);return a===Mr.falseFunc?Mr.falseFunc:a===Mr.trueFunc?jm(r,t):function(u){const d=t.getSiblings(u);let c=0;for(let h=0;h=0;h--){const _=d[h];if(n(u,_))break;t.isTag(_)&&t.getName(_)===t.getName(u)&&c++}return a(c)&&r(u)}},root(r,e,{adapter:t}){return n=>{const a=t.getParent(n);return(a==null||!t.isTag(a))&&r(n)}},scope(r,e,t,n){const{equals:a}=t;return!n||n.length===0?a0.root(r,e,t):n.length===1?o=>a(n[0],o)&&r(o):o=>n.includes(o)&&r(o)},hover:Ag("isHovered"),visited:Ag("isVisited"),active:Ag("isActive")};function Ag(r){return function(t,n,{adapter:a}){const o=a[r];return typeof o!="function"?Mr.falseFunc:function(d){return o(d)&&t(d)}}}const Ky={empty(r,{adapter:e}){return!e.getChildren(r).some(t=>e.isTag(t)||e.getText(t)!=="")},"first-child"(r,{adapter:e,equals:t}){if(e.prevElementSibling)return e.prevElementSibling(r)==null;const n=e.getSiblings(r).find(a=>e.isTag(a));return n!=null&&t(r,n)},"last-child"(r,{adapter:e,equals:t}){const n=e.getSiblings(r);for(let a=n.length-1;a>=0;a--){if(t(r,n[a]))return!0;if(e.isTag(n[a]))break}return!1},"first-of-type"(r,{adapter:e,equals:t}){const n=e.getSiblings(r),a=e.getName(r);for(let o=0;o=0;o--){const u=n[o];if(t(r,u))return!0;if(e.isTag(u)&&e.getName(u)===a)break}return!1},"only-of-type"(r,{adapter:e,equals:t}){const n=e.getName(r);return e.getSiblings(r).every(a=>t(r,a)||!e.isTag(a)||e.getName(a)!==n)},"only-child"(r,{adapter:e,equals:t}){return e.getSiblings(r).every(n=>t(r,n)||!e.isTag(n))}};function qy(r,e,t,n){if(t===null){if(r.length>n)throw new Error(`Pseudo-class :${e} requires an argument`)}else if(r.length===n)throw new Error(`Pseudo-class :${e} doesn't have any arguments`)}const sx={"any-link":":is(a, area, link)[href]",link:":any-link:not(:visited)",disabled:`:is( :is(button, input, select, textarea, optgroup, option)[disabled], optgroup[disabled] > option, fieldset[disabled]:not(fieldset[disabled] legend:first-of-type *) )`,enabled:":not(:disabled)",checked:":is(:is(input[type=radio], input[type=checkbox])[checked], option:selected)",required:":is(input, select, textarea)[required]",optional:":is(input, select, textarea):not([required])",selected:"option:is([selected], select:not([multiple]):not(:has(> option[selected])) > :first-of-type)",checkbox:"[type=checkbox]",file:"[type=file]",password:"[type=password]",radio:"[type=radio]",reset:"[type=reset]",image:"[type=image]",submit:"[type=submit]",parent:":not(:empty)",header:":is(h1, h2, h3, h4, h5, h6)",button:":is(button, input[type=button])",input:":is(input, textarea, select, button)",text:"input:is(:not([type!='']), [type=text])"},Mw={};function ax(r,e){return r===Mr.falseFunc?Mr.falseFunc:t=>e.isTag(t)&&r(t)}function Pw(r,e){const t=e.getSiblings(r);if(t.length<=1)return[];const n=t.indexOf(r);return n<0||n===t.length-1?[]:t.slice(n+1).filter(e.isTag)}function i0(r){return{xmlMode:!!r.xmlMode,lowerCaseAttributeNames:!!r.lowerCaseAttributeNames,lowerCaseTags:!!r.lowerCaseTags,quirksMode:!!r.quirksMode,cacheResults:!!r.cacheResults,pseudos:r.pseudos,adapter:r.adapter,equals:r.equals}}const kg=(r,e,t,n,a)=>{const o=a(e,i0(t),n);return o===Mr.trueFunc?r:o===Mr.falseFunc?Mr.falseFunc:u=>o(u)&&r(u)},Ig={is:kg,matches:kg,where:kg,not(r,e,t,n,a){const o=a(e,i0(t),n);return o===Mr.falseFunc?r:o===Mr.trueFunc?Mr.falseFunc:u=>!o(u)&&r(u)},has(r,e,t,n,a){const{adapter:o}=t,u=i0(t);u.relativeSelector=!0;const d=e.some(_=>_.some(O0))?[Mw]:void 0,c=a(e,u,d);if(c===Mr.falseFunc)return Mr.falseFunc;const h=ax(c,o);if(d&&c!==Mr.trueFunc){const{shouldTestNextSiblings:_=!1}=c;return y=>{if(!r(y))return!1;d[0]=y;const w=o.getChildren(y),M=_?[...w,...Pw(y,o)]:w;return o.existsOne(h,M)}}return _=>r(_)&&o.existsOne(h,o.getChildren(_))}};function ix(r,e,t,n,a){var o;const{name:u,data:d}=e;if(Array.isArray(d)){if(!(u in Ig))throw new Error(`Unknown pseudo-class :${u}(${d})`);return Ig[u](r,d,t,n,a)}const c=(o=t.pseudos)===null||o===void 0?void 0:o[u],h=typeof c=="string"?c:sx[u];if(typeof h=="string"){if(d!=null)throw new Error(`Pseudo ${u} doesn't have any arguments`);const _=S_(h);return Ig.is(r,_,t,n,a)}if(typeof c=="function")return qy(c,u,d,1),_=>c(_,d)&&r(_);if(u in a0)return a0[u](r,d,t,n);if(u in Ky){const _=Ky[u];return qy(_,u,d,2),y=>_(y,t,d)&&r(y)}throw new Error(`Unknown pseudo-class :${u}`)}function $g(r,e){const t=e.getParent(r);return t&&e.isTag(t)?t:null}function ox(r,e,t,n,a){const{adapter:o,equals:u}=t;switch(e.type){case nr.PseudoElement:throw new Error("Pseudo-elements are not supported by css-select");case nr.ColumnCombinator:throw new Error("Column combinators are not yet supported by css-select");case nr.Attribute:{if(e.namespace!=null)throw new Error("Namespaced attributes are not yet supported by css-select");return(!t.xmlMode||t.lowerCaseAttributeNames)&&(e.name=e.name.toLowerCase()),JT[e.action](r,e,t)}case nr.Pseudo:return ix(r,e,t,n,a);case nr.Tag:{if(e.namespace!=null)throw new Error("Namespaced tag names are not yet supported by css-select");let{name:d}=e;return(!t.xmlMode||t.lowerCaseTags)&&(d=d.toLowerCase()),function(h){return o.getName(h)===d&&r(h)}}case nr.Descendant:{if(t.cacheResults===!1||typeof WeakSet>"u")return function(h){let _=h;for(;_=$g(_,o);)if(r(_))return!0;return!1};const d=new WeakSet;return function(h){let _=h;for(;_=$g(_,o);)if(!d.has(_)){if(o.isTag(_)&&r(_))return!0;d.add(_)}return!1}}case"_flexibleDescendant":return function(c){let h=c;do if(r(h))return!0;while(h=$g(h,o));return!1};case nr.Parent:return function(c){return o.getChildren(c).some(h=>o.isTag(h)&&r(h))};case nr.Child:return function(c){const h=o.getParent(c);return h!=null&&o.isTag(h)&&r(h)};case nr.Sibling:return function(c){const h=o.getSiblings(c);for(let _=0;_e.some(Cw)))}const ux={type:nr.Descendant},lx={type:"_flexibleDescendant"},cx={type:nr.Pseudo,name:"scope",data:null};function dx(r,{adapter:e},t){const n=!!(t!=null&&t.every(a=>{const o=e.isTag(a)&&e.getParent(a);return a===Mw||o&&e.isTag(o)}));for(const a of r){if(!(a.length>0&&O0(a[0])&&a[0].type!==nr.Descendant))if(n&&!a.some(Cw))a.unshift(ux);else continue;a.unshift(cx)}}function Sw(r,e,t){var n;r.forEach(YT),t=(n=e.context)!==null&&n!==void 0?n:t;const a=Array.isArray(t),o=t&&(Array.isArray(t)?t:[t]);if(e.relativeSelector!==!1)dx(r,e,o);else if(r.some(c=>c.length>0&&O0(c[0])))throw new Error("Relative selectors are not allowed when the `relativeSelector` option is disabled");let u=!1;const d=r.map(c=>{if(c.length>=2){const[h,_]=c;h.type!==nr.Pseudo||h.name!=="scope"||(a&&_.type===nr.Descendant?c[1]=lx:(_.type===nr.Adjacent||_.type===nr.Sibling)&&(u=!0))}return hx(c,e,o)}).reduce(fx,Mr.falseFunc);return d.shouldTestNextSiblings=u,d}function hx(r,e,t){var n;return r.reduce((a,o)=>a===Mr.falseFunc?Mr.falseFunc:ox(a,o,e,t,Sw),(n=e.rootFunc)!==null&&n!==void 0?n:Mr.trueFunc)}function fx(r,e){return e===Mr.falseFunc||r===Mr.trueFunc?r:r===Mr.falseFunc||e===Mr.trueFunc?e:function(n){return r(n)||e(n)}}const Aw=(r,e)=>r===e,px={adapter:C_,equals:Aw};function mx(r){var e,t,n,a;const o=r??px;return(e=o.adapter)!==null&&e!==void 0||(o.adapter=C_),(t=o.equals)!==null&&t!==void 0||(o.equals=(a=(n=o.adapter)===null||n===void 0?void 0:n.equals)!==null&&a!==void 0?a:Aw),o}function _x(r){return function(t,n,a){const o=mx(n);return r(t,o,a)}}const L0=_x(Sw);function kw(r,e,t=!1){return t&&(r=gx(r,e)),Array.isArray(r)?e.removeSubsets(r):e.getChildren(r)}function gx(r,e){const t=Array.isArray(r)?r.slice(0):[r],n=t.length;for(let a=0;ae.some(a_)):!1}function yx(r,e,t){const n=e!=null?parseInt(e,10):NaN;switch(r){case"first":return 1;case"nth":case"eq":return isFinite(n)?n>=0?n+1:1/0:0;case"lt":return isFinite(n)?n>=0?Math.min(n,t):1/0:0;case"gt":return isFinite(n)?1/0:0;case"odd":return 2*t;case"even":return 2*t-1;case"last":case"not":return 1/0}}function wx(r){for(;r.parent;)r=r.parent;return r}function R0(r){const e=[],t=[];for(const n of r)n.some(a_)?e.push(n):t.push(n);return[t,e]}const vx={type:nr.Universal,namespace:null},Ex={type:nr.Pseudo,name:"scope",data:null};function Iw(r,e,t={}){return $w([r],e,t)}function $w(r,e,t={}){if(typeof e=="function")return r.some(e);const[n,a]=R0(S_(e));return n.length>0&&r.some(L0(n,t))||a.some(o=>Rw(o,r,t).length>0)}function Tx(r,e,t,n){const a=typeof t=="string"?parseInt(t,10):NaN;switch(r){case"first":case"lt":return e;case"last":return e.length>0?[e[e.length-1]]:e;case"nth":case"eq":return isFinite(a)&&Math.abs(a)u%2===0);case"odd":return e.filter((o,u)=>u%2===1);case"not":{const o=new Set(Lw(t,e,n));return e.filter(u=>!o.has(u))}}}function Ow(r,e,t={}){return Lw(S_(r),e,t)}function Lw(r,e,t){if(e.length===0)return[];const[n,a]=R0(r);let o;if(n.length){const u=u0(e,n,t);if(a.length===0)return u;u.length&&(o=new Set(u))}for(let u=0;udr(_)&&!o.has(_)):e).length===0)break;const h=Rw(d,e,t);if(h.length)if(o)h.forEach(_=>o.add(_));else{if(u===a.length-1)return h;o=new Set(h)}}return typeof o<"u"?o.size===e.length?e:e.filter(u=>o.has(u)):[]}function Rw(r,e,t){var n;if(r.some(np)){const a=(n=t.root)!==null&&n!==void 0?n:wx(e[0]),o={...t,context:e,relativeSelector:!1};return r.push(Ex),i_(a,r,o,!0,e.length)}return i_(e,r,t,!1,e.length)}function xx(r,e,t={},n=1/0){if(typeof r=="function")return Fw(e,r);const[a,o]=R0(S_(r)),u=o.map(d=>i_(e,d,t,!0,n));return a.length&&u.push(o0(e,a,t,n)),u.length===0?[]:u.length===1?u[0]:zl(u.reduce((d,c)=>[...d,...c]))}function i_(r,e,t,n,a){const o=e.findIndex(a_),u=e.slice(0,o),d=e[o],c=e.length-1===o?a:1/0,h=yx(d.name,d.data,c);if(h===0)return[];const y=(u.length===0&&!Array.isArray(r)?P_(r).filter(dr):u.length===0?(Array.isArray(r)?r:[r]).filter(dr):n||u.some(np)?o0(r,[u],t,h):u0(r,[u],t)).slice(0,h);let w=Tx(d.name,y,d.data,t);if(w.length===0||e.length===o+1)return w;const M=e.slice(o+1),S=M.some(np);if(S){if(np(M[0])){const{type:G}=M[0];(G===nr.Sibling||G===nr.Adjacent)&&(w=kw(w,C_,!0)),M.unshift(vx)}t={...t,relativeSelector:!1,rootFunc:G=>w.includes(G)}}else t.rootFunc&&t.rootFunc!==s_.trueFunc&&(t={...t,rootFunc:s_.trueFunc});return M.some(a_)?i_(w,M,t,!1,a):S?o0(w,[M],t,a):u0(w,[M],t)}function o0(r,e,t,n){const a=L0(e,t,r);return Fw(r,a,n)}function Fw(r,e,t=1/0){const n=kw(r,C_,e.shouldTestNextSiblings);return A0(a=>dr(a)&&e(a),n,!0,t)}function u0(r,e,t){const n=(Array.isArray(r)?r:[r]).filter(dr);if(n.length===0)return n;const a=L0(e,t);return a===s_.trueFunc?n:n.filter(a)}const Mx=/^\s*[+~]/;function Px(r){if(!r)return this._make([]);if(typeof r!="string"){const e=Ul(r)?r.toArray():[r],t=this.toArray();return this._make(e.filter(n=>t.some(a=>kT(a,n))))}return this._findBySelector(r,Number.POSITIVE_INFINITY)}function Cx(r,e){var t;const n=this.toArray(),a=Mx.test(r)?n:this.children().toArray(),o={context:n,root:(t=this._root)===null||t===void 0?void 0:t[0],xmlMode:this.options.xmlMode,lowerCaseTags:this.options.lowerCaseTags,lowerCaseAttributeNames:this.options.lowerCaseAttributeNames,pseudos:this.options.pseudos,quirksMode:this.options.quirksMode};return this._make(xx(r,a,o,e))}function F0(r){return function(e,...t){return function(n){var a;let o=r(e,this);return n&&(o=B0(o,n,this.options.xmlMode,(a=this._root)===null||a===void 0?void 0:a[0])),this._make(this.length>1&&o.length>1?t.reduce((u,d)=>d(u),o):o)}}}const $p=F0((r,e)=>{let t=[];for(let n=0;n0&&(t=t.concat(a))}return t}),N0=F0((r,e)=>{const t=[];for(let n=0;n{const u=[];return hn(o,d=>{for(let c;(c=a(d))&&!(t!=null&&t(c,u.length));d=c)u.push(c)}),u})(r,...e);return function(a,o){t=typeof a=="string"?d=>Iw(d,a,this.options):a?Op(a):null;const u=n.call(this,o);return t=null,u}}function Vl(r){return r.length>1?Array.from(new Set(r)):r}const Sx=N0(({parent:r})=>r&&!Bl(r)?r:null,Vl),Ax=$p(r=>{const e=[];for(;r.parent&&!Bl(r.parent);)e.push(r.parent),r=r.parent;return e},zl,r=>r.reverse()),kx=D0(({parent:r})=>r&&!Bl(r)?r:null,zl,r=>r.reverse());function Ix(r){var e;const t=[];if(!r)return this._make(t);const n={xmlMode:this.options.xmlMode,root:(e=this._root)===null||e===void 0?void 0:e[0]},a=typeof r=="string"?o=>Iw(o,r,n):Op(r);return hn(this,o=>{for(o&&!Bl(o)&&!dr(o)&&(o=o.parent);o&&dr(o);){if(a(o,0)){t.includes(o)||t.push(o);break}o=o.parent}}),this._make(t)}const $x=N0(r=>C0(r)),Ox=$p(r=>{const e=[];for(;r.next;)r=r.next,dr(r)&&e.push(r);return e},Vl),Lx=D0(r=>C0(r),Vl),Rx=N0(r=>S0(r)),Fx=$p(r=>{const e=[];for(;r.prev;)r=r.prev,dr(r)&&e.push(r);return e},Vl),Nx=D0(r=>S0(r),Vl),Dx=$p(r=>hw(r).filter(e=>dr(e)&&e!==r),zl),Bx=$p(r=>P_(r).filter(dr),Vl);function jx(){const r=this.toArray().reduce((e,t)=>Tn(t)?e.concat(t.children):e,[]);return this._make(r)}function zx(r){let e=0;const t=this.length;for(;er.call(e,t,e):Ul(r)?e=>Array.prototype.includes.call(r,e):function(e){return r===e}}function Vx(r){var e;return this._make(B0(this.toArray(),r,this.options.xmlMode,(e=this._root)===null||e===void 0?void 0:e[0]))}function B0(r,e,t,n){return typeof e=="string"?Ow(e,r,{xmlMode:t,root:n}):r.filter(Op(e))}function Wx(r){const e=this.toArray();return typeof r=="string"?$w(e.filter(dr),r,this.options):r?e.some(Op(r)):!1}function Gx(r){let e=this.toArray();if(typeof r=="string"){const t=new Set(Ow(r,e,this.options));e=e.filter(n=>!t.has(n))}else{const t=Op(r);e=e.filter((n,a)=>!t(n,a))}return this._make(e)}function Hx(r){return this.filter(typeof r=="string"?`:has(${r})`:(e,t)=>this._make(t).find(r).length>0)}function Kx(){return this.length>1?this._make(this[0]):this}function qx(){return this.length>0?this._make(this[this.length-1]):this}function Zx(r){var e;return r=+r,r===0&&this.length<=1?this:(r<0&&(r=this.length+r),this._make((e=this[r])!==null&&e!==void 0?e:[]))}function Yx(r){return r==null?this.toArray():this[r<0?this.length+r:r]}function Xx(){return Array.prototype.slice.call(this)}function Qx(r){let e,t;return r==null?(e=this.parent().children(),t=this[0]):typeof r=="string"?(e=this._make(r),t=this[0]):(e=this,t=Ul(r)?r[0]:r),Array.prototype.indexOf.call(e,t)}function Jx(r,e){return this._make(Array.prototype.slice.call(this,r,e))}function eM(){var r;return(r=this.prevObject)!==null&&r!==void 0?r:this._make([])}function tM(r,e){const t=this._make(r,e),n=zl([...this.get(),...t.get()]);return this._make(n)}function rM(r){return this.prevObject?this.add(r?this.prevObject.filter(r):this.prevObject):this}var nM=Object.freeze({__proto__:null,_findBySelector:Cx,add:tM,addBack:rM,children:Bx,closest:Ix,contents:jx,each:zx,end:eM,eq:Zx,filter:Vx,filterArray:B0,find:Px,first:Kx,get:Yx,has:Hx,index:Qx,is:Wx,last:qx,map:Ux,next:$x,nextAll:Ox,nextUntil:Lx,not:Gx,parent:Sx,parents:Ax,parentsUntil:kx,prev:Rx,prevAll:Fx,prevUntil:Nx,siblings:Dx,slice:Jx,toArray:Xx});function $l(r,e){const t=Array.isArray(r)?r:[r];e?e.children=t:e=null;for(let n=0;n{if(!Tn(n))return;const o=typeof e[0]=="function"?e[0].call(n,a,this._render(n.children)):e,u=this._makeDomArray(o,a=r.length?null:r[e+t];for(let _=0;_-1&&(w.children.splice(S,1),a===w&&e>S&&d[0]--)}y.parent=a,y.prev&&(y.prev.next=(o=y.next)!==null&&o!==void 0?o:null),y.next&&(y.next.prev=(u=y.prev)!==null&&u!==void 0?u:null),y.prev=_===0?c:n[_-1],y.next=_===n.length-1?h:n[_+1]}return c&&(c.next=n[0]),h&&(h.prev=n[n.length-1]),r.splice(...d)}function aM(r){return(Ul(r)?r:this._make(r)).append(this),this}function iM(r){return(Ul(r)?r:this._make(r)).prepend(this),this}const oM=Nw((r,e,t)=>{Ii(e,e.length,0,r,t)}),uM=Nw((r,e,t)=>{Ii(e,0,0,r,t)});function Dw(r){return function(e){const t=this.length-1,n=this.parents().last();for(let a=0;a{const{parent:n}=r;if(!n)return;const a=n.children,o=a.indexOf(r);$l([r],e),Ii(a,o,0,t,n)}),cM=Dw((r,e,t)=>{Tn(r)&&($l(r.children,e),$l(t,r))});function dM(r){return this.parent(r).not("body").each((e,t)=>{this._make(t).replaceWith(t.children)}),this}function hM(r){const e=this[0];if(e){const t=this._make(typeof r=="function"?r.call(e,0,e):r).insertBefore(e);let n;for(let o=0;o{if(!Tn(t)||!t.parent)return;const a=t.parent.children,o=a.indexOf(t);if(o<0)return;const u=typeof r[0]=="function"?r[0].call(t,n,this._render(t.children)):r,d=this._makeDomArray(u,n{if(!Tn(t)||!t.parent)return;const a=t.parent.children,o=a.indexOf(t);if(o<0)return;const u=typeof r[0]=="function"?r[0].call(t,n,this._render(t.children)):r,d=this._makeDomArray(u,n{const a=this.clone().toArray(),{parent:o}=n;if(!o)return;const u=o.children,d=u.indexOf(n);d<0||(Ii(u,d,0,a,o),t.push(...a))}),this._make(t)}function gM(r){const e=r?this.filter(r):this;return hn(e,t=>{Po(t),t.prev=t.next=t.parent=null}),this}function bM(r){return hn(this,(e,t)=>{const{parent:n}=e;if(!n)return;const a=n.children,o=typeof r=="function"?r.call(e,t,e):r,u=this._makeDomArray(o);$l(u,null);const d=a.indexOf(e);Ii(a,d,1,u,n),u.includes(e)||(e.parent=e.prev=e.next=null)})}function yM(){return hn(this,r=>{if(Tn(r)){for(const e of r.children)e.next=e.prev=e.parent=null;r.children.length=0}})}function wM(r){if(r===void 0){const e=this[0];return!e||!Tn(e)?null:this._render(e.children)}return hn(this,e=>{if(!Tn(e))return;for(const n of e.children)n.next=n.prev=n.parent=null;const t=Ul(r)?r.toArray():this._parse(`${r}`,this.options,!1,e).children;$l(t,e)})}function vM(){return this._render(this)}function EM(r){return r===void 0?t_(this):typeof r=="function"?hn(this,(e,t)=>this._make(e).text(r.call(e,t,t_([e])))):hn(this,e=>{if(!Tn(e))return;for(const n of e.children)n.next=n.prev=n.parent=null;const t=new aw(`${r}`);$l(t,e)})}function TM(){const r=Array.prototype.map.call(this.get(),t=>hp(t,!0)),e=new iw(r);for(const t of r)t.parent=e;return this._make(r)}var xM=Object.freeze({__proto__:null,_makeDomArray:sM,after:fM,append:oM,appendTo:aM,before:mM,clone:TM,empty:yM,html:wM,insertAfter:pM,insertBefore:_M,prepend:uM,prependTo:iM,remove:gM,replaceWith:bM,text:EM,toString:vM,unwrap:dM,wrap:lM,wrapAll:hM,wrapInner:cM});function MM(r,e){if(r!=null&&e!=null||typeof r=="object"&&!Array.isArray(r))return hn(this,(t,n)=>{dr(t)&&Bw(t,r,e,n)});if(this.length!==0)return jw(this[0],r)}function Bw(r,e,t,n){if(typeof e=="string"){const a=jw(r),o=typeof t=="function"?t.call(r,n,a[e]):t;o===""?delete a[e]:o!=null&&(a[e]=o),r.attribs.style=PM(a)}else if(typeof e=="object"){const a=Object.keys(e);for(let o=0;o`${e}${e?" ":""}${t}: ${r[t]};`,"")}function CM(r){if(r=(r||"").trim(),!r)return{};const e={};let t;for(const n of r.split(";")){const a=n.indexOf(":");if(a<1||a===n.length-1){const o=n.trimEnd();o.length>0&&t!==void 0&&(e[t]+=`;${o}`)}else t=n.slice(0,a).trim(),e[t]=n.slice(a+1).trim()}return e}var SM=Object.freeze({__proto__:null,css:MM});const Zy="input,select,textarea,keygen",AM=/%20/g,Yy=/\r?\n/g;function kM(){return this.serializeArray().map(t=>`${encodeURIComponent(t.name)}=${encodeURIComponent(t.value)}`).join("&").replace(AM,"+")}function IM(){return this.map((r,e)=>{const t=this._make(e);return dr(e)&&e.name==="form"?t.find(Zy).toArray():t.filter(Zy).toArray()}).filter('[name!=""]:enabled:not(:submit, :button, :image, :reset, :file):matches([checked], :not(:checkbox, :radio))').map((r,e)=>{var t;const n=this._make(e),a=n.attr("name"),o=(t=n.val())!==null&&t!==void 0?t:"";return Array.isArray(o)?o.map(u=>({name:a,value:u.replace(Yy,`\r `)})):{name:a,value:o.replace(Yy,`\r `)}}).toArray()}var $M=Object.freeze({__proto__:null,serialize:kM,serializeArray:IM});function OM(r){var e;return typeof r=="string"?{selector:r,value:"textContent"}:{selector:r.selector,value:(e=r.value)!==null&&e!==void 0?e:"textContent"}}function LM(r){const e={};for(const t in r){const n=r[t],a=Array.isArray(n),{selector:o,value:u}=OM(a?n[0]:n),d=typeof u=="function"?u:typeof u=="string"?c=>this._make(c).prop(u):c=>this._make(c).extract(u);if(a)e[t]=this._findBySelector(o,Number.POSITIVE_INFINITY).map((c,h)=>d(h,t,e)).get();else{const c=this._findBySelector(o,1);e[t]=c.length>0?d(c[0],t,e):void 0}}return e}var RM=Object.freeze({__proto__:null,extract:LM});class k_{constructor(e,t,n){if(this.length=0,this.options=n,this._root=t,e){for(let a=0;a[r.toLowerCase(),r]));An.XLINK,An.XLINK,An.XLINK,An.XLINK,An.XLINK,An.XLINK,An.XLINK,An.XML,An.XML,An.XMLNS,An.XMLNS;new Map(["altGlyph","altGlyphDef","altGlyphItem","animateColor","animateMotion","animateTransform","clipPath","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","foreignObject","glyphRef","linearGradient","radialGradient","textPath"].map(r=>[r.toLowerCase(),r]));_e.B,_e.BIG,_e.BLOCKQUOTE,_e.BODY,_e.BR,_e.CENTER,_e.CODE,_e.DD,_e.DIV,_e.DL,_e.DT,_e.EM,_e.EMBED,_e.H1,_e.H2,_e.H3,_e.H4,_e.H5,_e.H6,_e.HEAD,_e.HR,_e.I,_e.IMG,_e.LI,_e.LISTING,_e.MENU,_e.META,_e.NOBR,_e.OL,_e.P,_e.PRE,_e.RUBY,_e.S,_e.SMALL,_e.SPAN,_e.STRONG,_e.STRIKE,_e.SUB,_e.SUP,_e.TABLE,_e.TT,_e.U,_e.UL,_e.VAR;var r1;(function(r){r[r.INITIAL=0]="INITIAL",r[r.BEFORE_HTML=1]="BEFORE_HTML",r[r.BEFORE_HEAD=2]="BEFORE_HEAD",r[r.IN_HEAD=3]="IN_HEAD",r[r.IN_HEAD_NO_SCRIPT=4]="IN_HEAD_NO_SCRIPT",r[r.AFTER_HEAD=5]="AFTER_HEAD",r[r.IN_BODY=6]="IN_BODY",r[r.TEXT=7]="TEXT",r[r.IN_TABLE=8]="IN_TABLE",r[r.IN_TABLE_TEXT=9]="IN_TABLE_TEXT",r[r.IN_CAPTION=10]="IN_CAPTION",r[r.IN_COLUMN_GROUP=11]="IN_COLUMN_GROUP",r[r.IN_TABLE_BODY=12]="IN_TABLE_BODY",r[r.IN_ROW=13]="IN_ROW",r[r.IN_CELL=14]="IN_CELL",r[r.IN_SELECT=15]="IN_SELECT",r[r.IN_SELECT_IN_TABLE=16]="IN_SELECT_IN_TABLE",r[r.IN_TEMPLATE=17]="IN_TEMPLATE",r[r.AFTER_BODY=18]="AFTER_BODY",r[r.IN_FRAMESET=19]="IN_FRAMESET",r[r.AFTER_FRAMESET=20]="AFTER_FRAMESET",r[r.AFTER_AFTER_BODY=21]="AFTER_AFTER_BODY",r[r.AFTER_AFTER_FRAMESET=22]="AFTER_AFTER_FRAMESET"})(r1||(r1={}));_e.TABLE,_e.TBODY,_e.TFOOT,_e.THEAD,_e.TR;_e.CAPTION,_e.COL,_e.COLGROUP,_e.TBODY,_e.TD,_e.TFOOT,_e.TH,_e.THEAD,_e.TR;Ue.AREA,Ue.BASE,Ue.BASEFONT,Ue.BGSOUND,Ue.BR,Ue.COL,Ue.EMBED,Ue.FRAME,Ue.HR,Ue.IMG,Ue.INPUT,Ue.KEYGEN,Ue.LINK,Ue.META,Ue.PARAM,Ue.SOURCE,Ue.TRACK,Ue.WBR;class Uw{constructor(e){Object.defineProperty(this,"pageContent",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.pageContent=e.pageContent!==void 0?e.pageContent.toString():"",this.metadata=e.metadata??{},this.id=e.id}}var Nr;(function(r){r.assertEqual=a=>a;function e(a){}r.assertIs=e;function t(a){throw new Error}r.assertNever=t,r.arrayToEnum=a=>{const o={};for(const u of a)o[u]=u;return o},r.getValidEnumValues=a=>{const o=r.objectKeys(a).filter(d=>typeof a[a[d]]!="number"),u={};for(const d of o)u[d]=a[d];return r.objectValues(u)},r.objectValues=a=>r.objectKeys(a).map(function(o){return a[o]}),r.objectKeys=typeof Object.keys=="function"?a=>Object.keys(a):a=>{const o=[];for(const u in a)Object.prototype.hasOwnProperty.call(a,u)&&o.push(u);return o},r.find=(a,o)=>{for(const u of a)if(o(u))return u},r.isInteger=typeof Number.isInteger=="function"?a=>Number.isInteger(a):a=>typeof a=="number"&&isFinite(a)&&Math.floor(a)===a;function n(a,o=" | "){return a.map(u=>typeof u=="string"?`'${u}'`:u).join(o)}r.joinValues=n,r.jsonStringifyReplacer=(a,o)=>typeof o=="bigint"?o.toString():o})(Nr||(Nr={}));var c0;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(c0||(c0={}));const Bt=Nr.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ua=r=>{switch(typeof r){case"undefined":return Bt.undefined;case"string":return Bt.string;case"number":return isNaN(r)?Bt.nan:Bt.number;case"boolean":return Bt.boolean;case"function":return Bt.function;case"bigint":return Bt.bigint;case"symbol":return Bt.symbol;case"object":return Array.isArray(r)?Bt.array:r===null?Bt.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?Bt.promise:typeof Map<"u"&&r instanceof Map?Bt.map:typeof Set<"u"&&r instanceof Set?Bt.set:typeof Date<"u"&&r instanceof Date?Bt.date:Bt.object;default:return Bt.unknown}},pt=Nr.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"]),NM=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:");class ws 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]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(o){return o.message},n={_errors:[]},a=o=>{for(const u of o.issues)if(u.code==="invalid_union")u.unionErrors.map(a);else if(u.code==="invalid_return_type")a(u.returnTypeError);else if(u.code==="invalid_arguments")a(u.argumentsError);else if(u.path.length===0)n._errors.push(t(u));else{let d=n,c=0;for(;ct.message){const t={},n=[];for(const a of this.issues)a.path.length>0?(t[a.path[0]]=t[a.path[0]]||[],t[a.path[0]].push(e(a))):n.push(e(a));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}}ws.create=r=>new ws(r);const Ol=(r,e)=>{let t;switch(r.code){case pt.invalid_type:r.received===Bt.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case pt.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,Nr.jsonStringifyReplacer)}`;break;case pt.unrecognized_keys:t=`Unrecognized key(s) in object: ${Nr.joinValues(r.keys,", ")}`;break;case pt.invalid_union:t="Invalid input";break;case pt.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${Nr.joinValues(r.options)}`;break;case pt.invalid_enum_value:t=`Invalid enum value. Expected ${Nr.joinValues(r.options)}, received '${r.received}'`;break;case pt.invalid_arguments:t="Invalid function arguments";break;case pt.invalid_return_type:t="Invalid function return type";break;case pt.invalid_date:t="Invalid date";break;case pt.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:Nr.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case pt.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case pt.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case pt.custom:t="Invalid input";break;case pt.invalid_intersection_types:t="Intersection results could not be merged";break;case pt.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case pt.not_finite:t="Number must be finite";break;default:t=e.defaultError,Nr.assertNever(r)}return{message:t}};let Vw=Ol;function DM(r){Vw=r}function o_(){return Vw}const u_=r=>{const{data:e,path:t,errorMaps:n,issueData:a}=r,o=[...t,...a.path||[]],u={...a,path:o};if(a.message!==void 0)return{...a,path:o,message:a.message};let d="";const c=n.filter(h=>!!h).slice().reverse();for(const h of c)d=h(u,{data:e,defaultError:d}).message;return{...a,path:o,message:d}},BM=[];function $t(r,e){const t=o_(),n=u_({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===Ol?void 0:Ol].filter(a=>!!a)});r.common.issues.push(n)}class Hn{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const n=[];for(const a of t){if(a.status==="aborted")return lr;a.status==="dirty"&&e.dirty(),n.push(a.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){const n=[];for(const a of t){const o=await a.key,u=await a.value;n.push({key:o,value:u})}return Hn.mergeObjectSync(e,n)}static mergeObjectSync(e,t){const n={};for(const a of t){const{key:o,value:u}=a;if(o.status==="aborted"||u.status==="aborted")return lr;o.status==="dirty"&&e.dirty(),u.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof u.value<"u"||a.alwaysSet)&&(n[o.value]=u.value)}return{status:e.value,value:n}}}const lr=Object.freeze({status:"aborted"}),Pl=r=>({status:"dirty",value:r}),es=r=>({status:"valid",value:r}),d0=r=>r.status==="aborted",h0=r=>r.status==="dirty",To=r=>r.status==="valid",mp=r=>typeof Promise<"u"&&r instanceof Promise;function l_(r,e,t,n){if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e.get(r)}function Ww(r,e,t,n,a){if(typeof e=="function"?r!==e||!a:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(r,t),t}var Ht;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(Ht||(Ht={}));var tp,rp;class Ta{constructor(e,t,n,a){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=a}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const n1=(r,e)=>{if(To(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new ws(r.common.issues);return this._error=t,this._error}}};function gr(r){if(!r)return{};const{errorMap:e,invalid_type_error:t,required_error:n,description:a}=r;if(e&&(t||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:a}:{errorMap:(u,d)=>{var c,h;const{message:_}=r;return u.code==="invalid_enum_value"?{message:_??d.defaultError}:typeof d.data>"u"?{message:(c=_??n)!==null&&c!==void 0?c:d.defaultError}:u.code!=="invalid_type"?{message:d.defaultError}:{message:(h=_??t)!==null&&h!==void 0?h:d.defaultError}},description:a}}class wr{get description(){return this._def.description}_getType(e){return Ua(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Ua(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Hn,ctx:{common:e.parent.common,data:e.data,parsedType:Ua(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(mp(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){var n;const a={common:{issues:[],async:(n=t==null?void 0:t.async)!==null&&n!==void 0?n:!1,contextualErrorMap:t==null?void 0:t.errorMap},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ua(e)},o=this._parseSync({data:e,path:a.path,parent:a});return n1(a,o)}"~validate"(e){var t,n;const a={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ua(e)};if(!this["~standard"].async)try{const o=this._parseSync({data:e,path:[],parent:a});return To(o)?{value:o.value}:{issues:a.common.issues}}catch(o){!((n=(t=o==null?void 0:o.message)===null||t===void 0?void 0:t.toLowerCase())===null||n===void 0)&&n.includes("encountered")&&(this["~standard"].async=!0),a.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:a}).then(o=>To(o)?{value:o.value}:{issues:a.common.issues})}async parseAsync(e,t){const n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){const n={common:{issues:[],contextualErrorMap:t==null?void 0:t.errorMap,async:!0},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ua(e)},a=this._parse({data:e,path:n.path,parent:n}),o=await(mp(a)?a:Promise.resolve(a));return n1(n,o)}refine(e,t){const n=a=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(a):t;return this._refinement((a,o)=>{const u=e(a),d=()=>o.addIssue({code:pt.custom,...n(a)});return typeof Promise<"u"&&u instanceof Promise?u.then(c=>c?!0:(d(),!1)):u?!0:(d(),!1)})}refinement(e,t){return this._refinement((n,a)=>e(n)?!0:(a.addIssue(typeof t=="function"?t(n,a):t),!1))}_refinement(e){return new ea({schema:this,typeName:vt.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return Qs.create(this,this._def)}nullable(){return Si.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Xs.create(this)}promise(){return Rl.create(this,this._def)}or(e){return yp.create([this,e],this._def)}and(e){return wp.create(this,e,this._def)}transform(e){return new ea({...gr(this._def),schema:this,typeName:vt.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new Mp({...gr(this._def),innerType:this,defaultValue:t,typeName:vt.ZodDefault})}brand(){return new j0({typeName:vt.ZodBranded,type:this,...gr(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new Pp({...gr(this._def),innerType:this,catchValue:t,typeName:vt.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Lp.create(this,e)}readonly(){return Cp.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const jM=/^c[^\s-]{8,}$/i,zM=/^[0-9a-z]+$/,UM=/^[0-9A-HJKMNP-TV-Z]{26}$/i,VM=/^[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,WM=/^[a-z0-9_-]{21}$/i,GM=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,HM=/^[-+]?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)?)??$/,KM=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,qM="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Og;const ZM=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,YM=/^(?:(?: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])$/,XM=/^(([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]))$/,QM=/^(([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])$/,JM=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,eP=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Gw="((\\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])))",tP=new RegExp(`^${Gw}$`);function Hw(r){let e="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`),e}function rP(r){return new RegExp(`^${Hw(r)}$`)}function Kw(r){let e=`${Gw}T${Hw(r)}`;const t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function nP(r,e){return!!((e==="v4"||!e)&&ZM.test(r)||(e==="v6"||!e)&&XM.test(r))}function sP(r,e){if(!GM.test(r))return!1;try{const[t]=r.split("."),n=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),a=JSON.parse(atob(n));return!(typeof a!="object"||a===null||!a.typ||!a.alg||e&&a.alg!==e)}catch{return!1}}function aP(r,e){return!!((e==="v4"||!e)&&YM.test(r)||(e==="v6"||!e)&&QM.test(r))}class Zs extends wr{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==Bt.string){const o=this._getOrReturnCtx(e);return $t(o,{code:pt.invalid_type,expected:Bt.string,received:o.parsedType}),lr}const n=new Hn;let a;for(const o of this._def.checks)if(o.kind==="min")e.data.lengtho.value&&(a=this._getOrReturnCtx(e,a),$t(a,{code:pt.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){const u=e.data.length>o.value,d=e.data.lengthe.test(a),{validation:t,code:pt.invalid_string,...Ht.errToObj(n)})}_addCheck(e){return new Zs({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...Ht.errToObj(e)})}url(e){return this._addCheck({kind:"url",...Ht.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...Ht.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...Ht.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...Ht.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...Ht.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...Ht.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...Ht.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...Ht.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...Ht.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...Ht.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...Ht.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...Ht.errToObj(e)})}datetime(e){var t,n;return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,offset:(t=e==null?void 0:e.offset)!==null&&t!==void 0?t:!1,local:(n=e==null?void 0:e.local)!==null&&n!==void 0?n:!1,...Ht.errToObj(e==null?void 0: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==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,...Ht.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...Ht.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...Ht.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t==null?void 0:t.position,...Ht.errToObj(t==null?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...Ht.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...Ht.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...Ht.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...Ht.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...Ht.errToObj(t)})}nonempty(e){return this.min(1,Ht.errToObj(e))}trim(){return new Zs({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Zs({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Zs({...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(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value{var e;return new Zs({checks:[],typeName:vt.ZodString,coerce:(e=r==null?void 0:r.coerce)!==null&&e!==void 0?e:!1,...gr(r)})};function iP(r,e){const t=(r.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,a=t>n?t:n,o=parseInt(r.toFixed(a).replace(".","")),u=parseInt(e.toFixed(a).replace(".",""));return o%u/Math.pow(10,a)}class Mi extends wr{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)!==Bt.number){const o=this._getOrReturnCtx(e);return $t(o,{code:pt.invalid_type,expected:Bt.number,received:o.parsedType}),lr}let n;const a=new Hn;for(const o of this._def.checks)o.kind==="int"?Nr.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),$t(n,{code:pt.invalid_type,expected:"integer",received:"float",message:o.message}),a.dirty()):o.kind==="min"?(o.inclusive?e.datao.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),$t(n,{code:pt.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),a.dirty()):o.kind==="multipleOf"?iP(e.data,o.value)!==0&&(n=this._getOrReturnCtx(e,n),$t(n,{code:pt.not_multiple_of,multipleOf:o.value,message:o.message}),a.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),$t(n,{code:pt.not_finite,message:o.message}),a.dirty()):Nr.assertNever(o);return{status:a.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,Ht.toString(t))}gt(e,t){return this.setLimit("min",e,!1,Ht.toString(t))}lte(e,t){return this.setLimit("max",e,!0,Ht.toString(t))}lt(e,t){return this.setLimit("max",e,!1,Ht.toString(t))}setLimit(e,t,n,a){return new Mi({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:Ht.toString(a)}]})}_addCheck(e){return new Mi({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:Ht.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Ht.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Ht.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Ht.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Ht.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:Ht.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:Ht.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Ht.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Ht.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.valuee.kind==="int"||e.kind==="multipleOf"&&Nr.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(t===null||n.value>t)&&(t=n.value):n.kind==="max"&&(e===null||n.valuenew Mi({checks:[],typeName:vt.ZodNumber,coerce:(r==null?void 0:r.coerce)||!1,...gr(r)});class Pi extends wr{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)!==Bt.bigint)return this._getInvalidInput(e);let n;const a=new Hn;for(const o of this._def.checks)o.kind==="min"?(o.inclusive?e.datao.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),$t(n,{code:pt.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),a.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),$t(n,{code:pt.not_multiple_of,multipleOf:o.value,message:o.message}),a.dirty()):Nr.assertNever(o);return{status:a.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return $t(t,{code:pt.invalid_type,expected:Bt.bigint,received:t.parsedType}),lr}gte(e,t){return this.setLimit("min",e,!0,Ht.toString(t))}gt(e,t){return this.setLimit("min",e,!1,Ht.toString(t))}lte(e,t){return this.setLimit("max",e,!0,Ht.toString(t))}lt(e,t){return this.setLimit("max",e,!1,Ht.toString(t))}setLimit(e,t,n,a){return new Pi({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:Ht.toString(a)}]})}_addCheck(e){return new Pi({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Ht.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Ht.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Ht.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Ht.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:Ht.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value{var e;return new Pi({checks:[],typeName:vt.ZodBigInt,coerce:(e=r==null?void 0:r.coerce)!==null&&e!==void 0?e:!1,...gr(r)})};class _p extends wr{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==Bt.boolean){const n=this._getOrReturnCtx(e);return $t(n,{code:pt.invalid_type,expected:Bt.boolean,received:n.parsedType}),lr}return es(e.data)}}_p.create=r=>new _p({typeName:vt.ZodBoolean,coerce:(r==null?void 0:r.coerce)||!1,...gr(r)});class xo extends wr{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==Bt.date){const o=this._getOrReturnCtx(e);return $t(o,{code:pt.invalid_type,expected:Bt.date,received:o.parsedType}),lr}if(isNaN(e.data.getTime())){const o=this._getOrReturnCtx(e);return $t(o,{code:pt.invalid_date}),lr}const n=new Hn;let a;for(const o of this._def.checks)o.kind==="min"?e.data.getTime()o.value&&(a=this._getOrReturnCtx(e,a),$t(a,{code:pt.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):Nr.assertNever(o);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new xo({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:Ht.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:Ht.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.valuenew xo({checks:[],coerce:(r==null?void 0:r.coerce)||!1,typeName:vt.ZodDate,...gr(r)});class c_ extends wr{_parse(e){if(this._getType(e)!==Bt.symbol){const n=this._getOrReturnCtx(e);return $t(n,{code:pt.invalid_type,expected:Bt.symbol,received:n.parsedType}),lr}return es(e.data)}}c_.create=r=>new c_({typeName:vt.ZodSymbol,...gr(r)});class gp extends wr{_parse(e){if(this._getType(e)!==Bt.undefined){const n=this._getOrReturnCtx(e);return $t(n,{code:pt.invalid_type,expected:Bt.undefined,received:n.parsedType}),lr}return es(e.data)}}gp.create=r=>new gp({typeName:vt.ZodUndefined,...gr(r)});class bp extends wr{_parse(e){if(this._getType(e)!==Bt.null){const n=this._getOrReturnCtx(e);return $t(n,{code:pt.invalid_type,expected:Bt.null,received:n.parsedType}),lr}return es(e.data)}}bp.create=r=>new bp({typeName:vt.ZodNull,...gr(r)});class Ll extends wr{constructor(){super(...arguments),this._any=!0}_parse(e){return es(e.data)}}Ll.create=r=>new Ll({typeName:vt.ZodAny,...gr(r)});class wo extends wr{constructor(){super(...arguments),this._unknown=!0}_parse(e){return es(e.data)}}wo.create=r=>new wo({typeName:vt.ZodUnknown,...gr(r)});class Ga extends wr{_parse(e){const t=this._getOrReturnCtx(e);return $t(t,{code:pt.invalid_type,expected:Bt.never,received:t.parsedType}),lr}}Ga.create=r=>new Ga({typeName:vt.ZodNever,...gr(r)});class d_ extends wr{_parse(e){if(this._getType(e)!==Bt.undefined){const n=this._getOrReturnCtx(e);return $t(n,{code:pt.invalid_type,expected:Bt.void,received:n.parsedType}),lr}return es(e.data)}}d_.create=r=>new d_({typeName:vt.ZodVoid,...gr(r)});class Xs extends wr{_parse(e){const{ctx:t,status:n}=this._processInputParams(e),a=this._def;if(t.parsedType!==Bt.array)return $t(t,{code:pt.invalid_type,expected:Bt.array,received:t.parsedType}),lr;if(a.exactLength!==null){const u=t.data.length>a.exactLength.value,d=t.data.lengtha.maxLength.value&&($t(t,{code:pt.too_big,maximum:a.maxLength.value,type:"array",inclusive:!0,exact:!1,message:a.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((u,d)=>a.type._parseAsync(new Ta(t,u,t.path,d)))).then(u=>Hn.mergeArray(n,u));const o=[...t.data].map((u,d)=>a.type._parseSync(new Ta(t,u,t.path,d)));return Hn.mergeArray(n,o)}get element(){return this._def.type}min(e,t){return new Xs({...this._def,minLength:{value:e,message:Ht.toString(t)}})}max(e,t){return new Xs({...this._def,maxLength:{value:e,message:Ht.toString(t)}})}length(e,t){return new Xs({...this._def,exactLength:{value:e,message:Ht.toString(t)}})}nonempty(e){return this.min(1,e)}}Xs.create=(r,e)=>new Xs({type:r,minLength:null,maxLength:null,exactLength:null,typeName:vt.ZodArray,...gr(e)});function xl(r){if(r instanceof dn){const e={};for(const t in r.shape){const n=r.shape[t];e[t]=Qs.create(xl(n))}return new dn({...r._def,shape:()=>e})}else return r instanceof Xs?new Xs({...r._def,type:xl(r.element)}):r instanceof Qs?Qs.create(xl(r.unwrap())):r instanceof Si?Si.create(xl(r.unwrap())):r instanceof xa?xa.create(r.items.map(e=>xl(e))):r}class dn extends wr{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),t=Nr.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==Bt.object){const h=this._getOrReturnCtx(e);return $t(h,{code:pt.invalid_type,expected:Bt.object,received:h.parsedType}),lr}const{status:n,ctx:a}=this._processInputParams(e),{shape:o,keys:u}=this._getCached(),d=[];if(!(this._def.catchall instanceof Ga&&this._def.unknownKeys==="strip"))for(const h in a.data)u.includes(h)||d.push(h);const c=[];for(const h of u){const _=o[h],y=a.data[h];c.push({key:{status:"valid",value:h},value:_._parse(new Ta(a,y,a.path,h)),alwaysSet:h in a.data})}if(this._def.catchall instanceof Ga){const h=this._def.unknownKeys;if(h==="passthrough")for(const _ of d)c.push({key:{status:"valid",value:_},value:{status:"valid",value:a.data[_]}});else if(h==="strict")d.length>0&&($t(a,{code:pt.unrecognized_keys,keys:d}),n.dirty());else if(h!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const h=this._def.catchall;for(const _ of d){const y=a.data[_];c.push({key:{status:"valid",value:_},value:h._parse(new Ta(a,y,a.path,_)),alwaysSet:_ in a.data})}}return a.common.async?Promise.resolve().then(async()=>{const h=[];for(const _ of c){const y=await _.key,w=await _.value;h.push({key:y,value:w,alwaysSet:_.alwaysSet})}return h}).then(h=>Hn.mergeObjectSync(n,h)):Hn.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return Ht.errToObj,new dn({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{var a,o,u,d;const c=(u=(o=(a=this._def).errorMap)===null||o===void 0?void 0:o.call(a,t,n).message)!==null&&u!==void 0?u:n.defaultError;return t.code==="unrecognized_keys"?{message:(d=Ht.errToObj(e).message)!==null&&d!==void 0?d:c}:{message:c}}}:{}})}strip(){return new dn({...this._def,unknownKeys:"strip"})}passthrough(){return new dn({...this._def,unknownKeys:"passthrough"})}extend(e){return new dn({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new dn({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:vt.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new dn({...this._def,catchall:e})}pick(e){const t={};return Nr.objectKeys(e).forEach(n=>{e[n]&&this.shape[n]&&(t[n]=this.shape[n])}),new dn({...this._def,shape:()=>t})}omit(e){const t={};return Nr.objectKeys(this.shape).forEach(n=>{e[n]||(t[n]=this.shape[n])}),new dn({...this._def,shape:()=>t})}deepPartial(){return xl(this)}partial(e){const t={};return Nr.objectKeys(this.shape).forEach(n=>{const a=this.shape[n];e&&!e[n]?t[n]=a:t[n]=a.optional()}),new dn({...this._def,shape:()=>t})}required(e){const t={};return Nr.objectKeys(this.shape).forEach(n=>{if(e&&!e[n])t[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof Qs;)o=o._def.innerType;t[n]=o}}),new dn({...this._def,shape:()=>t})}keyof(){return qw(Nr.objectKeys(this.shape))}}dn.create=(r,e)=>new dn({shape:()=>r,unknownKeys:"strip",catchall:Ga.create(),typeName:vt.ZodObject,...gr(e)});dn.strictCreate=(r,e)=>new dn({shape:()=>r,unknownKeys:"strict",catchall:Ga.create(),typeName:vt.ZodObject,...gr(e)});dn.lazycreate=(r,e)=>new dn({shape:r,unknownKeys:"strip",catchall:Ga.create(),typeName:vt.ZodObject,...gr(e)});class yp extends wr{_parse(e){const{ctx:t}=this._processInputParams(e),n=this._def.options;function a(o){for(const d of o)if(d.result.status==="valid")return d.result;for(const d of o)if(d.result.status==="dirty")return t.common.issues.push(...d.ctx.common.issues),d.result;const u=o.map(d=>new ws(d.ctx.common.issues));return $t(t,{code:pt.invalid_union,unionErrors:u}),lr}if(t.common.async)return Promise.all(n.map(async o=>{const u={...t,common:{...t.common,issues:[]},parent:null};return{result:await o._parseAsync({data:t.data,path:t.path,parent:u}),ctx:u}})).then(a);{let o;const u=[];for(const c of n){const h={...t,common:{...t.common,issues:[]},parent:null},_=c._parseSync({data:t.data,path:t.path,parent:h});if(_.status==="valid")return _;_.status==="dirty"&&!o&&(o={result:_,ctx:h}),h.common.issues.length&&u.push(h.common.issues)}if(o)return t.common.issues.push(...o.ctx.common.issues),o.result;const d=u.map(c=>new ws(c));return $t(t,{code:pt.invalid_union,unionErrors:d}),lr}}get options(){return this._def.options}}yp.create=(r,e)=>new yp({options:r,typeName:vt.ZodUnion,...gr(e)});const za=r=>r instanceof Ep?za(r.schema):r instanceof ea?za(r.innerType()):r instanceof Tp?[r.value]:r instanceof Ci?r.options:r instanceof xp?Nr.objectValues(r.enum):r instanceof Mp?za(r._def.innerType):r instanceof gp?[void 0]:r instanceof bp?[null]:r instanceof Qs?[void 0,...za(r.unwrap())]:r instanceof Si?[null,...za(r.unwrap())]:r instanceof j0||r instanceof Cp?za(r.unwrap()):r instanceof Pp?za(r._def.innerType):[];class I_ extends wr{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==Bt.object)return $t(t,{code:pt.invalid_type,expected:Bt.object,received:t.parsedType}),lr;const n=this.discriminator,a=t.data[n],o=this.optionsMap.get(a);return o?t.common.async?o._parseAsync({data:t.data,path:t.path,parent:t}):o._parseSync({data:t.data,path:t.path,parent:t}):($t(t,{code:pt.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),lr)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){const a=new Map;for(const o of t){const u=za(o.shape[e]);if(!u.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const d of u){if(a.has(d))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(d)}`);a.set(d,o)}}return new I_({typeName:vt.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:a,...gr(n)})}}function f0(r,e){const t=Ua(r),n=Ua(e);if(r===e)return{valid:!0,data:r};if(t===Bt.object&&n===Bt.object){const a=Nr.objectKeys(e),o=Nr.objectKeys(r).filter(d=>a.indexOf(d)!==-1),u={...r,...e};for(const d of o){const c=f0(r[d],e[d]);if(!c.valid)return{valid:!1};u[d]=c.data}return{valid:!0,data:u}}else if(t===Bt.array&&n===Bt.array){if(r.length!==e.length)return{valid:!1};const a=[];for(let o=0;o{if(d0(o)||d0(u))return lr;const d=f0(o.value,u.value);return d.valid?((h0(o)||h0(u))&&t.dirty(),{status:t.value,value:d.data}):($t(n,{code:pt.invalid_intersection_types}),lr)};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,u])=>a(o,u)):a(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}wp.create=(r,e,t)=>new wp({left:r,right:e,typeName:vt.ZodIntersection,...gr(t)});class xa extends wr{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==Bt.array)return $t(n,{code:pt.invalid_type,expected:Bt.array,received:n.parsedType}),lr;if(n.data.lengththis._def.items.length&&($t(n,{code:pt.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const o=[...n.data].map((u,d)=>{const c=this._def.items[d]||this._def.rest;return c?c._parse(new Ta(n,u,n.path,d)):null}).filter(u=>!!u);return n.common.async?Promise.all(o).then(u=>Hn.mergeArray(t,u)):Hn.mergeArray(t,o)}get items(){return this._def.items}rest(e){return new xa({...this._def,rest:e})}}xa.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new xa({items:r,typeName:vt.ZodTuple,rest:null,...gr(e)})};class vp extends wr{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==Bt.object)return $t(n,{code:pt.invalid_type,expected:Bt.object,received:n.parsedType}),lr;const a=[],o=this._def.keyType,u=this._def.valueType;for(const d in n.data)a.push({key:o._parse(new Ta(n,d,n.path,d)),value:u._parse(new Ta(n,n.data[d],n.path,d)),alwaysSet:d in n.data});return n.common.async?Hn.mergeObjectAsync(t,a):Hn.mergeObjectSync(t,a)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof wr?new vp({keyType:e,valueType:t,typeName:vt.ZodRecord,...gr(n)}):new vp({keyType:Zs.create(),valueType:e,typeName:vt.ZodRecord,...gr(t)})}}class h_ extends wr{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==Bt.map)return $t(n,{code:pt.invalid_type,expected:Bt.map,received:n.parsedType}),lr;const a=this._def.keyType,o=this._def.valueType,u=[...n.data.entries()].map(([d,c],h)=>({key:a._parse(new Ta(n,d,n.path,[h,"key"])),value:o._parse(new Ta(n,c,n.path,[h,"value"]))}));if(n.common.async){const d=new Map;return Promise.resolve().then(async()=>{for(const c of u){const h=await c.key,_=await c.value;if(h.status==="aborted"||_.status==="aborted")return lr;(h.status==="dirty"||_.status==="dirty")&&t.dirty(),d.set(h.value,_.value)}return{status:t.value,value:d}})}else{const d=new Map;for(const c of u){const h=c.key,_=c.value;if(h.status==="aborted"||_.status==="aborted")return lr;(h.status==="dirty"||_.status==="dirty")&&t.dirty(),d.set(h.value,_.value)}return{status:t.value,value:d}}}}h_.create=(r,e,t)=>new h_({valueType:e,keyType:r,typeName:vt.ZodMap,...gr(t)});class Mo extends wr{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==Bt.set)return $t(n,{code:pt.invalid_type,expected:Bt.set,received:n.parsedType}),lr;const a=this._def;a.minSize!==null&&n.data.sizea.maxSize.value&&($t(n,{code:pt.too_big,maximum:a.maxSize.value,type:"set",inclusive:!0,exact:!1,message:a.maxSize.message}),t.dirty());const o=this._def.valueType;function u(c){const h=new Set;for(const _ of c){if(_.status==="aborted")return lr;_.status==="dirty"&&t.dirty(),h.add(_.value)}return{status:t.value,value:h}}const d=[...n.data.values()].map((c,h)=>o._parse(new Ta(n,c,n.path,h)));return n.common.async?Promise.all(d).then(c=>u(c)):u(d)}min(e,t){return new Mo({...this._def,minSize:{value:e,message:Ht.toString(t)}})}max(e,t){return new Mo({...this._def,maxSize:{value:e,message:Ht.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}Mo.create=(r,e)=>new Mo({valueType:r,minSize:null,maxSize:null,typeName:vt.ZodSet,...gr(e)});class kl extends wr{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==Bt.function)return $t(t,{code:pt.invalid_type,expected:Bt.function,received:t.parsedType}),lr;function n(d,c){return u_({data:d,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,o_(),Ol].filter(h=>!!h),issueData:{code:pt.invalid_arguments,argumentsError:c}})}function a(d,c){return u_({data:d,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,o_(),Ol].filter(h=>!!h),issueData:{code:pt.invalid_return_type,returnTypeError:c}})}const o={errorMap:t.common.contextualErrorMap},u=t.data;if(this._def.returns instanceof Rl){const d=this;return es(async function(...c){const h=new ws([]),_=await d._def.args.parseAsync(c,o).catch(M=>{throw h.addIssue(n(c,M)),h}),y=await Reflect.apply(u,this,_);return await d._def.returns._def.type.parseAsync(y,o).catch(M=>{throw h.addIssue(a(y,M)),h})})}else{const d=this;return es(function(...c){const h=d._def.args.safeParse(c,o);if(!h.success)throw new ws([n(c,h.error)]);const _=Reflect.apply(u,this,h.data),y=d._def.returns.safeParse(_,o);if(!y.success)throw new ws([a(_,y.error)]);return y.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new kl({...this._def,args:xa.create(e).rest(wo.create())})}returns(e){return new kl({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new kl({args:e||xa.create([]).rest(wo.create()),returns:t||wo.create(),typeName:vt.ZodFunction,...gr(n)})}}class Ep extends wr{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}Ep.create=(r,e)=>new Ep({getter:r,typeName:vt.ZodLazy,...gr(e)});class Tp extends wr{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return $t(t,{received:t.data,code:pt.invalid_literal,expected:this._def.value}),lr}return{status:"valid",value:e.data}}get value(){return this._def.value}}Tp.create=(r,e)=>new Tp({value:r,typeName:vt.ZodLiteral,...gr(e)});function qw(r,e){return new Ci({values:r,typeName:vt.ZodEnum,...gr(e)})}class Ci extends wr{constructor(){super(...arguments),tp.set(this,void 0)}_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),n=this._def.values;return $t(t,{expected:Nr.joinValues(n),received:t.parsedType,code:pt.invalid_type}),lr}if(l_(this,tp)||Ww(this,tp,new Set(this._def.values)),!l_(this,tp).has(e.data)){const t=this._getOrReturnCtx(e),n=this._def.values;return $t(t,{received:t.data,code:pt.invalid_enum_value,options:n}),lr}return es(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return Ci.create(e,{...this._def,...t})}exclude(e,t=this._def){return Ci.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}}tp=new WeakMap;Ci.create=qw;class xp extends wr{constructor(){super(...arguments),rp.set(this,void 0)}_parse(e){const t=Nr.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==Bt.string&&n.parsedType!==Bt.number){const a=Nr.objectValues(t);return $t(n,{expected:Nr.joinValues(a),received:n.parsedType,code:pt.invalid_type}),lr}if(l_(this,rp)||Ww(this,rp,new Set(Nr.getValidEnumValues(this._def.values))),!l_(this,rp).has(e.data)){const a=Nr.objectValues(t);return $t(n,{received:n.data,code:pt.invalid_enum_value,options:a}),lr}return es(e.data)}get enum(){return this._def.values}}rp=new WeakMap;xp.create=(r,e)=>new xp({values:r,typeName:vt.ZodNativeEnum,...gr(e)});class Rl extends wr{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==Bt.promise&&t.common.async===!1)return $t(t,{code:pt.invalid_type,expected:Bt.promise,received:t.parsedType}),lr;const n=t.parsedType===Bt.promise?t.data:Promise.resolve(t.data);return es(n.then(a=>this._def.type.parseAsync(a,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Rl.create=(r,e)=>new Rl({type:r,typeName:vt.ZodPromise,...gr(e)});class ea extends wr{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===vt.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:n}=this._processInputParams(e),a=this._def.effect||null,o={addIssue:u=>{$t(n,u),u.fatal?t.abort():t.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),a.type==="preprocess"){const u=a.transform(n.data,o);if(n.common.async)return Promise.resolve(u).then(async d=>{if(t.value==="aborted")return lr;const c=await this._def.schema._parseAsync({data:d,path:n.path,parent:n});return c.status==="aborted"?lr:c.status==="dirty"||t.value==="dirty"?Pl(c.value):c});{if(t.value==="aborted")return lr;const d=this._def.schema._parseSync({data:u,path:n.path,parent:n});return d.status==="aborted"?lr:d.status==="dirty"||t.value==="dirty"?Pl(d.value):d}}if(a.type==="refinement"){const u=d=>{const c=a.refinement(d,o);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return d};if(n.common.async===!1){const d=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return d.status==="aborted"?lr:(d.status==="dirty"&&t.dirty(),u(d.value),{status:t.value,value:d.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(d=>d.status==="aborted"?lr:(d.status==="dirty"&&t.dirty(),u(d.value).then(()=>({status:t.value,value:d.value}))))}if(a.type==="transform")if(n.common.async===!1){const u=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!To(u))return u;const d=a.transform(u.value,o);if(d instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:d}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(u=>To(u)?Promise.resolve(a.transform(u.value,o)).then(d=>({status:t.value,value:d})):u);Nr.assertNever(a)}}ea.create=(r,e,t)=>new ea({schema:r,typeName:vt.ZodEffects,effect:e,...gr(t)});ea.createWithPreprocess=(r,e,t)=>new ea({schema:e,effect:{type:"preprocess",transform:r},typeName:vt.ZodEffects,...gr(t)});class Qs extends wr{_parse(e){return this._getType(e)===Bt.undefined?es(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Qs.create=(r,e)=>new Qs({innerType:r,typeName:vt.ZodOptional,...gr(e)});class Si extends wr{_parse(e){return this._getType(e)===Bt.null?es(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Si.create=(r,e)=>new Si({innerType:r,typeName:vt.ZodNullable,...gr(e)});class Mp extends wr{_parse(e){const{ctx:t}=this._processInputParams(e);let n=t.data;return t.parsedType===Bt.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Mp.create=(r,e)=>new Mp({innerType:r,typeName:vt.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...gr(e)});class Pp extends wr{_parse(e){const{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},a=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return mp(a)?a.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new ws(n.common.issues)},input:n.data})})):{status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new ws(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}Pp.create=(r,e)=>new Pp({innerType:r,typeName:vt.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...gr(e)});class f_ extends wr{_parse(e){if(this._getType(e)!==Bt.nan){const n=this._getOrReturnCtx(e);return $t(n,{code:pt.invalid_type,expected:Bt.nan,received:n.parsedType}),lr}return{status:"valid",value:e.data}}}f_.create=r=>new f_({typeName:vt.ZodNaN,...gr(r)});const oP=Symbol("zod_brand");class j0 extends wr{_parse(e){const{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}}class Lp extends wr{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{const o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?lr:o.status==="dirty"?(t.dirty(),Pl(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{const a=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?lr:a.status==="dirty"?(t.dirty(),{status:"dirty",value:a.value}):this._def.out._parseSync({data:a.value,path:n.path,parent:n})}}static create(e,t){return new Lp({in:e,out:t,typeName:vt.ZodPipeline})}}class Cp extends wr{_parse(e){const t=this._def.innerType._parse(e),n=a=>(To(a)&&(a.value=Object.freeze(a.value)),a);return mp(t)?t.then(a=>n(a)):n(t)}unwrap(){return this._def.innerType}}Cp.create=(r,e)=>new Cp({innerType:r,typeName:vt.ZodReadonly,...gr(e)});function Zw(r,e={},t){return r?Ll.create().superRefine((n,a)=>{var o,u;if(!r(n)){const d=typeof e=="function"?e(n):typeof e=="string"?{message:e}:e,c=(u=(o=d.fatal)!==null&&o!==void 0?o:t)!==null&&u!==void 0?u:!0,h=typeof d=="string"?{message:d}:d;a.addIssue({code:"custom",...h,fatal:c})}}):Ll.create()}const uP={object:dn.lazycreate};var vt;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(vt||(vt={}));const lP=(r,e={message:`Input not instance of ${r.name}`})=>Zw(t=>t instanceof r,e),Yw=Zs.create,Xw=Mi.create,cP=f_.create,dP=Pi.create,Qw=_p.create,hP=xo.create,fP=c_.create,pP=gp.create,mP=bp.create,_P=Ll.create,gP=wo.create,bP=Ga.create,yP=d_.create,wP=Xs.create,vP=dn.create,EP=dn.strictCreate,TP=yp.create,xP=I_.create,MP=wp.create,PP=xa.create,CP=vp.create,SP=h_.create,AP=Mo.create,kP=kl.create,IP=Ep.create,$P=Tp.create,OP=Ci.create,LP=xp.create,RP=Rl.create,s1=ea.create,FP=Qs.create,NP=Si.create,DP=ea.createWithPreprocess,BP=Lp.create,jP=()=>Yw().optional(),zP=()=>Xw().optional(),UP=()=>Qw().optional(),VP={string:r=>Zs.create({...r,coerce:!0}),number:r=>Mi.create({...r,coerce:!0}),boolean:r=>_p.create({...r,coerce:!0}),bigint:r=>Pi.create({...r,coerce:!0}),date:r=>xo.create({...r,coerce:!0})},WP=lr;var sp=Object.freeze({__proto__:null,defaultErrorMap:Ol,setErrorMap:DM,getErrorMap:o_,makeIssue:u_,EMPTY_PATH:BM,addIssueToContext:$t,ParseStatus:Hn,INVALID:lr,DIRTY:Pl,OK:es,isAborted:d0,isDirty:h0,isValid:To,isAsync:mp,get util(){return Nr},get objectUtil(){return c0},ZodParsedType:Bt,getParsedType:Ua,ZodType:wr,datetimeRegex:Kw,ZodString:Zs,ZodNumber:Mi,ZodBigInt:Pi,ZodBoolean:_p,ZodDate:xo,ZodSymbol:c_,ZodUndefined:gp,ZodNull:bp,ZodAny:Ll,ZodUnknown:wo,ZodNever:Ga,ZodVoid:d_,ZodArray:Xs,ZodObject:dn,ZodUnion:yp,ZodDiscriminatedUnion:I_,ZodIntersection:wp,ZodTuple:xa,ZodRecord:vp,ZodMap:h_,ZodSet:Mo,ZodFunction:kl,ZodLazy:Ep,ZodLiteral:Tp,ZodEnum:Ci,ZodNativeEnum:xp,ZodPromise:Rl,ZodEffects:ea,ZodTransformer:ea,ZodOptional:Qs,ZodNullable:Si,ZodDefault:Mp,ZodCatch:Pp,ZodNaN:f_,BRAND:oP,ZodBranded:j0,ZodPipeline:Lp,ZodReadonly:Cp,custom:Zw,Schema:wr,ZodSchema:wr,late:uP,get ZodFirstPartyTypeKind(){return vt},coerce:VP,any:_P,array:wP,bigint:dP,boolean:Qw,date:hP,discriminatedUnion:xP,effect:s1,enum:OP,function:kP,instanceof:lP,intersection:MP,lazy:IP,literal:$P,map:SP,nan:cP,nativeEnum:LP,never:bP,null:mP,nullable:NP,number:Xw,object:vP,oboolean:UP,onumber:zP,optional:FP,ostring:jP,pipeline:BP,preprocess:DP,promise:RP,record:CP,set:AP,strictObject:EP,string:Yw,symbol:fP,transformer:s1,tuple:PP,undefined:pP,union:TP,unknown:gP,void:yP,NEVER:WP,ZodIssueCode:pt,quotelessJson:NM,ZodError:ws}),$_={exports:{}},Jw={};function Rs(r,e){typeof e=="boolean"&&(e={forever:e}),this._originalTimeouts=JSON.parse(JSON.stringify(r)),this._timeouts=r,this._options=e||{},this._maxRetryTime=e&&e.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}var GP=Rs;Rs.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};Rs.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};Rs.prototype.retry=function(r){if(this._timeout&&clearTimeout(this._timeout),!r)return!1;var e=new Date().getTime();if(r&&e-this._operationStart>=this._maxRetryTime)return this._errors.push(r),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(r);var t=this._timeouts.shift();if(t===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),t=this._cachedTimeouts.slice(-1);else return!1;var n=this;return this._timer=setTimeout(function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout(function(){n._operationTimeoutCb(n._attempts)},n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)},t),this._options.unref&&this._timer.unref(),!0};Rs.prototype.attempt=function(r,e){this._fn=r,e&&(e.timeout&&(this._operationTimeout=e.timeout),e.cb&&(this._operationTimeoutCb=e.cb));var t=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){t._operationTimeoutCb()},t._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};Rs.prototype.try=function(r){console.log("Using RetryOperation.try() is deprecated"),this.attempt(r)};Rs.prototype.start=function(r){console.log("Using RetryOperation.start() is deprecated"),this.attempt(r)};Rs.prototype.start=Rs.prototype.try;Rs.prototype.errors=function(){return this._errors};Rs.prototype.attempts=function(){return this._attempts};Rs.prototype.mainError=function(){if(this._errors.length===0)return null;for(var r={},e=null,t=0,n=0;n=t&&(e=a,t=u)}return e};(function(r){var e=GP;r.operation=function(t){var n=r.timeouts(t);return new e(n,{forever:t&&(t.forever||t.retries===1/0),unref:t&&t.unref,maxRetryTime:t&&t.maxRetryTime})},r.timeouts=function(t){if(t instanceof Array)return[].concat(t);var n={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var a in t)n[a]=t[a];if(n.minTimeout>n.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var o=[],u=0;u{const n=t.retries-(e-1);return r.attemptNumber=e,r.retriesLeft=n,r},YP=r=>qP.includes(r),tv=(r,e)=>new Promise((t,n)=>{e={onFailedAttempt:()=>{},retries:10,...e};const a=KP.operation(e);a.attempt(async o=>{try{t(await r(o))}catch(u){if(!(u instanceof Error)){n(new TypeError(`Non-error was thrown: "${u}". You should only throw errors.`));return}if(u instanceof ev)a.stop(),n(u.originalError);else if(u instanceof TypeError&&!YP(u.message))a.stop(),n(u);else{ZP(u,o,e);try{await e.onFailedAttempt(u)}catch(d){n(d);return}a.retry(u)||n(a.mainError())}}})});$_.exports=tv;$_.exports.default=tv;$_.exports.AbortError=ev;var XP=$_.exports,p_=A_(XP),QP=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function ap(r){return typeof r=="string"&&QP.test(r)}var Bn=[];for(var Lg=0;Lg<256;++Lg)Bn.push((Lg+256).toString(16).slice(1));function JP(r,e=0){return(Bn[r[e+0]]+Bn[r[e+1]]+Bn[r[e+2]]+Bn[r[e+3]]+"-"+Bn[r[e+4]]+Bn[r[e+5]]+"-"+Bn[r[e+6]]+Bn[r[e+7]]+"-"+Bn[r[e+8]]+Bn[r[e+9]]+"-"+Bn[r[e+10]]+Bn[r[e+11]]+Bn[r[e+12]]+Bn[r[e+13]]+Bn[r[e+14]]+Bn[r[e+15]]).toLowerCase()}var zm,eC=new Uint8Array(16);function tC(){if(!zm&&(zm=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!zm))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return zm(eC)}var rC=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),a1={randomUUID:rC};function hs(r,e,t){if(a1.randomUUID&&!e&&!r)return a1.randomUUID();r=r||{};var n=r.random||(r.rng||tC)();return n[6]=n[6]&15|64,n[8]=n[8]&63|128,JP(n)}var rv={},nv={exports:{}};(function(r){var e=Object.prototype.hasOwnProperty,t="~";function n(){}Object.create&&(n.prototype=Object.create(null),new n().__proto__||(t=!1));function a(c,h,_){this.fn=c,this.context=h,this.once=_||!1}function o(c,h,_,y,w){if(typeof _!="function")throw new TypeError("The listener must be a function");var M=new a(_,y||c,w),S=t?t+h:h;return c._events[S]?c._events[S].fn?c._events[S]=[c._events[S],M]:c._events[S].push(M):(c._events[S]=M,c._eventsCount++),c}function u(c,h){--c._eventsCount===0?c._events=new n:delete c._events[h]}function d(){this._events=new n,this._eventsCount=0}d.prototype.eventNames=function(){var h=[],_,y;if(this._eventsCount===0)return h;for(y in _=this._events)e.call(_,y)&&h.push(t?y.slice(1):y);return Object.getOwnPropertySymbols?h.concat(Object.getOwnPropertySymbols(_)):h},d.prototype.listeners=function(h){var _=t?t+h:h,y=this._events[_];if(!y)return[];if(y.fn)return[y.fn];for(var w=0,M=y.length,S=new Array(M);w(e=e||(()=>{}),r.then(t=>new Promise(n=>{n(e())}).then(()=>t),t=>new Promise(n=>{n(e())}).then(()=>{throw t})));const aC=sC;class sv extends Error{constructor(e){super(e),this.name="TimeoutError"}}const av=(r,e,t)=>new Promise((n,a)=>{if(typeof e!="number"||e<0)throw new TypeError("Expected `milliseconds` to be a positive number");if(e===1/0){n(r);return}const o=setTimeout(()=>{if(typeof t=="function"){try{n(t())}catch(c){a(c)}return}const u=typeof t=="string"?t:`Promise timed out after ${e} milliseconds`,d=t instanceof Error?t:new sv(u);typeof r.cancel=="function"&&r.cancel(),a(d)},e);aC(r.then(n,a),()=>{clearTimeout(o)})});O_.exports=av;O_.exports.default=av;O_.exports.TimeoutError=sv;var iC=O_.exports,z0={},U0={};Object.defineProperty(U0,"__esModule",{value:!0});function oC(r,e,t){let n=0,a=r.length;for(;a>0;){const o=a/2|0;let u=n+o;t(r[u],e)<=0?(n=++u,a-=o+1):a=o}return n}U0.default=oC;Object.defineProperty(z0,"__esModule",{value:!0});const uC=U0;class lC{constructor(){this._queue=[]}enqueue(e,t){t=Object.assign({priority:0},t);const n={priority:t.priority,run:e};if(this.size&&this._queue[this.size-1].priority>=t.priority){this._queue.push(n);return}const a=uC.default(this._queue,n,(o,u)=>u.priority-o.priority);this._queue.splice(a,0,n)}dequeue(){const e=this._queue.shift();return e==null?void 0:e.run}filter(e){return this._queue.filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return this._queue.length}}z0.default=lC;Object.defineProperty(rv,"__esModule",{value:!0});const cC=nC,iv=iC,dC=z0,Um=()=>{},hC=new iv.TimeoutError;class fC extends cC{constructor(e){var t,n,a,o;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=Um,this._resolveIdle=Um,e=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:dC.default},e),!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(n=(t=e.intervalCap)===null||t===void 0?void 0:t.toString())!==null&&n!==void 0?n:""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(o=(a=e.interval)===null||a===void 0?void 0:a.toString())!==null&&o!==void 0?o:""}\` (${typeof e.interval})`);this._carryoverConcurrencyCount=e.carryoverConcurrencyCount,this._isIntervalIgnored=e.intervalCap===1/0||e.interval===0,this._intervalCap=e.intervalCap,this._interval=e.interval,this._queue=new e.queueClass,this._queueClass=e.queueClass,this.concurrency=e.concurrency,this._timeout=e.timeout,this._throwOnTimeout=e.throwOnTimeout===!0,this._isPaused=e.autoStart===!1}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount{this._onResumeInterval()},t)),!0}return!1}_tryToStartAnother(){if(this._queue.size===0)return this._intervalId&&clearInterval(this._intervalId),this._intervalId=void 0,this._resolvePromises(),!1;if(!this._isPaused){const e=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){const t=this._queue.dequeue();return t?(this.emit("active"),t(),e&&this._initializeIntervalIfNeeded(),!0):!1}}return!1}_initializeIntervalIfNeeded(){this._isIntervalIgnored||this._intervalId!==void 0||(this._intervalId=setInterval(()=>{this._onInterval()},this._interval),this._intervalEnd=Date.now()+this._interval)}_onInterval(){this._intervalCount===0&&this._pendingCount===0&&this._intervalId&&(clearInterval(this._intervalId),this._intervalId=void 0),this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0,this._processQueue()}_processQueue(){for(;this._tryToStartAnother(););}get concurrency(){return this._concurrency}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this._concurrency=e,this._processQueue()}async add(e,t={}){return new Promise((n,a)=>{const o=async()=>{this._pendingCount++,this._intervalCount++;try{const u=this._timeout===void 0&&t.timeout===void 0?e():iv.default(Promise.resolve(e()),t.timeout===void 0?this._timeout:t.timeout,()=>{(t.throwOnTimeout===void 0?this._throwOnTimeout:t.throwOnTimeout)&&a(hC)});n(await u)}catch(u){a(u)}this._next()};this._queue.enqueue(o,t),this._tryToStartAnother(),this.emit("add")})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this._isPaused?(this._isPaused=!1,this._processQueue(),this):this}pause(){this._isPaused=!0}clear(){this._queue=new this._queueClass}async onEmpty(){if(this._queue.size!==0)return new Promise(e=>{const t=this._resolveEmpty;this._resolveEmpty=()=>{t(),e()}})}async onIdle(){if(!(this._pendingCount===0&&this._queue.size===0))return new Promise(e=>{const t=this._resolveIdle;this._resolveIdle=()=>{t(),e()}})}get size(){return this._queue.size}sizeBy(e){return this._queue.filter(e).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(e){this._timeout=e}}var Va=rv.default=fC;const pC=(...r)=>fetch(...r),mC=Symbol.for("ls:fetch_implementation"),Qt=()=>globalThis[mC]??pC,_C=[400,401,403,404,405,406,407,408],gC=[409];let i1=class{constructor(e){Object.defineProperty(this,"maxConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxRetries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onFailedResponseHook",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,"default"in Va?this.queue=new Va.default({concurrency:this.maxConcurrency}):this.queue=new Va({concurrency:this.maxConcurrency}),this.onFailedResponseHook=e==null?void 0:e.onFailedResponseHook}call(e,...t){const n=this.onFailedResponseHook;return this.queue.add(()=>p_(()=>e(...t).catch(a=>{throw a instanceof Error?a:new Error(a)}),{async onFailedAttempt(a){if(a.message.startsWith("Cancel")||a.message.startsWith("TimeoutError")||a.message.startsWith("AbortError")||(a==null?void 0:a.code)==="ECONNABORTED")throw a;const o=a==null?void 0:a.response,u=o==null?void 0:o.status;if(u){if(_C.includes(+u))throw a;if(gC.includes(+u))return;n&&await n(o)}},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(e,t,...n){return e.signal?Promise.race([this.call(t,...n),new Promise((a,o)=>{var u;(u=e.signal)==null||u.addEventListener("abort",()=>{o(new Error("AbortError"))})})]):this.call(t,...n)}fetch(...e){return this.call(()=>Qt()(...e).then(t=>t.ok?t:Promise.reject(t)))}};function o1(r){return typeof(r==null?void 0:r._getType)=="function"}function u1(r){const e={type:r._getType(),data:{content:r.content}};return r!=null&&r.additional_kwargs&&Object.keys(r.additional_kwargs).length>0&&(e.data.additional_kwargs={...r.additional_kwargs}),e}function Er(r,e){if(!ap(r)){const t=e!==void 0?`Invalid UUID for ${e}: ${r}`:`Invalid UUID: ${r}`;throw new Error(t)}return r}const l1={};function ov(r){l1[r]||(console.warn(r),l1[r]=!0)}var p0={exports:{}};const bC="2.0.0",uv=256,yC=Number.MAX_SAFE_INTEGER||9007199254740991,wC=16,vC=uv-6,EC=["major","premajor","minor","preminor","patch","prepatch","prerelease"];var L_={MAX_LENGTH:uv,MAX_SAFE_COMPONENT_LENGTH:wC,MAX_SAFE_BUILD_LENGTH:vC,MAX_SAFE_INTEGER:yC,RELEASE_TYPES:EC,SEMVER_SPEC_VERSION:bC,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2},Rg={};const TC=typeof process=="object"&&Rg&&Rg.NODE_DEBUG&&/\bsemver\b/i.test(Rg.NODE_DEBUG)?(...r)=>console.error("SEMVER",...r):()=>{};var R_=TC;(function(r,e){const{MAX_SAFE_COMPONENT_LENGTH:t,MAX_SAFE_BUILD_LENGTH:n,MAX_LENGTH:a}=L_,o=R_;e=r.exports={};const u=e.re=[],d=e.safeRe=[],c=e.src=[],h=e.t={};let _=0;const y="[a-zA-Z0-9-]",w=[["\\s",1],["\\d",a],[y,n]],M=G=>{for(const[H,B]of w)G=G.split(`${H}*`).join(`${H}{0,${B}}`).split(`${H}+`).join(`${H}{1,${B}}`);return G},S=(G,H,B)=>{const z=M(H),U=_++;o(G,U,H),h[G]=U,c[U]=H,u[U]=new RegExp(H,B?"g":void 0),d[U]=new RegExp(z,B?"g":void 0)};S("NUMERICIDENTIFIER","0|[1-9]\\d*"),S("NUMERICIDENTIFIERLOOSE","\\d+"),S("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${y}*`),S("MAINVERSION",`(${c[h.NUMERICIDENTIFIER]})\\.(${c[h.NUMERICIDENTIFIER]})\\.(${c[h.NUMERICIDENTIFIER]})`),S("MAINVERSIONLOOSE",`(${c[h.NUMERICIDENTIFIERLOOSE]})\\.(${c[h.NUMERICIDENTIFIERLOOSE]})\\.(${c[h.NUMERICIDENTIFIERLOOSE]})`),S("PRERELEASEIDENTIFIER",`(?:${c[h.NUMERICIDENTIFIER]}|${c[h.NONNUMERICIDENTIFIER]})`),S("PRERELEASEIDENTIFIERLOOSE",`(?:${c[h.NUMERICIDENTIFIERLOOSE]}|${c[h.NONNUMERICIDENTIFIER]})`),S("PRERELEASE",`(?:-(${c[h.PRERELEASEIDENTIFIER]}(?:\\.${c[h.PRERELEASEIDENTIFIER]})*))`),S("PRERELEASELOOSE",`(?:-?(${c[h.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${c[h.PRERELEASEIDENTIFIERLOOSE]})*))`),S("BUILDIDENTIFIER",`${y}+`),S("BUILD",`(?:\\+(${c[h.BUILDIDENTIFIER]}(?:\\.${c[h.BUILDIDENTIFIER]})*))`),S("FULLPLAIN",`v?${c[h.MAINVERSION]}${c[h.PRERELEASE]}?${c[h.BUILD]}?`),S("FULL",`^${c[h.FULLPLAIN]}$`),S("LOOSEPLAIN",`[v=\\s]*${c[h.MAINVERSIONLOOSE]}${c[h.PRERELEASELOOSE]}?${c[h.BUILD]}?`),S("LOOSE",`^${c[h.LOOSEPLAIN]}$`),S("GTLT","((?:<|>)?=?)"),S("XRANGEIDENTIFIERLOOSE",`${c[h.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),S("XRANGEIDENTIFIER",`${c[h.NUMERICIDENTIFIER]}|x|X|\\*`),S("XRANGEPLAIN",`[v=\\s]*(${c[h.XRANGEIDENTIFIER]})(?:\\.(${c[h.XRANGEIDENTIFIER]})(?:\\.(${c[h.XRANGEIDENTIFIER]})(?:${c[h.PRERELEASE]})?${c[h.BUILD]}?)?)?`),S("XRANGEPLAINLOOSE",`[v=\\s]*(${c[h.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[h.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[h.XRANGEIDENTIFIERLOOSE]})(?:${c[h.PRERELEASELOOSE]})?${c[h.BUILD]}?)?)?`),S("XRANGE",`^${c[h.GTLT]}\\s*${c[h.XRANGEPLAIN]}$`),S("XRANGELOOSE",`^${c[h.GTLT]}\\s*${c[h.XRANGEPLAINLOOSE]}$`),S("COERCEPLAIN",`(^|[^\\d])(\\d{1,${t}})(?:\\.(\\d{1,${t}}))?(?:\\.(\\d{1,${t}}))?`),S("COERCE",`${c[h.COERCEPLAIN]}(?:$|[^\\d])`),S("COERCEFULL",c[h.COERCEPLAIN]+`(?:${c[h.PRERELEASE]})?(?:${c[h.BUILD]})?(?:$|[^\\d])`),S("COERCERTL",c[h.COERCE],!0),S("COERCERTLFULL",c[h.COERCEFULL],!0),S("LONETILDE","(?:~>?)"),S("TILDETRIM",`(\\s*)${c[h.LONETILDE]}\\s+`,!0),e.tildeTrimReplace="$1~",S("TILDE",`^${c[h.LONETILDE]}${c[h.XRANGEPLAIN]}$`),S("TILDELOOSE",`^${c[h.LONETILDE]}${c[h.XRANGEPLAINLOOSE]}$`),S("LONECARET","(?:\\^)"),S("CARETTRIM",`(\\s*)${c[h.LONECARET]}\\s+`,!0),e.caretTrimReplace="$1^",S("CARET",`^${c[h.LONECARET]}${c[h.XRANGEPLAIN]}$`),S("CARETLOOSE",`^${c[h.LONECARET]}${c[h.XRANGEPLAINLOOSE]}$`),S("COMPARATORLOOSE",`^${c[h.GTLT]}\\s*(${c[h.LOOSEPLAIN]})$|^$`),S("COMPARATOR",`^${c[h.GTLT]}\\s*(${c[h.FULLPLAIN]})$|^$`),S("COMPARATORTRIM",`(\\s*)${c[h.GTLT]}\\s*(${c[h.LOOSEPLAIN]}|${c[h.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",S("HYPHENRANGE",`^\\s*(${c[h.XRANGEPLAIN]})\\s+-\\s+(${c[h.XRANGEPLAIN]})\\s*$`),S("HYPHENRANGELOOSE",`^\\s*(${c[h.XRANGEPLAINLOOSE]})\\s+-\\s+(${c[h.XRANGEPLAINLOOSE]})\\s*$`),S("STAR","(<|>)?=?\\s*\\*"),S("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),S("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")})(p0,p0.exports);var Rp=p0.exports;const xC=Object.freeze({loose:!0}),MC=Object.freeze({}),PC=r=>r?typeof r!="object"?xC:r:MC;var V0=PC;const c1=/^[0-9]+$/,lv=(r,e)=>{const t=c1.test(r),n=c1.test(e);return t&&n&&(r=+r,e=+e),r===e?0:t&&!n?-1:n&&!t?1:rlv(e,r);var cv={compareIdentifiers:lv,rcompareIdentifiers:CC};const Vm=R_,{MAX_LENGTH:d1,MAX_SAFE_INTEGER:Wm}=L_,{safeRe:h1,t:f1}=Rp,SC=V0,{compareIdentifiers:El}=cv;let AC=class va{constructor(e,t){if(t=SC(t),e instanceof va){if(e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease)return e;e=e.version}else if(typeof e!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof e}".`);if(e.length>d1)throw new TypeError(`version is longer than ${d1} characters`);Vm("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;const n=e.trim().match(t.loose?h1[f1.LOOSE]:h1[f1.FULL]);if(!n)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+n[1],this.minor=+n[2],this.patch=+n[3],this.major>Wm||this.major<0)throw new TypeError("Invalid major version");if(this.minor>Wm||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>Wm||this.patch<0)throw new TypeError("Invalid patch version");n[4]?this.prerelease=n[4].split(".").map(a=>{if(/^[0-9]+$/.test(a)){const o=+a;if(o>=0&&o=0;)typeof this.prerelease[o]=="number"&&(this.prerelease[o]++,o=-2);if(o===-1){if(t===this.prerelease.join(".")&&n===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(a)}}if(t){let o=[t,a];n===!1&&(o=[t]),El(this.prerelease[0],t)===0?isNaN(this.prerelease[1])&&(this.prerelease=o):this.prerelease=o}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};var ts=AC;const p1=ts,kC=(r,e,t=!1)=>{if(r instanceof p1)return r;try{return new p1(r,e)}catch(n){if(!t)return null;throw n}};var Wl=kC;const IC=Wl,$C=(r,e)=>{const t=IC(r,e);return t?t.version:null};var OC=$C;const LC=Wl,RC=(r,e)=>{const t=LC(r.trim().replace(/^[=v]+/,""),e);return t?t.version:null};var FC=RC;const m1=ts,NC=(r,e,t,n,a)=>{typeof t=="string"&&(a=n,n=t,t=void 0);try{return new m1(r instanceof m1?r.version:r,t).inc(e,n,a).version}catch{return null}};var DC=NC;const _1=Wl,BC=(r,e)=>{const t=_1(r,null,!0),n=_1(e,null,!0),a=t.compare(n);if(a===0)return null;const o=a>0,u=o?t:n,d=o?n:t,c=!!u.prerelease.length;if(!!d.prerelease.length&&!c)return!d.patch&&!d.minor?"major":u.patch?"patch":u.minor?"minor":"major";const _=c?"pre":"";return t.major!==n.major?_+"major":t.minor!==n.minor?_+"minor":t.patch!==n.patch?_+"patch":"prerelease"};var jC=BC;const zC=ts,UC=(r,e)=>new zC(r,e).major;var VC=UC;const WC=ts,GC=(r,e)=>new WC(r,e).minor;var HC=GC;const KC=ts,qC=(r,e)=>new KC(r,e).patch;var ZC=qC;const YC=Wl,XC=(r,e)=>{const t=YC(r,e);return t&&t.prerelease.length?t.prerelease:null};var QC=XC;const g1=ts,JC=(r,e,t)=>new g1(r,t).compare(new g1(e,t));var ta=JC;const eS=ta,tS=(r,e,t)=>eS(e,r,t);var rS=tS;const nS=ta,sS=(r,e)=>nS(r,e,!0);var aS=sS;const b1=ts,iS=(r,e,t)=>{const n=new b1(r,t),a=new b1(e,t);return n.compare(a)||n.compareBuild(a)};var W0=iS;const oS=W0,uS=(r,e)=>r.sort((t,n)=>oS(t,n,e));var lS=uS;const cS=W0,dS=(r,e)=>r.sort((t,n)=>cS(n,t,e));var hS=dS;const fS=ta,pS=(r,e,t)=>fS(r,e,t)>0;var F_=pS;const mS=ta,_S=(r,e,t)=>mS(r,e,t)<0;var G0=_S;const gS=ta,bS=(r,e,t)=>gS(r,e,t)===0;var dv=bS;const yS=ta,wS=(r,e,t)=>yS(r,e,t)!==0;var hv=wS;const vS=ta,ES=(r,e,t)=>vS(r,e,t)>=0;var H0=ES;const TS=ta,xS=(r,e,t)=>TS(r,e,t)<=0;var K0=xS;const MS=dv,PS=hv,CS=F_,SS=H0,AS=G0,kS=K0,IS=(r,e,t,n)=>{switch(e){case"===":return typeof r=="object"&&(r=r.version),typeof t=="object"&&(t=t.version),r===t;case"!==":return typeof r=="object"&&(r=r.version),typeof t=="object"&&(t=t.version),r!==t;case"":case"=":case"==":return MS(r,t,n);case"!=":return PS(r,t,n);case">":return CS(r,t,n);case">=":return SS(r,t,n);case"<":return AS(r,t,n);case"<=":return kS(r,t,n);default:throw new TypeError(`Invalid operator: ${e}`)}};var fv=IS;const $S=ts,OS=Wl,{safeRe:Gm,t:Hm}=Rp,LS=(r,e)=>{if(r instanceof $S)return r;if(typeof r=="number"&&(r=String(r)),typeof r!="string")return null;e=e||{};let t=null;if(!e.rtl)t=r.match(e.includePrerelease?Gm[Hm.COERCEFULL]:Gm[Hm.COERCE]);else{const c=e.includePrerelease?Gm[Hm.COERCERTLFULL]:Gm[Hm.COERCERTL];let h;for(;(h=c.exec(r))&&(!t||t.index+t[0].length!==r.length);)(!t||h.index+h[0].length!==t.index+t[0].length)&&(t=h),c.lastIndex=h.index+h[1].length+h[2].length;c.lastIndex=-1}if(t===null)return null;const n=t[2],a=t[3]||"0",o=t[4]||"0",u=e.includePrerelease&&t[5]?`-${t[5]}`:"",d=e.includePrerelease&&t[6]?`+${t[6]}`:"";return OS(`${n}.${a}.${o}${u}${d}`,e)};var RS=LS;class FS{constructor(){this.max=1e3,this.map=new Map}get(e){const t=this.map.get(e);if(t!==void 0)return this.map.delete(e),this.map.set(e,t),t}delete(e){return this.map.delete(e)}set(e,t){if(!this.delete(e)&&t!==void 0){if(this.map.size>=this.max){const a=this.map.keys().next().value;this.delete(a)}this.map.set(e,t)}return this}}var NS=FS,Fg,y1;function ra(){if(y1)return Fg;y1=1;const r=/\s+/g;class e{constructor(re,ge){if(ge=a(ge),re instanceof e)return re.loose===!!ge.loose&&re.includePrerelease===!!ge.includePrerelease?re:new e(re.raw,ge);if(re instanceof o)return this.raw=re.value,this.set=[[re]],this.formatted=void 0,this;if(this.options=ge,this.loose=!!ge.loose,this.includePrerelease=!!ge.includePrerelease,this.raw=re.trim().replace(r," "),this.set=this.raw.split("||").map(ve=>this.parseRange(ve.trim())).filter(ve=>ve.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const ve=this.set[0];if(this.set=this.set.filter(me=>!G(me[0])),this.set.length===0)this.set=[ve];else if(this.set.length>1){for(const me of this.set)if(me.length===1&&H(me[0])){this.set=[me];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let re=0;re0&&(this.formatted+="||");const ge=this.set[re];for(let ve=0;ve0&&(this.formatted+=" "),this.formatted+=ge[ve].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(re){const ve=((this.options.includePrerelease&&M)|(this.options.loose&&S))+":"+re,me=n.get(ve);if(me)return me;const Le=this.options.loose,$e=Le?c[h.HYPHENRANGELOOSE]:c[h.HYPHENRANGE];re=re.replace($e,Te(this.options.includePrerelease)),u("hyphen replace",re),re=re.replace(c[h.COMPARATORTRIM],_),u("comparator trim",re),re=re.replace(c[h.TILDETRIM],y),u("tilde trim",re),re=re.replace(c[h.CARETTRIM],w),u("caret trim",re);let pe=re.split(" ").map(Re=>z(Re,this.options)).join(" ").split(/\s+/).map(Re=>Pe(Re,this.options));Le&&(pe=pe.filter(Re=>(u("loose invalid filter",Re,this.options),!!Re.match(c[h.COMPARATORLOOSE])))),u("range list",pe);const X=new Map,le=pe.map(Re=>new o(Re,this.options));for(const Re of le){if(G(Re))return[Re];X.set(Re.value,Re)}X.size>1&&X.has("")&&X.delete("");const ke=[...X.values()];return n.set(ve,ke),ke}intersects(re,ge){if(!(re instanceof e))throw new TypeError("a Range is required");return this.set.some(ve=>B(ve,ge)&&re.set.some(me=>B(me,ge)&&ve.every(Le=>me.every($e=>Le.intersects($e,ge)))))}test(re){if(!re)return!1;if(typeof re=="string")try{re=new d(re,this.options)}catch{return!1}for(let ge=0;geoe.value==="<0.0.0-0",H=oe=>oe.value==="",B=(oe,re)=>{let ge=!0;const ve=oe.slice();let me=ve.pop();for(;ge&&ve.length;)ge=ve.every(Le=>me.intersects(Le,re)),me=ve.pop();return ge},z=(oe,re)=>(u("comp",oe,re),oe=k(oe,re),u("caret",oe),oe=F(oe,re),u("tildes",oe),oe=j(oe,re),u("xrange",oe),oe=ue(oe,re),u("stars",oe),oe),U=oe=>!oe||oe.toLowerCase()==="x"||oe==="*",F=(oe,re)=>oe.trim().split(/\s+/).map(ge=>I(ge,re)).join(" "),I=(oe,re)=>{const ge=re.loose?c[h.TILDELOOSE]:c[h.TILDE];return oe.replace(ge,(ve,me,Le,$e,pe)=>{u("tilde",oe,ve,me,Le,$e,pe);let X;return U(me)?X="":U(Le)?X=`>=${me}.0.0 <${+me+1}.0.0-0`:U($e)?X=`>=${me}.${Le}.0 <${me}.${+Le+1}.0-0`:pe?(u("replaceTilde pr",pe),X=`>=${me}.${Le}.${$e}-${pe} <${me}.${+Le+1}.0-0`):X=`>=${me}.${Le}.${$e} <${me}.${+Le+1}.0-0`,u("tilde return",X),X})},k=(oe,re)=>oe.trim().split(/\s+/).map(ge=>$(ge,re)).join(" "),$=(oe,re)=>{u("caret",oe,re);const ge=re.loose?c[h.CARETLOOSE]:c[h.CARET],ve=re.includePrerelease?"-0":"";return oe.replace(ge,(me,Le,$e,pe,X)=>{u("caret",oe,me,Le,$e,pe,X);let le;return U(Le)?le="":U($e)?le=`>=${Le}.0.0${ve} <${+Le+1}.0.0-0`:U(pe)?Le==="0"?le=`>=${Le}.${$e}.0${ve} <${Le}.${+$e+1}.0-0`:le=`>=${Le}.${$e}.0${ve} <${+Le+1}.0.0-0`:X?(u("replaceCaret pr",X),Le==="0"?$e==="0"?le=`>=${Le}.${$e}.${pe}-${X} <${Le}.${$e}.${+pe+1}-0`:le=`>=${Le}.${$e}.${pe}-${X} <${Le}.${+$e+1}.0-0`:le=`>=${Le}.${$e}.${pe}-${X} <${+Le+1}.0.0-0`):(u("no pr"),Le==="0"?$e==="0"?le=`>=${Le}.${$e}.${pe}${ve} <${Le}.${$e}.${+pe+1}-0`:le=`>=${Le}.${$e}.${pe}${ve} <${Le}.${+$e+1}.0-0`:le=`>=${Le}.${$e}.${pe} <${+Le+1}.0.0-0`),u("caret return",le),le})},j=(oe,re)=>(u("replaceXRanges",oe,re),oe.split(/\s+/).map(ge=>ce(ge,re)).join(" ")),ce=(oe,re)=>{oe=oe.trim();const ge=re.loose?c[h.XRANGELOOSE]:c[h.XRANGE];return oe.replace(ge,(ve,me,Le,$e,pe,X)=>{u("xRange",oe,ve,me,Le,$e,pe,X);const le=U(Le),ke=le||U($e),Re=ke||U(pe),Xe=Re;return me==="="&&Xe&&(me=""),X=re.includePrerelease?"-0":"",le?me===">"||me==="<"?ve="<0.0.0-0":ve="*":me&&Xe?(ke&&($e=0),pe=0,me===">"?(me=">=",ke?(Le=+Le+1,$e=0,pe=0):($e=+$e+1,pe=0)):me==="<="&&(me="<",ke?Le=+Le+1:$e=+$e+1),me==="<"&&(X="-0"),ve=`${me+Le}.${$e}.${pe}${X}`):ke?ve=`>=${Le}.0.0${X} <${+Le+1}.0.0-0`:Re&&(ve=`>=${Le}.${$e}.0${X} <${Le}.${+$e+1}.0-0`),u("xRange return",ve),ve})},ue=(oe,re)=>(u("replaceStars",oe,re),oe.trim().replace(c[h.STAR],"")),Pe=(oe,re)=>(u("replaceGTE0",oe,re),oe.trim().replace(c[re.includePrerelease?h.GTE0PRE:h.GTE0],"")),Te=oe=>(re,ge,ve,me,Le,$e,pe,X,le,ke,Re,Xe)=>(U(ve)?ge="":U(me)?ge=`>=${ve}.0.0${oe?"-0":""}`:U(Le)?ge=`>=${ve}.${me}.0${oe?"-0":""}`:$e?ge=`>=${ge}`:ge=`>=${ge}${oe?"-0":""}`,U(le)?X="":U(ke)?X=`<${+le+1}.0.0-0`:U(Re)?X=`<${le}.${+ke+1}.0-0`:Xe?X=`<=${le}.${ke}.${Re}-${Xe}`:oe?X=`<${le}.${ke}.${+Re+1}-0`:X=`<=${X}`,`${ge} ${X}`.trim()),ie=(oe,re,ge)=>{for(let ve=0;ve0){const me=oe[ve].semver;if(me.major===re.major&&me.minor===re.minor&&me.patch===re.patch)return!0}return!1}return!0};return Fg}var Ng,w1;function N_(){if(w1)return Ng;w1=1;const r=Symbol("SemVer ANY");class e{static get ANY(){return r}constructor(_,y){if(y=t(y),_ instanceof e){if(_.loose===!!y.loose)return _;_=_.value}_=_.trim().split(/\s+/).join(" "),u("comparator",_,y),this.options=y,this.loose=!!y.loose,this.parse(_),this.semver===r?this.value="":this.value=this.operator+this.semver.version,u("comp",this)}parse(_){const y=this.options.loose?n[a.COMPARATORLOOSE]:n[a.COMPARATOR],w=_.match(y);if(!w)throw new TypeError(`Invalid comparator: ${_}`);this.operator=w[1]!==void 0?w[1]:"",this.operator==="="&&(this.operator=""),w[2]?this.semver=new d(w[2],this.options.loose):this.semver=r}toString(){return this.value}test(_){if(u("Comparator.test",_,this.options.loose),this.semver===r||_===r)return!0;if(typeof _=="string")try{_=new d(_,this.options)}catch{return!1}return o(_,this.operator,this.semver,this.options)}intersects(_,y){if(!(_ instanceof e))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new c(_.value,y).test(this.value):_.operator===""?_.value===""?!0:new c(this.value,y).test(_.semver):(y=t(y),y.includePrerelease&&(this.value==="<0.0.0-0"||_.value==="<0.0.0-0")||!y.includePrerelease&&(this.value.startsWith("<0.0.0")||_.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&_.operator.startsWith(">")||this.operator.startsWith("<")&&_.operator.startsWith("<")||this.semver.version===_.semver.version&&this.operator.includes("=")&&_.operator.includes("=")||o(this.semver,"<",_.semver,y)&&this.operator.startsWith(">")&&_.operator.startsWith("<")||o(this.semver,">",_.semver,y)&&this.operator.startsWith("<")&&_.operator.startsWith(">")))}}Ng=e;const t=V0,{safeRe:n,t:a}=Rp,o=fv,u=R_,d=ts,c=ra();return Ng}const DS=ra(),BS=(r,e,t)=>{try{e=new DS(e,t)}catch{return!1}return e.test(r)};var D_=BS;const jS=ra(),zS=(r,e)=>new jS(r,e).set.map(t=>t.map(n=>n.value).join(" ").trim().split(" "));var US=zS;const VS=ts,WS=ra(),GS=(r,e,t)=>{let n=null,a=null,o=null;try{o=new WS(e,t)}catch{return null}return r.forEach(u=>{o.test(u)&&(!n||a.compare(u)===-1)&&(n=u,a=new VS(n,t))}),n};var HS=GS;const KS=ts,qS=ra(),ZS=(r,e,t)=>{let n=null,a=null,o=null;try{o=new qS(e,t)}catch{return null}return r.forEach(u=>{o.test(u)&&(!n||a.compare(u)===1)&&(n=u,a=new KS(n,t))}),n};var YS=ZS;const Dg=ts,XS=ra(),v1=F_,QS=(r,e)=>{r=new XS(r,e);let t=new Dg("0.0.0");if(r.test(t)||(t=new Dg("0.0.0-0"),r.test(t)))return t;t=null;for(let n=0;n{const d=new Dg(u.semver.version);switch(u.operator){case">":d.prerelease.length===0?d.patch++:d.prerelease.push(0),d.raw=d.format();case"":case">=":(!o||v1(d,o))&&(o=d);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${u.operator}`)}}),o&&(!t||v1(t,o))&&(t=o)}return t&&r.test(t)?t:null};var JS=QS;const eA=ra(),tA=(r,e)=>{try{return new eA(r,e).range||"*"}catch{return null}};var rA=tA;const nA=ts,pv=N_(),{ANY:sA}=pv,aA=ra(),iA=D_,E1=F_,T1=G0,oA=K0,uA=H0,lA=(r,e,t,n)=>{r=new nA(r,n),e=new aA(e,n);let a,o,u,d,c;switch(t){case">":a=E1,o=oA,u=T1,d=">",c=">=";break;case"<":a=T1,o=uA,u=E1,d="<",c="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(iA(r,e,n))return!1;for(let h=0;h{M.semver===sA&&(M=new pv(">=0.0.0")),y=y||M,w=w||M,a(M.semver,y.semver,n)?y=M:u(M.semver,w.semver,n)&&(w=M)}),y.operator===d||y.operator===c||(!w.operator||w.operator===d)&&o(r,w.semver))return!1;if(w.operator===c&&u(r,w.semver))return!1}return!0};var q0=lA;const cA=q0,dA=(r,e,t)=>cA(r,e,">",t);var hA=dA;const fA=q0,pA=(r,e,t)=>fA(r,e,"<",t);var mA=pA;const x1=ra(),_A=(r,e,t)=>(r=new x1(r,t),e=new x1(e,t),r.intersects(e,t));var gA=_A;const bA=D_,yA=ta;var wA=(r,e,t)=>{const n=[];let a=null,o=null;const u=r.sort((_,y)=>yA(_,y,t));for(const _ of u)bA(_,e,t)?(o=_,a||(a=_)):(o&&n.push([a,o]),o=null,a=null);a&&n.push([a,null]);const d=[];for(const[_,y]of n)_===y?d.push(_):!y&&_===u[0]?d.push("*"):y?_===u[0]?d.push(`<=${y}`):d.push(`${_} - ${y}`):d.push(`>=${_}`);const c=d.join(" || "),h=typeof e.raw=="string"?e.raw:String(e);return c.length{if(r===e)return!0;r=new M1(r,t),e=new M1(e,t);let n=!1;e:for(const a of r.set){for(const o of e.set){const u=TA(a,o,t);if(n=n||u!==null,u)continue e}if(n)return!1}return!0},EA=[new Z0(">=0.0.0-0")],P1=[new Z0(">=0.0.0")],TA=(r,e,t)=>{if(r===e)return!0;if(r.length===1&&r[0].semver===Bg){if(e.length===1&&e[0].semver===Bg)return!0;t.includePrerelease?r=EA:r=P1}if(e.length===1&&e[0].semver===Bg){if(t.includePrerelease)return!0;e=P1}const n=new Set;let a,o;for(const M of r)M.operator===">"||M.operator===">="?a=C1(a,M,t):M.operator==="<"||M.operator==="<="?o=S1(o,M,t):n.add(M.semver);if(n.size>1)return null;let u;if(a&&o){if(u=Y0(a.semver,o.semver,t),u>0)return null;if(u===0&&(a.operator!==">="||o.operator!=="<="))return null}for(const M of n){if(a&&!Qf(M,String(a),t)||o&&!Qf(M,String(o),t))return null;for(const S of e)if(!Qf(M,String(S),t))return!1;return!0}let d,c,h,_,y=o&&!t.includePrerelease&&o.semver.prerelease.length?o.semver:!1,w=a&&!t.includePrerelease&&a.semver.prerelease.length?a.semver:!1;y&&y.prerelease.length===1&&o.operator==="<"&&y.prerelease[0]===0&&(y=!1);for(const M of e){if(_=_||M.operator===">"||M.operator===">=",h=h||M.operator==="<"||M.operator==="<=",a){if(w&&M.semver.prerelease&&M.semver.prerelease.length&&M.semver.major===w.major&&M.semver.minor===w.minor&&M.semver.patch===w.patch&&(w=!1),M.operator===">"||M.operator===">="){if(d=C1(a,M,t),d===M&&d!==a)return!1}else if(a.operator===">="&&!Qf(a.semver,String(M),t))return!1}if(o){if(y&&M.semver.prerelease&&M.semver.prerelease.length&&M.semver.major===y.major&&M.semver.minor===y.minor&&M.semver.patch===y.patch&&(y=!1),M.operator==="<"||M.operator==="<="){if(c=S1(o,M,t),c===M&&c!==o)return!1}else if(o.operator==="<="&&!Qf(o.semver,String(M),t))return!1}if(!M.operator&&(o||a)&&u!==0)return!1}return!(a&&h&&!o&&u!==0||o&&_&&!a&&u!==0||w||y)},C1=(r,e,t)=>{if(!r)return e;const n=Y0(r.semver,e.semver,t);return n>0?r:n<0||e.operator===">"&&r.operator===">="?e:r},S1=(r,e,t)=>{if(!r)return e;const n=Y0(r.semver,e.semver,t);return n<0?r:n>0||e.operator==="<"&&r.operator==="<="?e:r};var xA=vA;const jg=Rp,A1=L_,MA=ts,k1=cv,PA=Wl,CA=OC,SA=FC,AA=DC,kA=jC,IA=VC,$A=HC,OA=ZC,LA=QC,RA=ta,FA=rS,NA=aS,DA=W0,BA=lS,jA=hS,zA=F_,UA=G0,VA=dv,WA=hv,GA=H0,HA=K0,KA=fv,qA=RS,ZA=N_(),YA=ra(),XA=D_,QA=US,JA=HS,e3=YS,t3=JS,r3=rA,n3=q0,s3=hA,a3=mA,i3=gA,o3=wA,u3=xA;jg.re,jg.src,jg.t,A1.SEMVER_SPEC_VERSION,A1.RELEASE_TYPES,k1.compareIdentifiers,k1.rcompareIdentifiers;function gi(r){if(!r||r.split("/").length>2||r.startsWith("/")||r.endsWith("/")||r.split(":").length>2)throw new Error(`Invalid identifier format: ${r}`);const[e,t]=r.split(":"),n=t||"latest";if(e.includes("/")){const[a,o]=e.split("/",2);if(!a||!o)throw new Error(`Invalid identifier format: ${r}`);return[a,o,n]}else{if(!e)throw new Error(`Invalid identifier format: ${r}`);return["-",e,n]}}class l3 extends Error{constructor(e){super(e),this.name="LangSmithConflictError"}}async function yr(r,e,t){let n;if(r.ok){t&&(n=await r.text());return}n=await r.text();const a=`Failed to ${e}. Received status [${r.status}]: ${r.statusText}. Server response: ${n}`;throw r.status===409?new l3(a):new Error(a)}var I1="[...]",c3={result:"[Circular]"},m_=[],Cl=[];function d3(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function bs(r,e,t,n){var u;try{return JSON.stringify(r,e,t)}catch(d){if(!((u=d.message)!=null&&u.includes("Converting circular structure to JSON")))return console.warn("[WARNING]: LangSmith received unserializable value."),"[Unserializable]";console.warn("[WARNING]: LangSmith received circular JSON. This will decrease tracer performance."),typeof n>"u"&&(n=d3()),m0(r,"",0,[],void 0,0,n);var a;try{Cl.length===0?a=JSON.stringify(r,e,t):a=JSON.stringify(r,h3(e),t)}catch{return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;m_.length!==0;){var o=m_.pop();o.length===4?Object.defineProperty(o[0],o[1],o[3]):o[0][o[1]]=o[2]}}return a}}function zg(r,e,t,n){var a=Object.getOwnPropertyDescriptor(n,t);a.get!==void 0?a.configurable?(Object.defineProperty(n,t,{value:r}),m_.push([n,t,e,a])):Cl.push([e,t,r]):(n[t]=r,m_.push([n,t,e]))}function m0(r,e,t,n,a,o,u){o+=1;var d;if(typeof r=="object"&&r!==null){for(d=0;du.depthLimit){zg(I1,r,e,a);return}if(typeof u.edgesLimit<"u"&&t+1>u.edgesLimit){zg(I1,r,e,a);return}if(n.push(r),Array.isArray(r))for(d=0;d0)for(var n=0;n{const r=go("TRACING_SAMPLING_RATE");if(r===void 0)return;const e=parseFloat(r);if(e<0||e>1)throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${e}`);return e},p3=r=>{const t=r.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return t==="localhost"||t==="127.0.0.1"||t==="::1"};async function m3(r){const e=[];for await(const t of r)e.push(t);return e}function Ug(r){if(r!==void 0)return r.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}const _3=async r=>{if((r==null?void 0:r.status)===429){const e=parseInt(r.headers.get("retry-after")??"30",10)*1e3;if(e>0)return await new Promise(t=>setTimeout(t,e)),!0}return!1};class g3{constructor(){Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"sizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0})}peek(){return this.items[0]}push(e){let t;const n=new Promise(o=>{t=o}),a=bs(e.item).length;return this.items.push({action:e.action,payload:e.item,itemPromiseResolve:t,itemPromise:n,size:a}),this.sizeBytes+=a,n}pop(e){var a;if(e<1)throw new Error("Number of bytes to pop off may not be less than 1.");const t=[];let n=0;for(;n+(((a=this.peek())==null?void 0:a.size)??0)0;){const o=this.items.shift();o&&(t.push(o),n+=o.size,this.sizeBytes-=o.size)}if(t.length===0&&this.items.length>0){const o=this.items.shift();t.push(o),n+=o.size,this.sizeBytes-=o.size}return[t.map(o=>({action:o.action,item:o.payload})),()=>t.forEach(o=>o.itemPromiseResolve())]}}const b3=20971520,y3=2500;class Sp{constructor(e={}){var n;Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"webUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchIngestCaller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"timeout_ms",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_tenantId",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"hideInputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hideOutputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingSampleRate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"filteredPostUuids",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"autoBatchTracing",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"autoBatchQueue",{enumerable:!0,configurable:!0,writable:!0,value:new g3}),Object.defineProperty(this,"autoBatchTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchAggregationDelayMs",{enumerable:!0,configurable:!0,writable:!0,value:250}),Object.defineProperty(this,"batchSizeBytesLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"settings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"blockOnRootRunFinalization",{enumerable:!0,configurable:!0,writable:!0,value:Ti("LANGSMITH_TRACING_BACKGROUND")==="false"}),Object.defineProperty(this,"traceBatchConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:5}),Object.defineProperty(this,"_serverInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_getServerInfoPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"manualFlushMode",{enumerable:!0,configurable:!0,writable:!0,value:!1});const t=Sp.getDefaultClientConfig();if(this.tracingSampleRate=f3(),this.apiUrl=Ug(e.apiUrl??t.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1)),this.apiKey=Ug(e.apiKey??t.apiKey),this.webUrl=Ug(e.webUrl??t.webUrl),(n=this.webUrl)!=null&&n.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.timeout_ms=e.timeout_ms??9e4,this.caller=new i1(e.callerOptions??{}),this.traceBatchConcurrency=e.traceBatchConcurrency??this.traceBatchConcurrency,this.traceBatchConcurrency<1)throw new Error("Trace batch concurrency must be positive.");this.batchIngestCaller=new i1({maxRetries:2,maxConcurrency:this.traceBatchConcurrency,...e.callerOptions??{},onFailedResponseHook:_3}),this.hideInputs=e.hideInputs??e.anonymizer??t.hideInputs,this.hideOutputs=e.hideOutputs??e.anonymizer??t.hideOutputs,this.autoBatchTracing=e.autoBatchTracing??this.autoBatchTracing,this.blockOnRootRunFinalization=e.blockOnRootRunFinalization??this.blockOnRootRunFinalization,this.batchSizeBytesLimit=e.batchSizeBytesLimit,this.fetchOptions=e.fetchOptions||{},this.manualFlushMode=e.manualFlushMode??this.manualFlushMode}static getDefaultClientConfig(){const e=go("API_KEY"),t=go("ENDPOINT")??"https://api.smith.langchain.com",n=go("HIDE_INPUTS")==="true",a=go("HIDE_OUTPUTS")==="true";return{apiUrl:t,apiKey:e,webUrl:void 0,hideInputs:n,hideOutputs:a}}getHostUrl(){return this.webUrl?this.webUrl:p3(this.apiUrl)?(this.webUrl="http://localhost:3000",this.webUrl):this.apiUrl.includes("/api")&&!this.apiUrl.split(".",1)[0].endsWith("api")?(this.webUrl=this.apiUrl.replace("/api",""),this.webUrl):this.apiUrl.split(".",1)[0].includes("dev")?(this.webUrl="https://dev.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("eu")?(this.webUrl="https://eu.smith.langchain.com",this.webUrl):(this.webUrl="https://smith.langchain.com",this.webUrl)}get headers(){const e={"User-Agent":`langsmith-js/${mv}`};return this.apiKey&&(e["x-api-key"]=`${this.apiKey}`),e}processInputs(e){return this.hideInputs===!1?e:this.hideInputs===!0?{}:typeof this.hideInputs=="function"?this.hideInputs(e):e}processOutputs(e){return this.hideOutputs===!1?e:this.hideOutputs===!0?{}:typeof this.hideOutputs=="function"?this.hideOutputs(e):e}prepareRunCreateOrUpdateInputs(e){const t={...e};return t.inputs!==void 0&&(t.inputs=this.processInputs(t.inputs)),t.outputs!==void 0&&(t.outputs=this.processOutputs(t.outputs)),t}async _getResponse(e,t){const n=(t==null?void 0:t.toString())??"",a=`${this.apiUrl}${e}?${n}`,o=await this.caller.call(Qt(),a,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await yr(o,`Failed to fetch ${e}`),o}async _get(e,t){return(await this._getResponse(e,t)).json()}async*_getPaginated(e,t=new URLSearchParams,n){let a=Number(t.get("offset"))||0;const o=Number(t.get("limit"))||100;for(;;){t.set("offset",String(a)),t.set("limit",String(o));const u=`${this.apiUrl}${e}?${t}`,d=await this.caller.call(Qt(),u,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await yr(d,`Failed to fetch ${e}`);const c=n?n(await d.json()):await d.json();if(c.length===0||(yield c,c.length0;){const[n,a]=this.autoBatchQueue.pop(e);if(!n.length){a();break}const o=this._processBatch(n,a).catch(console.error);t.push(o)}return Promise.all(t)}async _processBatch(e,t){var n;if(!e.length){t();return}try{const a={runCreates:e.filter(u=>u.action==="create").map(u=>u.item),runUpdates:e.filter(u=>u.action==="update").map(u=>u.item)},o=await this._ensureServerInfo();(n=o==null?void 0:o.batch_ingest_config)!=null&&n.use_multipart_endpoint?await this.multipartIngestRuns(a):await this.batchIngestRuns(a)}finally{t()}}async processRunOperation(e){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,e.action==="create"&&(e.item=$1(e.item));const t=this.autoBatchQueue.push(e);if(this.manualFlushMode)return t;const n=await this._getBatchSizeLimitBytes();return this.autoBatchQueue.sizeBytes>n&&this.drainAutoBatchQueue(n),this.autoBatchQueue.items.length>0&&(this.autoBatchTimeout=setTimeout(()=>{this.autoBatchTimeout=void 0,this.drainAutoBatchQueue(n)},this.autoBatchAggregationDelayMs)),t}async _getServerInfo(){const e=await Qt()(`${this.apiUrl}/info`,{method:"GET",headers:{Accept:"application/json"},signal:AbortSignal.timeout(y3),...this.fetchOptions});return await yr(e,"get server info"),e.json()}async _ensureServerInfo(){return this._getServerInfoPromise===void 0&&(this._getServerInfoPromise=(async()=>{if(this._serverInfo===void 0)try{this._serverInfo=await this._getServerInfo()}catch{console.warn("[WARNING]: LangSmith failed to fetch info on supported operations. Falling back to batch operations and default limits.")}return this._serverInfo??{}})()),this._getServerInfoPromise.then(e=>(this._serverInfo===void 0&&(this._getServerInfoPromise=void 0),e))}async _getSettings(){return this.settings||(this.settings=this._get("/settings")),await this.settings}async flush(){const e=await this._getBatchSizeLimitBytes();await this.drainAutoBatchQueue(e)}async createRun(e){if(!this._filterForSampling([e]).length)return;const t={...this.headers,"Content-Type":"application/json"},n=e.project_name;delete e.project_name;const a=this.prepareRunCreateOrUpdateInputs({session_name:n,...e,start_time:e.start_time??Date.now()});if(this.autoBatchTracing&&a.trace_id!==void 0&&a.dotted_order!==void 0){this.processRunOperation({action:"create",item:a}).catch(console.error);return}const o=$1(a),u=await this.caller.call(Qt(),`${this.apiUrl}/runs`,{method:"POST",headers:t,body:bs(o),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await yr(u,"create run",!0)}async batchIngestRuns({runCreates:e,runUpdates:t}){if(e===void 0&&t===void 0)return;let n=(e==null?void 0:e.map(d=>this.prepareRunCreateOrUpdateInputs(d)))??[],a=(t==null?void 0:t.map(d=>this.prepareRunCreateOrUpdateInputs(d)))??[];if(n.length>0&&a.length>0){const d=n.reduce((h,_)=>(_.id&&(h[_.id]=_),h),{}),c=[];for(const h of a)h.id!==void 0&&d[h.id]?d[h.id]={...d[h.id],...h}:c.push(h);n=Object.values(d),a=c}const o={post:this._filterForSampling(n),patch:this._filterForSampling(a,!0)};if(!o.post.length&&!o.patch.length)return;const u={post:[],patch:[]};for(const d of["post","patch"]){const c=d,h=o[c].reverse();let _=h.pop();for(;_!==void 0;)u[c].push(_),_=h.pop()}(u.post.length>0||u.patch.length>0)&&await this._postBatchIngestRuns(bs(u))}async _postBatchIngestRuns(e){const t={...this.headers,"Content-Type":"application/json",Accept:"application/json"},n=await this.batchIngestCaller.call(Qt(),`${this.apiUrl}/runs/batch`,{method:"POST",headers:t,body:e,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await yr(n,"batch create run",!0)}async multipartIngestRuns({runCreates:e,runUpdates:t}){if(e===void 0&&t===void 0)return;const n={};let a=[];for(const _ of e??[]){const y=this.prepareRunCreateOrUpdateInputs(_);y.id!==void 0&&y.attachments!==void 0&&(n[y.id]=y.attachments),delete y.attachments,a.push(y)}let o=[];for(const _ of t??[])o.push(this.prepareRunCreateOrUpdateInputs(_));if(a.find(_=>_.trace_id===void 0||_.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run');if(o.find(_=>_.trace_id===void 0||_.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run');if(a.length>0&&o.length>0){const _=a.reduce((w,M)=>(M.id&&(w[M.id]=M),w),{}),y=[];for(const w of o)w.id!==void 0&&_[w.id]?_[w.id]={..._[w.id],...w}:y.push(w);a=Object.values(_),o=y}if(a.length===0&&o.length===0)return;const c=[],h=[];for(const[_,y]of[["post",a],["patch",o]])for(const w of y){const{inputs:M,outputs:S,events:G,attachments:H,...B}=w,z={inputs:M,outputs:S,events:G},U=bs(B);h.push({name:`${_}.${B.id}`,payload:new Blob([U],{type:`application/json; length=${U.length}`})});for(const[F,I]of Object.entries(z)){if(I===void 0)continue;const k=bs(I);h.push({name:`${_}.${B.id}.${F}`,payload:new Blob([k],{type:`application/json; length=${k.length}`})})}if(B.id!==void 0){const F=n[B.id];if(F){delete n[B.id];for(const[I,k]of Object.entries(F)){let $,j;if(Array.isArray(k)?[$,j]=k:($=k.mimeType,j=k.data),I.includes(".")){console.warn(`Skipping attachment '${I}' for run ${B.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);continue}h.push({name:`attachment.${B.id}.${I}`,payload:new Blob([j],{type:`${$}; length=${j.byteLength}`})})}}}c.push(`trace=${B.trace_id},id=${B.id}`)}await this._sendMultipartRequest(h,c.join("; "))}async _sendMultipartRequest(e,t){try{const n="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),a=[];for(const c of e)a.push(new Blob([`--${n}\r `])),a.push(new Blob([`Content-Disposition: form-data; name="${c.name}"\r `,`Content-Type: ${c.payload.type}\r \r `])),a.push(c.payload),a.push(new Blob([`\r `]));a.push(new Blob([`--${n}--\r `]));const u=await new Blob(a).arrayBuffer(),d=await this.batchIngestCaller.call(Qt(),`${this.apiUrl}/runs/multipart`,{method:"POST",headers:{...this.headers,"Content-Type":`multipart/form-data; boundary=${n}`},body:u,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await yr(d,"ingest multipart runs",!0)}catch(n){console.warn(`${n.message.trim()} Context: ${t}`)}}async updateRun(e,t){Er(e),t.inputs&&(t.inputs=this.processInputs(t.inputs)),t.outputs&&(t.outputs=this.processOutputs(t.outputs));const n={...t,id:e};if(!this._filterForSampling([n],!0).length)return;if(this.autoBatchTracing&&n.trace_id!==void 0&&n.dotted_order!==void 0){if(t.end_time!==void 0&&n.parent_run_id===void 0&&this.blockOnRootRunFinalization&&!this.manualFlushMode){await this.processRunOperation({action:"update",item:n}).catch(console.error);return}else this.processRunOperation({action:"update",item:n}).catch(console.error);return}const a={...this.headers,"Content-Type":"application/json"},o=await this.caller.call(Qt(),`${this.apiUrl}/runs/${e}`,{method:"PATCH",headers:a,body:bs(t),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await yr(o,"update run",!0)}async readRun(e,{loadChildRuns:t}={loadChildRuns:!1}){Er(e);let n=await this._get(`/runs/${e}`);return t&&n.child_run_ids&&(n=await this._loadChildRuns(n)),n}async getRunUrl({runId:e,run:t,projectOpts:n}){if(t!==void 0){let a;t.session_id?a=t.session_id:n!=null&&n.projectName?a=(await this.readProject({projectName:n==null?void 0:n.projectName})).id:n!=null&&n.projectId?a=n==null?void 0:n.projectId:a=(await this.readProject({projectName:go("PROJECT")||"default"})).id;const o=await this._getTenantId();return`${this.getHostUrl()}/o/${o}/projects/p/${a}/r/${t.id}?poll=true`}else if(e!==void 0){const a=await this.readRun(e);if(!a.app_path)throw new Error(`Run ${e} has no app_path`);return`${this.getHostUrl()}${a.app_path}`}else throw new Error("Must provide either runId or run")}async _loadChildRuns(e){const t=await m3(this.listRuns({id:e.child_run_ids})),n={},a={};t.sort((o,u)=>((o==null?void 0:o.dotted_order)??"").localeCompare((u==null?void 0:u.dotted_order)??""));for(const o of t){if(o.parent_run_id===null||o.parent_run_id===void 0)throw new Error(`Child run ${o.id} has no parent`);o.parent_run_id in n||(n[o.parent_run_id]=[]),n[o.parent_run_id].push(o),a[o.id]=o}e.child_runs=n[e.id]||[];for(const o in n)o!==e.id&&(a[o].child_runs=n[o]);return e}async*listRuns(e){const{projectId:t,projectName:n,parentRunId:a,traceId:o,referenceExampleId:u,startTime:d,executionOrder:c,isRoot:h,runType:_,error:y,id:w,query:M,filter:S,traceFilter:G,treeFilter:H,limit:B,select:z}=e;let U=[];if(t&&(U=Array.isArray(t)?t:[t]),n){const $=Array.isArray(n)?n:[n],j=await Promise.all($.map(ce=>this.readProject({projectName:ce}).then(ue=>ue.id)));U.push(...j)}const F=["app_path","child_run_ids","completion_cost","completion_tokens","dotted_order","end_time","error","events","extra","feedback_stats","first_token_time","id","inputs","name","outputs","parent_run_id","parent_run_ids","prompt_cost","prompt_tokens","reference_example_id","run_type","session_id","start_time","status","tags","total_cost","total_tokens","trace_id"],I={session:U.length?U:null,run_type:_,reference_example:u,query:M,filter:S,trace_filter:G,tree_filter:H,execution_order:c,parent_run:a,start_time:d?d.toISOString():null,error:y,id:w,limit:B,trace:o,select:z||F,is_root:h};let k=0;for await(const $ of this._getCursorPaginatedList("/runs/query",I))if(B){if(k>=B)break;if($.length+k>B){yield*$.slice(0,B-k);break}k+=$.length,yield*$}else yield*$}async getRunStats({id:e,trace:t,parentRun:n,runType:a,projectNames:o,projectIds:u,referenceExampleIds:d,startTime:c,endTime:h,error:_,query:y,filter:w,traceFilter:M,treeFilter:S,isRoot:G,dataSourceType:H}){let B=u||[];o&&(B=[...u||[],...await Promise.all(o.map(k=>this.readProject({projectName:k}).then($=>$.id)))]);const U=Object.fromEntries(Object.entries({id:e,trace:t,parent_run:n,run_type:a,session:B,reference_example:d,start_time:c,end_time:h,error:_,query:y,filter:w,trace_filter:M,tree_filter:S,is_root:G,data_source_type:H}).filter(([k,$])=>$!==void 0));return await(await this.caller.call(Qt(),`${this.apiUrl}/runs/stats`,{method:"POST",headers:this.headers,body:JSON.stringify(U),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions})).json()}async shareRun(e,{shareId:t}={}){const n={run_id:e,share_token:t||hs()};Er(e);const o=await(await this.caller.call(Qt(),`${this.apiUrl}/runs/${e}/share`,{method:"PUT",headers:this.headers,body:JSON.stringify(n),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions})).json();if(o===null||!("share_token"in o))throw new Error("Invalid response from server");return`${this.getHostUrl()}/public/${o.share_token}/r`}async unshareRun(e){Er(e);const t=await this.caller.call(Qt(),`${this.apiUrl}/runs/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await yr(t,"unshare run",!0)}async readRunSharedLink(e){Er(e);const n=await(await this.caller.call(Qt(),`${this.apiUrl}/runs/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions})).json();if(!(n===null||!("share_token"in n)))return`${this.getHostUrl()}/public/${n.share_token}/r`}async listSharedRuns(e,{runIds:t}={}){const n=new URLSearchParams({share_token:e});if(t!==void 0)for(const u of t)n.append("id",u);return Er(e),await(await this.caller.call(Qt(),`${this.apiUrl}/public/${e}/runs${n}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions})).json()}async readDatasetSharedSchema(e,t){if(!e&&!t)throw new Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:t})).id),Er(e);const a=await(await this.caller.call(Qt(),`${this.apiUrl}/datasets/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions})).json();return a.url=`${this.getHostUrl()}/public/${a.share_token}/d`,a}async shareDataset(e,t){if(!e&&!t)throw new Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:t})).id);const n={dataset_id:e};Er(e);const o=await(await this.caller.call(Qt(),`${this.apiUrl}/datasets/${e}/share`,{method:"PUT",headers:this.headers,body:JSON.stringify(n),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions})).json();return o.url=`${this.getHostUrl()}/public/${o.share_token}/d`,o}async unshareDataset(e){Er(e);const t=await this.caller.call(Qt(),`${this.apiUrl}/datasets/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await yr(t,"unshare dataset",!0)}async readSharedDataset(e){return Er(e),await(await this.caller.call(Qt(),`${this.apiUrl}/public/${e}/datasets`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions})).json()}async listSharedExamples(e,t){const n={};t!=null&&t.exampleIds&&(n.id=t.exampleIds);const a=new URLSearchParams;Object.entries(n).forEach(([d,c])=>{Array.isArray(c)?c.forEach(h=>a.append(d,h)):a.append(d,c)});const o=await this.caller.call(Qt(),`${this.apiUrl}/public/${e}/examples?${a.toString()}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),u=await o.json();if(!o.ok)throw"detail"in u?new Error(`Failed to list shared examples. Status: ${o.status} Message: ${u.detail.join(` `)}`):new Error(`Failed to list shared examples: ${o.status} ${o.statusText}`);return u.map(d=>({...d,_hostUrl:this.getHostUrl()}))}async createProject({projectName:e,description:t=null,metadata:n=null,upsert:a=!1,projectExtra:o=null,referenceDatasetId:u=null}){const d=a?"?upsert=true":"",c=`${this.apiUrl}/sessions${d}`,h=o||{};n&&(h.metadata=n);const _={name:e,extra:h,description:t};u!==null&&(_.reference_dataset_id=u);const y=await this.caller.call(Qt(),c,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(_),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await yr(y,"create project"),await y.json()}async updateProject(e,{name:t=null,description:n=null,metadata:a=null,projectExtra:o=null,endTime:u=null}){const d=`${this.apiUrl}/sessions/${e}`;let c=o;a&&(c={...c||{},metadata:a});const h={name:t,extra:c,description:n,end_time:u?new Date(u).toISOString():null},_=await this.caller.call(Qt(),d,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(h),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await yr(_,"update project"),await _.json()}async hasProject({projectId:e,projectName:t}){let n="/sessions";const a=new URLSearchParams;if(e!==void 0&&t!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)Er(e),n+=`/${e}`;else if(t!==void 0)a.append("name",t);else throw new Error("Must provide projectName or projectId");const o=await this.caller.call(Qt(),`${this.apiUrl}${n}?${a}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});try{const u=await o.json();return o.ok?Array.isArray(u)?u.length>0:!0:!1}catch{return!1}}async readProject({projectId:e,projectName:t,includeStats:n}){let a="/sessions";const o=new URLSearchParams;if(e!==void 0&&t!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)Er(e),a+=`/${e}`;else if(t!==void 0)o.append("name",t);else throw new Error("Must provide projectName or projectId");n!==void 0&&o.append("include_stats",n.toString());const u=await this._get(a,o);let d;if(Array.isArray(u)){if(u.length===0)throw new Error(`Project[id=${e}, name=${t}] not found`);d=u[0]}else d=u;return d}async getProjectUrl({projectId:e,projectName:t}){if(e===void 0&&t===void 0)throw new Error("Must provide either projectName or projectId");const n=await this.readProject({projectId:e,projectName:t}),a=await this._getTenantId();return`${this.getHostUrl()}/o/${a}/projects/p/${n.id}`}async getDatasetUrl({datasetId:e,datasetName:t}){if(e===void 0&&t===void 0)throw new Error("Must provide either datasetName or datasetId");const n=await this.readDataset({datasetId:e,datasetName:t}),a=await this._getTenantId();return`${this.getHostUrl()}/o/${a}/datasets/${n.id}`}async _getTenantId(){if(this._tenantId!==null)return this._tenantId;const e=new URLSearchParams({limit:"1"});for await(const t of this._getPaginated("/sessions",e))return this._tenantId=t[0].tenant_id,t[0].tenant_id;throw new Error("No projects found to resolve tenant.")}async*listProjects({projectIds:e,name:t,nameContains:n,referenceDatasetId:a,referenceDatasetName:o,referenceFree:u,metadata:d}={}){const c=new URLSearchParams;if(e!==void 0)for(const h of e)c.append("id",h);if(t!==void 0&&c.append("name",t),n!==void 0&&c.append("name_contains",n),a!==void 0)c.append("reference_dataset",a);else if(o!==void 0){const h=await this.readDataset({datasetName:o});c.append("reference_dataset",h.id)}u!==void 0&&c.append("reference_free",u.toString()),d!==void 0&&c.append("metadata",JSON.stringify(d));for await(const h of this._getPaginated("/sessions",c))yield*h}async deleteProject({projectId:e,projectName:t}){let n;if(e===void 0&&t===void 0)throw new Error("Must provide projectName or projectId");if(e!==void 0&&t!==void 0)throw new Error("Must provide either projectName or projectId, not both");e===void 0?n=(await this.readProject({projectName:t})).id:n=e,Er(n);const a=await this.caller.call(Qt(),`${this.apiUrl}/sessions/${n}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await yr(a,`delete session ${n} (${t})`,!0)}async uploadCsv({csvFile:e,fileName:t,inputKeys:n,outputKeys:a,description:o,dataType:u,name:d}){const c=`${this.apiUrl}/datasets/upload`,h=new FormData;h.append("file",e,t),n.forEach(w=>{h.append("input_keys",w)}),a.forEach(w=>{h.append("output_keys",w)}),o&&h.append("description",o),u&&h.append("data_type",u),d&&h.append("name",d);const _=await this.caller.call(Qt(),c,{method:"POST",headers:this.headers,body:h,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await yr(_,"upload CSV"),await _.json()}async createDataset(e,{description:t,dataType:n,inputsSchema:a,outputsSchema:o,metadata:u}={}){const d={name:e,description:t,extra:u?{metadata:u}:void 0};n&&(d.data_type=n),a&&(d.inputs_schema_definition=a),o&&(d.outputs_schema_definition=o);const c=await this.caller.call(Qt(),`${this.apiUrl}/datasets`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(d),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await yr(c,"create dataset"),await c.json()}async readDataset({datasetId:e,datasetName:t}){let n="/datasets";const a=new URLSearchParams({limit:"1"});if(e!==void 0&&t!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(e!==void 0)Er(e),n+=`/${e}`;else if(t!==void 0)a.append("name",t);else throw new Error("Must provide datasetName or datasetId");const o=await this._get(n,a);let u;if(Array.isArray(o)){if(o.length===0)throw new Error(`Dataset[id=${e}, name=${t}] not found`);u=o[0]}else u=o;return u}async hasDataset({datasetId:e,datasetName:t}){try{return await this.readDataset({datasetId:e,datasetName:t}),!0}catch(n){if(n instanceof Error&&n.message.toLocaleLowerCase().includes("not found"))return!1;throw n}}async diffDatasetVersions({datasetId:e,datasetName:t,fromVersion:n,toVersion:a}){let o=e;if(o===void 0&&t===void 0)throw new Error("Must provide either datasetName or datasetId");if(o!==void 0&&t!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");o===void 0&&(o=(await this.readDataset({datasetName:t})).id);const u=new URLSearchParams({from_version:typeof n=="string"?n:n.toISOString(),to_version:typeof a=="string"?a:a.toISOString()});return await this._get(`/datasets/${o}/versions/diff`,u)}async readDatasetOpenaiFinetuning({datasetId:e,datasetName:t}){const n="/datasets";if(e===void 0)if(t!==void 0)e=(await this.readDataset({datasetName:t})).id;else throw new Error("Must provide datasetName or datasetId");return(await(await this._getResponse(`${n}/${e}/openai_ft`)).text()).trim().split(` `).map(d=>JSON.parse(d))}async*listDatasets({limit:e=100,offset:t=0,datasetIds:n,datasetName:a,datasetNameContains:o,metadata:u}={}){const d="/datasets",c=new URLSearchParams({limit:e.toString(),offset:t.toString()});if(n!==void 0)for(const h of n)c.append("id",h);a!==void 0&&c.append("name",a),o!==void 0&&c.append("name_contains",o),u!==void 0&&c.append("metadata",JSON.stringify(u));for await(const h of this._getPaginated(d,c))yield*h}async updateDataset(e){const{datasetId:t,datasetName:n,...a}=e;if(!t&&!n)throw new Error("Must provide either datasetName or datasetId");const o=t??(await this.readDataset({datasetName:n})).id;Er(o);const u=await this.caller.call(Qt(),`${this.apiUrl}/datasets/${o}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(a),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await yr(u,"update dataset"),await u.json()}async deleteDataset({datasetId:e,datasetName:t}){let n="/datasets",a=e;if(e!==void 0&&t!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(t!==void 0&&(a=(await this.readDataset({datasetName:t})).id),a!==void 0)Er(a),n+=`/${a}`;else throw new Error("Must provide datasetName or datasetId");const o=await this.caller.call(Qt(),this.apiUrl+n,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await yr(o,`delete ${n}`),await o.json()}async indexDataset({datasetId:e,datasetName:t,tag:n}){let a=e;if(!a&&!t)throw new Error("Must provide either datasetName or datasetId");if(a&&t)throw new Error("Must provide either datasetName or datasetId, not both");a||(a=(await this.readDataset({datasetName:t})).id),Er(a);const o={tag:n},u=await this.caller.call(Qt(),`${this.apiUrl}/datasets/${a}/index`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await yr(u,"index dataset"),await u.json()}async similarExamples(e,t,n,{filter:a}={}){const o={limit:n,inputs:e};a!==void 0&&(o.filter=a),Er(t);const u=await this.caller.call(Qt(),`${this.apiUrl}/datasets/${t}/search`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await yr(u,"fetch similar examples"),(await u.json()).examples}async createExample(e,t,{datasetId:n,datasetName:a,createdAt:o,exampleId:u,metadata:d,split:c,sourceRunId:h}){let _=n;if(_===void 0&&a===void 0)throw new Error("Must provide either datasetName or datasetId");if(_!==void 0&&a!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");_===void 0&&(_=(await this.readDataset({datasetName:a})).id);const y=o||new Date,w={dataset_id:_,inputs:e,outputs:t,created_at:y==null?void 0:y.toISOString(),id:u,metadata:d,split:c,source_run_id:h},M=await this.caller.call(Qt(),`${this.apiUrl}/examples`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(w),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await yr(M,"create example"),await M.json()}async createExamples(e){const{inputs:t,outputs:n,metadata:a,sourceRunIds:o,exampleIds:u,datasetId:d,datasetName:c}=e;let h=d;if(h===void 0&&c===void 0)throw new Error("Must provide either datasetName or datasetId");if(h!==void 0&&c!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");h===void 0&&(h=(await this.readDataset({datasetName:c})).id);const _=t.map((M,S)=>({dataset_id:h,inputs:M,outputs:n?n[S]:void 0,metadata:a?a[S]:void 0,split:e.splits?e.splits[S]:void 0,id:u?u[S]:void 0,source_run_id:o?o[S]:void 0})),y=await this.caller.call(Qt(),`${this.apiUrl}/examples/bulk`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(_),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await yr(y,"create examples"),await y.json()}async createLLMExample(e,t,n){return this.createExample({input:e},{output:t},n)}async createChatExample(e,t,n){const a=e.map(u=>o1(u)?u1(u):u),o=o1(t)?u1(t):t;return this.createExample({input:a},{output:o},n)}async readExample(e){Er(e);const t=`/examples/${e}`,n=await this._get(t),{attachment_urls:a,...o}=n,u=o;return a&&(u.attachments=Object.entries(a).reduce((d,[c,h])=>(d[c.slice(11)]={presigned_url:h.presigned_url},d),{})),u}async*listExamples({datasetId:e,datasetName:t,exampleIds:n,asOf:a,splits:o,inlineS3Urls:u,metadata:d,limit:c,offset:h,filter:_,includeAttachments:y}={}){let w;if(e!==void 0&&t!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(e!==void 0)w=e;else if(t!==void 0)w=(await this.readDataset({datasetName:t})).id;else throw new Error("Must provide a datasetName or datasetId");const M=new URLSearchParams({dataset:w}),S=a?typeof a=="string"?a:a==null?void 0:a.toISOString():void 0;S&&M.append("as_of",S);const G=u??!0;if(M.append("inline_s3_urls",G.toString()),n!==void 0)for(const B of n)M.append("id",B);if(o!==void 0)for(const B of o)M.append("splits",B);if(d!==void 0){const B=JSON.stringify(d);M.append("metadata",B)}c!==void 0&&M.append("limit",c.toString()),h!==void 0&&M.append("offset",h.toString()),_!==void 0&&M.append("filter",_),y===!0&&["attachment_urls","outputs","metadata"].forEach(B=>M.append("select",B));let H=0;for await(const B of this._getPaginated("/examples",M)){for(const z of B){const{attachment_urls:U,...F}=z,I=F;U&&(I.attachments=Object.entries(U).reduce((k,[$,j])=>(k[$.slice(11)]={presigned_url:j.presigned_url},k),{})),yield I,H++}if(c!==void 0&&H>=c)break}}async deleteExample(e){Er(e);const t=`/examples/${e}`,n=await this.caller.call(Qt(),this.apiUrl+t,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await yr(n,`delete ${t}`),await n.json()}async updateExample(e,t){Er(e);const n=await this.caller.call(Qt(),`${this.apiUrl}/examples/${e}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(t),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await yr(n,"update example"),await n.json()}async updateExamples(e){const t=await this.caller.call(Qt(),`${this.apiUrl}/examples/bulk`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(e),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await yr(t,"update examples"),await t.json()}async listDatasetSplits({datasetId:e,datasetName:t,asOf:n}){let a;if(e===void 0&&t===void 0)throw new Error("Must provide dataset name or ID");if(e!==void 0&&t!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");e===void 0?a=(await this.readDataset({datasetName:t})).id:a=e,Er(a);const o=new URLSearchParams,u=n?typeof n=="string"?n:n==null?void 0:n.toISOString():void 0;return u&&o.append("as_of",u),await this._get(`/datasets/${a}/splits`,o)}async updateDatasetSplits({datasetId:e,datasetName:t,splitName:n,exampleIds:a,remove:o=!1}){let u;if(e===void 0&&t===void 0)throw new Error("Must provide dataset name or ID");if(e!==void 0&&t!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");e===void 0?u=(await this.readDataset({datasetName:t})).id:u=e,Er(u);const d={split_name:n,examples:a.map(h=>(Er(h),h)),remove:o},c=await this.caller.call(Qt(),`${this.apiUrl}/datasets/${u}/splits`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(d),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await yr(c,"update dataset splits",!0)}async evaluateRun(e,t,{sourceInfo:n,loadChildRuns:a,referenceExample:o}={loadChildRuns:!1}){ov("This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead.");let u;if(typeof e=="string")u=await this.readRun(e,{loadChildRuns:a});else if(typeof e=="object"&&"id"in e)u=e;else throw new Error(`Invalid run type: ${typeof e}`);u.reference_example_id!==null&&u.reference_example_id!==void 0&&(o=await this.readExample(u.reference_example_id));const d=await t.evaluateRun(u,o),[c,h]=await this._logEvaluationFeedback(d,u,n);return h[0]}async createFeedback(e,t,{score:n,value:a,correction:o,comment:u,sourceInfo:d,feedbackSourceType:c="api",sourceRunId:h,feedbackId:_,feedbackConfig:y,projectId:w,comparativeExperimentId:M}){var z;if(!e&&!w)throw new Error("One of runId or projectId must be provided");if(e&&w)throw new Error("Only one of runId or projectId can be provided");const S={type:c??"api",metadata:d??{}};h!==void 0&&(S==null?void 0:S.metadata)!==void 0&&!S.metadata.__run&&(S.metadata.__run={run_id:h}),(S==null?void 0:S.metadata)!==void 0&&((z=S.metadata.__run)==null?void 0:z.run_id)!==void 0&&Er(S.metadata.__run.run_id);const G={id:_??hs(),run_id:e,key:t,score:n,value:a,correction:o,comment:u,feedback_source:S,comparative_experiment_id:M,feedbackConfig:y,session_id:w},H=`${this.apiUrl}/feedback`,B=await this.caller.call(Qt(),H,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(G),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await yr(B,"create feedback",!0),G}async updateFeedback(e,{score:t,value:n,correction:a,comment:o}){const u={};t!=null&&(u.score=t),n!=null&&(u.value=n),a!=null&&(u.correction=a),o!=null&&(u.comment=o),Er(e);const d=await this.caller.call(Qt(),`${this.apiUrl}/feedback/${e}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(u),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await yr(d,"update feedback",!0)}async readFeedback(e){Er(e);const t=`/feedback/${e}`;return await this._get(t)}async deleteFeedback(e){Er(e);const t=`/feedback/${e}`,n=await this.caller.call(Qt(),this.apiUrl+t,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await yr(n,`delete ${t}`),await n.json()}async*listFeedback({runIds:e,feedbackKeys:t,feedbackSourceTypes:n}={}){const a=new URLSearchParams;if(e&&a.append("run",e.join(",")),t)for(const o of t)a.append("key",o);if(n)for(const o of n)a.append("source",o);for await(const o of this._getPaginated("/feedback",a))yield*o}async createPresignedFeedbackToken(e,t,{expiration:n,feedbackConfig:a}={}){const o={run_id:e,feedback_key:t,feedback_config:a};return n?typeof n=="string"?o.expires_at=n:(n!=null&&n.hours||n!=null&&n.minutes||n!=null&&n.days)&&(o.expires_in=n):o.expires_in={hours:3},await(await this.caller.call(Qt(),`${this.apiUrl}/feedback/tokens`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions})).json()}async createComparativeExperiment({name:e,experimentIds:t,referenceDatasetId:n,createdAt:a,description:o,metadata:u,id:d}){var _;if(t.length===0)throw new Error("At least one experiment is required");if(n||(n=(await this.readProject({projectId:t[0]})).reference_dataset_id),!n==null)throw new Error("A reference dataset is required");const c={id:d,name:e,experiment_ids:t,reference_dataset_id:n,description:o,created_at:(_=a??new Date)==null?void 0:_.toISOString(),extra:{}};return u&&(c.extra.metadata=u),await(await this.caller.call(Qt(),`${this.apiUrl}/datasets/comparative`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(c),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions})).json()}async*listPresignedFeedbackTokens(e){Er(e);const t=new URLSearchParams({run_id:e});for await(const n of this._getPaginated("/feedback/tokens",t))yield*n}_selectEvalResults(e){let t;return"results"in e?t=e.results:t=[e],t}async _logEvaluationFeedback(e,t,n){const a=this._selectEvalResults(e),o=[];for(const u of a){let d=n||{};u.evaluatorInfo&&(d={...u.evaluatorInfo,...d});let c=null;u.targetRunId?c=u.targetRunId:t&&(c=t.id),o.push(await this.createFeedback(c,u.key,{score:u.score,value:u.value,comment:u.comment,correction:u.correction,sourceInfo:d,sourceRunId:u.sourceRunId,feedbackConfig:u.feedbackConfig,feedbackSourceType:"model"}))}return[a,o]}async logEvaluationFeedback(e,t,n){const[a]=await this._logEvaluationFeedback(e,t,n);return a}async*listAnnotationQueues(e={}){const{queueIds:t,name:n,nameContains:a,limit:o}=e,u=new URLSearchParams;t&&t.forEach((c,h)=>{Er(c,`queueIds[${h}]`),u.append("ids",c)}),n&&u.append("name",n),a&&u.append("name_contains",a),u.append("limit",(o!==void 0?Math.min(o,100):100).toString());let d=0;for await(const c of this._getPaginated("/annotation-queues",u))if(yield*c,d++,o!==void 0&&d>=o)break}async createAnnotationQueue(e){const{name:t,description:n,queueId:a}=e,o={name:t,description:n,id:a||hs()},u=await this.caller.call(Qt(),`${this.apiUrl}/annotation-queues`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(Object.fromEntries(Object.entries(o).filter(([c,h])=>h!==void 0))),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await yr(u,"create annotation queue"),await u.json()}async readAnnotationQueue(e){const t=await this.listAnnotationQueues({queueIds:[e]}).next();if(t.done)throw new Error(`Annotation queue with ID ${e} not found`);return t.value}async updateAnnotationQueue(e,t){const{name:n,description:a}=t,o=await this.caller.call(Qt(),`${this.apiUrl}/annotation-queues/${Er(e,"queueId")}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify({name:n,description:a}),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await yr(o,"update annotation queue")}async deleteAnnotationQueue(e){const t=await this.caller.call(Qt(),`${this.apiUrl}/annotation-queues/${Er(e,"queueId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await yr(t,"delete annotation queue")}async addRunsToAnnotationQueue(e,t){const n=await this.caller.call(Qt(),`${this.apiUrl}/annotation-queues/${Er(e,"queueId")}/runs`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(t.map((a,o)=>Er(a,`runIds[${o}]`).toString())),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await yr(n,"add runs to annotation queue")}async getRunFromAnnotationQueue(e,t){const n=`/annotation-queues/${Er(e,"queueId")}/run`,a=await this.caller.call(Qt(),`${this.apiUrl}${n}/${t}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await yr(a,"get run from annotation queue"),await a.json()}async deleteRunFromAnnotationQueue(e,t){const n=await this.caller.call(Qt(),`${this.apiUrl}/annotation-queues/${Er(e,"queueId")}/runs/${Er(t,"queueRunId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await yr(n,"delete run from annotation queue")}async getSizeFromAnnotationQueue(e){const t=await this.caller.call(Qt(),`${this.apiUrl}/annotation-queues/${Er(e,"queueId")}/size`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await yr(t,"get size from annotation queue"),await t.json()}async _currentTenantIsOwner(e){const t=await this._getSettings();return e=="-"||t.tenant_handle===e}async _ownerConflictError(e,t){const n=await this._getSettings();return new Error(`Cannot ${e} for another tenant. Current tenant: ${n.tenant_handle} Requested tenant: ${t}`)}async _getLatestCommitHash(e){const t=await this.caller.call(Qt(),`${this.apiUrl}/commits/${e}/?limit=1&offset=0`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),n=await t.json();if(!t.ok){const a=typeof n.detail=="string"?n.detail:JSON.stringify(n.detail),o=new Error(`Error ${t.status}: ${t.statusText} ${a}`);throw o.statusCode=t.status,o}if(n.commits.length!==0)return n.commits[0].commit_hash}async _likeOrUnlikePrompt(e,t){const[n,a,o]=gi(e),u=await this.caller.call(Qt(),`${this.apiUrl}/likes/${n}/${a}`,{method:"POST",body:JSON.stringify({like:t}),headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await yr(u,`${t?"like":"unlike"} prompt`),await u.json()}async _getPromptUrl(e){const[t,n,a]=gi(e);if(await this._currentTenantIsOwner(t)){const o=await this._getSettings();return a!=="latest"?`${this.getHostUrl()}/prompts/${n}/${a.substring(0,8)}?organizationId=${o.id}`:`${this.getHostUrl()}/prompts/${n}?organizationId=${o.id}`}else return a!=="latest"?`${this.getHostUrl()}/hub/${t}/${n}/${a.substring(0,8)}`:`${this.getHostUrl()}/hub/${t}/${n}`}async promptExists(e){return!!await this.getPrompt(e)}async likePrompt(e){return this._likeOrUnlikePrompt(e,!0)}async unlikePrompt(e){return this._likeOrUnlikePrompt(e,!1)}async*listCommits(e){for await(const t of this._getPaginated(`/commits/${e}/`,new URLSearchParams,n=>n.commits))yield*t}async*listPrompts(e){const t=new URLSearchParams;t.append("sort_field",(e==null?void 0:e.sortField)??"updated_at"),t.append("sort_direction","desc"),t.append("is_archived",(!!(e!=null&&e.isArchived)).toString()),(e==null?void 0:e.isPublic)!==void 0&&t.append("is_public",e.isPublic.toString()),e!=null&&e.query&&t.append("query",e.query);for await(const n of this._getPaginated("/repos",t,a=>a.repos))yield*n}async getPrompt(e){const[t,n,a]=gi(e),o=await this.caller.call(Qt(),`${this.apiUrl}/repos/${t}/${n}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});if(o.status===404)return null;await yr(o,"get prompt");const u=await o.json();return u.repo?u.repo:null}async createPrompt(e,t){const n=await this._getSettings();if(t!=null&&t.isPublic&&!n.tenant_handle)throw new Error(`Cannot create a public prompt without first creating a LangChain Hub handle. You can add a handle by creating a public prompt at: https://smith.langchain.com/prompts`);const[a,o,u]=gi(e);if(!await this._currentTenantIsOwner(a))throw await this._ownerConflictError("create a prompt",a);const d={repo_handle:o,...(t==null?void 0:t.description)&&{description:t.description},...(t==null?void 0:t.readme)&&{readme:t.readme},...(t==null?void 0:t.tags)&&{tags:t.tags},is_public:!!(t!=null&&t.isPublic)},c=await this.caller.call(Qt(),`${this.apiUrl}/repos/`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(d),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await yr(c,"create prompt");const{repo:h}=await c.json();return h}async createCommit(e,t,n){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[a,o,u]=gi(e),d=(n==null?void 0:n.parentCommitHash)==="latest"||!(n!=null&&n.parentCommitHash)?await this._getLatestCommitHash(`${a}/${o}`):n==null?void 0:n.parentCommitHash,c={manifest:JSON.parse(JSON.stringify(t)),parent_commit:d},h=await this.caller.call(Qt(),`${this.apiUrl}/commits/${a}/${o}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(c),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await yr(h,"create commit");const _=await h.json();return this._getPromptUrl(`${a}/${o}${_.commit_hash?`:${_.commit_hash}`:""}`)}async updateExamplesMultipart(e,t=[]){if(!await this._getMultiPartSupport())throw new Error("Your LangSmith version does not allow using the multipart examples endpoint, please update to the latest version.");const n=new FormData;for(const u of t){const d=u.id,c={...u.metadata&&{metadata:u.metadata},...u.split&&{split:u.split}},h=bs(c),_=new Blob([h],{type:"application/json"});if(n.append(d,_),u.inputs){const y=bs(u.inputs),w=new Blob([y],{type:"application/json"});n.append(`${d}.inputs`,w)}if(u.outputs){const y=bs(u.outputs),w=new Blob([y],{type:"application/json"});n.append(`${d}.outputs`,w)}if(u.attachments)for(const[y,w]of Object.entries(u.attachments)){let M,S;Array.isArray(w)?[M,S]=w:(M=w.mimeType,S=w.data);const G=new Blob([S],{type:`${M}; length=${S.byteLength}`});n.append(`${d}.attachment.${y}`,G)}if(u.attachments_operations){const y=bs(u.attachments_operations),w=new Blob([y],{type:"application/json"});n.append(`${d}.attachments_operations`,w)}}return await(await this.caller.call(Qt(),`${this.apiUrl}/v1/platform/datasets/${e}/examples`,{method:"PATCH",headers:this.headers,body:n})).json()}async uploadExamplesMultipart(e,t=[]){if(!await this._getMultiPartSupport())throw new Error("Your LangSmith version does not allow using the multipart examples endpoint, please update to the latest version.");const n=new FormData;for(const u of t){const d=(u.id??hs()).toString(),c={created_at:u.created_at,...u.metadata&&{metadata:u.metadata},...u.split&&{split:u.split}},h=bs(c),_=new Blob([h],{type:"application/json"});n.append(d,_);const y=bs(u.inputs),w=new Blob([y],{type:"application/json"});if(n.append(`${d}.inputs`,w),u.outputs){const M=bs(u.outputs),S=new Blob([M],{type:"application/json"});n.append(`${d}.outputs`,S)}if(u.attachments)for(const[M,S]of Object.entries(u.attachments)){let G,H;Array.isArray(S)?[G,H]=S:(G=S.mimeType,H=S.data);const B=new Blob([H],{type:`${G}; length=${H.byteLength}`});n.append(`${d}.attachment.${M}`,B)}}return await(await this.caller.call(Qt(),`${this.apiUrl}/v1/platform/datasets/${e}/examples`,{method:"POST",headers:this.headers,body:n})).json()}async updatePrompt(e,t){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[n,a]=gi(e);if(!await this._currentTenantIsOwner(n))throw await this._ownerConflictError("update a prompt",n);const o={};if((t==null?void 0:t.description)!==void 0&&(o.description=t.description),(t==null?void 0:t.readme)!==void 0&&(o.readme=t.readme),(t==null?void 0:t.tags)!==void 0&&(o.tags=t.tags),(t==null?void 0:t.isPublic)!==void 0&&(o.is_public=t.isPublic),(t==null?void 0:t.isArchived)!==void 0&&(o.is_archived=t.isArchived),Object.keys(o).length===0)throw new Error("No valid update options provided");const u=await this.caller.call(Qt(),`${this.apiUrl}/repos/${n}/${a}`,{method:"PATCH",body:JSON.stringify(o),headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await yr(u,"update prompt"),u.json()}async deletePrompt(e){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[t,n,a]=gi(e);if(!await this._currentTenantIsOwner(t))throw await this._ownerConflictError("delete a prompt",t);return await(await this.caller.call(Qt(),`${this.apiUrl}/repos/${t}/${n}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions})).json()}async pullPromptCommit(e,t){const[n,a,o]=gi(e),u=await this.caller.call(Qt(),`${this.apiUrl}/commits/${n}/${a}/${o}${t!=null&&t.includeModel?"?include_model=true":""}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await yr(u,"pull prompt commit");const d=await u.json();return{owner:n,repo:a,commit_hash:d.commit_hash,manifest:d.manifest,examples:d.examples}}async _pullPrompt(e,t){const n=await this.pullPromptCommit(e,{includeModel:t==null?void 0:t.includeModel});return JSON.stringify(n.manifest)}async pushPrompt(e,t){return await this.promptExists(e)?t&&Object.keys(t).some(a=>a!=="object")&&await this.updatePrompt(e,{description:t==null?void 0:t.description,readme:t==null?void 0:t.readme,tags:t==null?void 0:t.tags,isPublic:t==null?void 0:t.isPublic}):await this.createPrompt(e,{description:t==null?void 0:t.description,readme:t==null?void 0:t.readme,tags:t==null?void 0:t.tags,isPublic:t==null?void 0:t.isPublic}),t!=null&&t.object?await this.createCommit(e,t==null?void 0:t.object,{parentCommitHash:t==null?void 0:t.parentCommitHash}):await this._getPromptUrl(e)}async clonePublicDataset(e,t={}){const{sourceApiUrl:n=this.apiUrl,datasetName:a}=t,[o,u]=this.parseTokenOrUrl(e,n),d=new Sp({apiUrl:o,apiKey:"placeholder"}),c=await d.readSharedDataset(u),h=a||c.name;try{if(await this.hasDataset({datasetId:h})){console.log(`Dataset ${h} already exists in your tenant. Skipping.`);return}}catch{}const _=await d.listSharedExamples(u),y=await this.createDataset(h,{description:c.description,dataType:c.data_type||"kv",inputsSchema:c.inputs_schema_definition??void 0,outputsSchema:c.outputs_schema_definition??void 0});try{await this.createExamples({inputs:_.map(w=>w.inputs),outputs:_.flatMap(w=>w.outputs?[w.outputs]:[]),datasetId:y.id})}catch(w){throw console.error(`An error occurred while creating dataset ${h}. You should delete it manually.`),w}}parseTokenOrUrl(e,t,n=2,a="dataset"){try{return Er(e),[t,e]}catch{}try{const u=new URL(e).pathname.split("/").filter(d=>d!=="");if(u.length>=n){const d=u[u.length-n];return[t,d]}else throw new Error(`Invalid public ${a} URL: ${e}`)}catch{throw new Error(`Invalid public ${a} URL or token: ${e}`)}}awaitPendingTraceBatches(){return this.manualFlushMode?(console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches."),Promise.resolve()):Promise.all([...this.autoBatchQueue.items.map(({itemPromise:e})=>e),this.batchIngestCaller.queue.onIdle()])}}const mv="0.2.15";var ip={};let ja;const w3=()=>typeof window<"u"&&typeof window.document<"u",v3=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",E3=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&(navigator.userAgent.includes("Node.js")||navigator.userAgent.includes("jsdom")),_v=()=>typeof Deno<"u",T3=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!_v(),x3=()=>ja||(w3()?ja="browser":T3()?ja="node":v3()?ja="webworker":E3()?ja="jsdom":_v()?ja="deno":ja="other",ja);let Vg;function gv(){if(Vg===void 0){const r=x3(),e=C3();Vg={library:"langsmith",runtime:r,sdk:"langsmith-js",sdk_version:mv,...e}}return Vg}function M3(){const r=P3()||{},e={},t=["LANGCHAIN_API_KEY","LANGCHAIN_ENDPOINT","LANGCHAIN_TRACING_V2","LANGCHAIN_PROJECT","LANGCHAIN_SESSION","LANGSMITH_API_KEY","LANGSMITH_ENDPOINT","LANGSMITH_TRACING_V2","LANGSMITH_PROJECT","LANGSMITH_SESSION"];for(const[n,a]of Object.entries(r))(n.startsWith("LANGCHAIN_")||n.startsWith("LANGSMITH_"))&&typeof a=="string"&&!t.includes(n)&&!n.toLowerCase().includes("key")&&!n.toLowerCase().includes("secret")&&!n.toLowerCase().includes("token")&&(n==="LANGCHAIN_REVISION_ID"?e.revision_id=a:e[n]=a);return e}function P3(){try{return typeof process<"u"&&ip?Object.entries(ip).reduce((r,[e,t])=>(r[e]=String(t),r),{}):void 0}catch{return}}function Ti(r){try{return typeof process<"u"?ip==null?void 0:ip[r]:void 0}catch{return}}function go(r){return Ti(`LANGSMITH_${r}`)||Ti(`LANGCHAIN_${r}`)}let Wg;function C3(){if(Wg!==void 0)return Wg;const r=["VERCEL_GIT_COMMIT_SHA","NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA","COMMIT_REF","RENDER_GIT_COMMIT","CI_COMMIT_SHA","CIRCLE_SHA1","CF_PAGES_COMMIT_SHA","REACT_APP_GIT_SHA","SOURCE_VERSION","GITHUB_SHA","TRAVIS_COMMIT","GIT_COMMIT","BUILD_VCS_NUMBER","bamboo_planRepository_revision","Build.SourceVersion","BITBUCKET_COMMIT","DRONE_COMMIT_SHA","SEMAPHORE_GIT_SHA","BUILDKITE_COMMIT"],e={};for(const t of r){const n=Ti(t);n!==void 0&&(e[t]=n)}return Wg=e,e}const S3=r=>!!["TRACING_V2","TRACING"].find(t=>go(t)==="true"),Gg=Symbol.for("lc:context_variables");function A3(r){return r.replace(/[-:.]/g,"")}function k3(r,e,t=1){const n=t.toFixed(0).slice(0,3).padStart(3,"0");return A3(`${new Date(r).toISOString().slice(0,-1)}${n}Z`)+e}class __{constructor(e,t){Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.metadata=e,this.tags=t}static fromHeader(e){const t=e.split(",");let n={},a=[];for(const o of t){const[u,d]=o.split("="),c=decodeURIComponent(d);u==="langsmith-metadata"?n=JSON.parse(c):u==="langsmith-tags"&&(a=c.split(","))}return new __(n,a)}toHeader(){const e=[];return this.metadata&&Object.keys(this.metadata).length>0&&e.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`),this.tags&&this.tags.length>0&&e.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`),e.join(",")}}class ys{constructor(e){var d;if(Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"run_type",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_runs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"end_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"extra",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"error",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"serialized",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"inputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reference_example_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"events",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"trace_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dotted_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingEnabled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"attachments",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),bv(e)){Object.assign(this,{...e});return}const t=ys.getDefaultConfig(),{metadata:n,...a}=e,o=a.client??ys.getSharedClient(),u={...n,...(d=a==null?void 0:a.extra)==null?void 0:d.metadata};if(a.extra={...a.extra,metadata:u},Object.assign(this,{...t,...a,client:o}),this.trace_id||(this.parent_run?this.trace_id=this.parent_run.trace_id??this.id:this.trace_id=this.id),this.execution_order??(this.execution_order=1),this.child_execution_order??(this.child_execution_order=1),!this.dotted_order){const c=k3(this.start_time,this.id,this.execution_order);this.parent_run?this.dotted_order=this.parent_run.dotted_order+"."+c:this.dotted_order=c}}static getDefaultConfig(){return{id:hs(),run_type:"chain",project_name:Ti("LANGCHAIN_PROJECT")??Ti("LANGCHAIN_SESSION")??"default",child_runs:[],api_url:Ti("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:Ti("LANGCHAIN_API_KEY"),caller_options:{},start_time:Date.now(),serialized:{},inputs:{},extra:{}}}static getSharedClient(){return ys.sharedClient||(ys.sharedClient=new Sp),ys.sharedClient}createChild(e){var c,h,_,y,w,M;const t=this.child_execution_order+1,n=new ys({...e,parent_run:this,project_name:this.project_name,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:t,child_execution_order:t});Gg in this&&(n[Gg]=this[Gg]);const a=Symbol.for("lc:child_config"),o=((c=e.extra)==null?void 0:c[a])??this.extra[a];if($3(o)){const S={...o},G=I3(S.callbacks)?(_=(h=S.callbacks).copy)==null?void 0:_.call(h):void 0;G&&(Object.assign(G,{_parentRunId:n.id}),(M=(w=(y=G.handlers)==null?void 0:y.find(yv))==null?void 0:w.updateFromRunTree)==null||M.call(w,n),S.callbacks=G),n.extra[a]=S}const u=new Set;let d=this;for(;d!=null&&!u.has(d.id);)u.add(d.id),d.child_execution_order=Math.max(d.child_execution_order,t),d=d.parent_run;return this.child_runs.push(n),n}async end(e,t,n=Date.now(),a){this.outputs=this.outputs??e,this.error=this.error??t,this.end_time=this.end_time??n,a&&Object.keys(a).length>0&&(this.extra=this.extra?{...this.extra,metadata:{...this.extra.metadata,...a}}:{metadata:a})}_convertToCreate(e,t,n=!0){var c;const a=e.extra??{};if(a.runtime||(a.runtime={}),t)for(const[h,_]of Object.entries(t))a.runtime[h]||(a.runtime[h]=_);let o,u;return n?(u=(c=e.parent_run)==null?void 0:c.id,o=[]):(o=e.child_runs.map(h=>this._convertToCreate(h,t,n)),u=void 0),{id:e.id,name:e.name,start_time:e.start_time,end_time:e.end_time,run_type:e.run_type,reference_example_id:e.reference_example_id,extra:a,serialized:e.serialized,error:e.error,inputs:e.inputs,outputs:e.outputs,session_name:e.project_name,child_runs:o,parent_run_id:u,trace_id:e.trace_id,dotted_order:e.dotted_order,tags:e.tags,attachments:e.attachments}}async postRun(e=!0){try{const t=gv(),n=await this._convertToCreate(this,t,!0);if(await this.client.createRun(n),!e){ov("Posting with excludeChildRuns=false is deprecated and will be removed in a future version.");for(const a of this.child_runs)await a.postRun(!1)}}catch(t){console.error(`Error in postRun for run ${this.id}:`,t)}}async patchRun(){var e;try{const t={end_time:this.end_time,error:this.error,inputs:this.inputs,outputs:this.outputs,parent_run_id:(e=this.parent_run)==null?void 0:e.id,reference_example_id:this.reference_example_id,extra:this.extra,events:this.events,dotted_order:this.dotted_order,trace_id:this.trace_id,tags:this.tags,attachments:this.attachments};await this.client.updateRun(this.id,t)}catch(t){console.error(`Error in patchRun for run ${this.id}`,t)}}toJSON(){return this._convertToCreate(this,void 0,!1)}static fromRunnableConfig(e,t){var h,_,y,w;const n=e==null?void 0:e.callbacks;let a,o,u,d=S3();if(n){const M=((h=n==null?void 0:n.getParentRunId)==null?void 0:h.call(n))??"",S=(_=n==null?void 0:n.handlers)==null?void 0:_.find(G=>(G==null?void 0:G.name)=="langchain_tracer");a=(y=S==null?void 0:S.getRun)==null?void 0:y.call(S,M),o=S==null?void 0:S.projectName,u=S==null?void 0:S.client,d=d||!!S}return a?new ys({name:a.name,id:a.id,trace_id:a.trace_id,dotted_order:a.dotted_order,client:u,tracingEnabled:d,project_name:o,tags:[...new Set(((a==null?void 0:a.tags)??[]).concat((e==null?void 0:e.tags)??[]))],extra:{metadata:{...(w=a==null?void 0:a.extra)==null?void 0:w.metadata,...e==null?void 0:e.metadata}}}).createChild(t):new ys({...t,client:u,tracingEnabled:d,project_name:o})}static fromDottedOrder(e){return this.fromHeaders({"langsmith-trace":e})}static fromHeaders(e,t){var h;const n="get"in e&&typeof e.get=="function"?{"langsmith-trace":e.get("langsmith-trace"),baggage:e.get("baggage")}:e,a=n["langsmith-trace"];if(!a||typeof a!="string")return;const o=a.trim(),u=o.split(".").map(_=>{const[y,w]=_.split("Z");return{strTime:y,time:Date.parse(y+"Z"),uuid:w}}),d=u[0].uuid,c={...t,name:(t==null?void 0:t.name)??"parent",run_type:(t==null?void 0:t.run_type)??"chain",start_time:(t==null?void 0:t.start_time)??Date.now(),id:(h=u.at(-1))==null?void 0:h.uuid,trace_id:d,dotted_order:o};if(n.baggage&&typeof n.baggage=="string"){const _=__.fromHeader(n.baggage);c.metadata=_.metadata,c.tags=_.tags}return new ys(c)}toHeaders(e){var n;const t={"langsmith-trace":this.dotted_order,baggage:new __((n=this.extra)==null?void 0:n.metadata,this.tags).toHeader()};if(e)for(const[a,o]of Object.entries(t))e.set(a,o);return t}}Object.defineProperty(ys,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});function bv(r){return r!==void 0&&typeof r.createChild=="function"&&typeof r.postRun=="function"}function yv(r){return typeof r=="object"&&r!=null&&typeof r.name=="string"&&r.name==="langchain_tracer"}function O1(r){return Array.isArray(r)&&r.some(e=>yv(e))}function I3(r){return typeof r=="object"&&r!=null&&Array.isArray(r.handlers)}function $3(r){var e;return r!==void 0&&typeof r.callbacks=="object"&&(O1((e=r.callbacks)==null?void 0:e.handlers)||O1(r.callbacks))}let O3=class{getStore(){}run(e,t){return t()}};const Hg=Symbol.for("ls:tracing_async_local_storage"),L3=new O3;let R3=class{getInstance(){return globalThis[Hg]??L3}initializeGlobalInstance(e){globalThis[Hg]===void 0&&(globalThis[Hg]=e)}};const F3=new R3,N3=()=>{const r=F3.getInstance().getStore();if(!bv(r))throw new Error(["Could not get the current run tree.","","Please make sure you are calling this method within a traceable function or the tracing is enabled."].join(` `));return r};function X0(r){return typeof r=="function"&&"langsmith:traceable"in r}/*! * https://github.com/Starcounter-Jack/JSON-Patch * (c) 2017-2022 Joachim Wester * MIT licensed */const D3=Object.prototype.hasOwnProperty;function B3(r,e){return D3.call(r,e)}function j3(r){if(Array.isArray(r)){const t=new Array(r.length);for(let n=0;n=48&&n<=57){e++;continue}return!1}return!0}function z3(r){return r.replace(/~1/g,"/").replace(/~0/g,"~")}function g0(r){if(r===void 0)return!0;if(r){if(Array.isArray(r)){for(let t=0,n=r.length;t0&&d[h-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(t&&y===void 0&&(c[w]===void 0?y=d.slice(0,h).join("/"):h==_-1&&(y=e.path),y!==void 0&&M(e,0,r,y)),h++,Array.isArray(c)){if(w==="-")w=c.length;else{if(t&&!_0(w))throw new Cn("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",o,e,r);_0(w)&&(w=~~w)}if(h>=_){if(t&&e.op==="add"&&w>c.length)throw new Cn("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",o,e,r);const S=V3[e.op].call(e,c,w,r);if(S.test===!1)throw new Cn("Test operation failed","TEST_OPERATION_FAILED",o,e,r);return S}}else if(h>=_){const S=Sl[e.op].call(e,c,w,r);if(S.test===!1)throw new Cn("Test operation failed","TEST_OPERATION_FAILED",o,e,r);return S}if(c=c[w],t&&h<_&&(!c||typeof c!="object"))throw new Cn("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",o,e,r)}}}function g_(r,e,t,n=!0,a=!0){if(t&&!Array.isArray(e))throw new Cn("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");n||(r=Fl(r));const o=new Array(e.length);for(let u=0,d=e.length;u0)throw new Cn('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,r,t);if((r.op==="move"||r.op==="copy")&&typeof r.from!="string")throw new Cn("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,r,t);if((r.op==="add"||r.op==="replace"||r.op==="test")&&r.value===void 0)throw new Cn("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,r,t);if((r.op==="add"||r.op==="replace"||r.op==="test")&&g0(r.value))throw new Cn("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,r,t);if(t){if(r.op=="add"){var a=r.path.split("/").length,o=n.split("/").length;if(a!==o+1&&a!==o)throw new Cn("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,r,t)}else if(r.op==="replace"||r.op==="remove"||r.op==="_get"){if(r.path!==n)throw new Cn("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,r,t)}else if(r.op==="move"||r.op==="copy"){var u={op:"_get",path:r.from,value:void 0},d=W3([u],t);if(d&&d.name==="OPERATION_PATH_UNRESOLVABLE")throw new Cn("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,r,t)}}}else throw new Cn("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,r,t)}function W3(r,e,t){try{if(!Array.isArray(r))throw new Cn("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)g_(Fl(e),Fl(r),t||!0);else{t=t||y0;for(var n=0;n"u"?"_":e,r.replace(/([a-z\d])([A-Z])/g,"$1"+e+"$2").replace(/([A-Z]+)([A-Z][a-z\d]+)/g,"$1"+e+"$2").toLowerCase()},H3=A_(G3),wv={exports:{}};const K3=/[\p{Lu}]/u,q3=/[\p{Ll}]/u,R1=/^[\p{Lu}](?![\p{Lu}])/gu,vv=/([\p{Alpha}\p{N}_]|$)/u,Ev=/[_.\- ]+/,Z3=new RegExp("^"+Ev.source),F1=new RegExp(Ev.source+vv.source,"gu"),N1=new RegExp("\\d+"+vv.source,"gu"),Y3=(r,e,t)=>{let n=!1,a=!1,o=!1;for(let u=0;u(R1.lastIndex=0,r.replace(R1,t=>e(t))),Q3=(r,e)=>(F1.lastIndex=0,N1.lastIndex=0,r.replace(F1,(t,n)=>e(n)).replace(N1,t=>e(t))),Tv=(r,e)=>{if(!(typeof r=="string"||Array.isArray(r)))throw new TypeError("Expected the input to be `string | string[]`");if(e={pascalCase:!1,preserveConsecutiveUppercase:!1,...e},Array.isArray(r)?r=r.map(o=>o.trim()).filter(o=>o.length).join("-"):r=r.trim(),r.length===0)return"";const t=e.locale===!1?o=>o.toLowerCase():o=>o.toLocaleLowerCase(e.locale),n=e.locale===!1?o=>o.toUpperCase():o=>o.toLocaleUpperCase(e.locale);return r.length===1?e.pascalCase?n(r):t(r):(r!==t(r)&&(r=Y3(r,t,n)),r=r.replace(Z3,""),e.preserveConsecutiveUppercase?r=X3(r,t):r=t(r),e.pascalCase&&(r=n(r.charAt(0))+r.slice(1)),Q3(r,n))};wv.exports=Tv;wv.exports.default=Tv;function J3(r,e){return(e==null?void 0:e[r])||H3(r)}function ek(r,e,t){const n={};for(const a in r)Object.hasOwn(r,a)&&(n[e(a,t)]=r[a]);return n}function D1(r){return Array.isArray(r)?[...r]:{...r}}function tk(r,e){const t=D1(r);for(const[n,a]of Object.entries(e)){const[o,...u]=n.split(".").reverse();let d=t;for(const c of u.reverse()){if(d[c]===void 0)break;d[c]=D1(d[c]),d=d[c]}d[o]!==void 0&&(d[o]={lc:1,type:"secret",id:[a]})}return t}function xv(r){const e=Object.getPrototypeOf(r);return typeof r.lc_name=="function"&&(typeof e.lc_name!="function"||r.lc_name()!==e.lc_name())?r.lc_name():r.name}class Nl{static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,xv(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}constructor(e,...t){Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.lc_kwargs=e||{}}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof Nl||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();const e={},t={},n=Object.keys(this.lc_kwargs).reduce((a,o)=>(a[o]=o in this?this[o]:this.lc_kwargs[o],a),{});for(let a=Object.getPrototypeOf(this);a;a=Object.getPrototypeOf(a))Object.assign(e,Reflect.get(a,"lc_aliases",this)),Object.assign(t,Reflect.get(a,"lc_secrets",this)),Object.assign(n,Reflect.get(a,"lc_attributes",this));return Object.keys(t).forEach(a=>{let o=this,u=n;const[d,...c]=a.split(".").reverse();for(const h of c.reverse()){if(!(h in o)||o[h]===void 0)return;(!(h in u)||u[h]===void 0)&&(typeof o[h]=="object"&&o[h]!=null?u[h]={}:Array.isArray(o[h])&&(u[h]=[])),o=o[h],u=u[h]}d in o&&o[d]!==void 0&&(u[d]=u[d]||o[d])}),{lc:1,type:"constructor",id:this.lc_id,kwargs:ek(Object.keys(t).length?tk(n,t):n,J3,e)}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}}var Kg={};const rk=()=>typeof window<"u"&&typeof window.document<"u",nk=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",sk=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&(navigator.userAgent.includes("Node.js")||navigator.userAgent.includes("jsdom")),Q0=()=>typeof Deno<"u",ak=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!Q0(),Mv=()=>{let r;return rk()?r="browser":ak()?r="node":nk()?r="webworker":sk()?r="jsdom":Q0()?r="deno":r="other",r};let qg;async function ik(){return qg===void 0&&(qg={library:"langchain-js",runtime:Mv()}),qg}function xi(r){try{return typeof process<"u"?Kg==null?void 0:Kg[r]:Q0()?Deno==null?void 0:Deno.env.get(r):void 0}catch{return}}class ok{}class Fp extends ok{get lc_namespace(){return["langchain_core","callbacks",this.name]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,xv(this.constructor)]}constructor(e){super(),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ignoreLLM",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreChain",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreAgent",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreRetriever",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreCustomEvent",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"raiseError",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"awaitHandlers",{enumerable:!0,configurable:!0,writable:!0,value:xi("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"}),this.lc_kwargs=e||{},e&&(this.ignoreLLM=e.ignoreLLM??this.ignoreLLM,this.ignoreChain=e.ignoreChain??this.ignoreChain,this.ignoreAgent=e.ignoreAgent??this.ignoreAgent,this.ignoreRetriever=e.ignoreRetriever??this.ignoreRetriever,this.ignoreCustomEvent=e.ignoreCustomEvent??this.ignoreCustomEvent,this.raiseError=e.raiseError??this.raiseError,this.awaitHandlers=this.raiseError||(e._awaitHandler??this.awaitHandlers))}copy(){return new this.constructor(this)}toJSON(){return Nl.prototype.toJSON.call(this)}toJSONNotImplemented(){return Nl.prototype.toJSONNotImplemented.call(this)}static fromMethods(e){class t extends Fp{constructor(){super(),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:hs()}),Object.assign(this,e)}}return new t}}const uk=r=>{const e=r;return e!==void 0&&typeof e.copy=="function"&&typeof e.name=="string"&&typeof e.awaitHandlers=="boolean"};function Zg(r,e){return r&&!Array.isArray(r)&&typeof r=="object"?r:{[e]:r}}function lk(r){return r.replace(/[-:.]/g,"")}function ck(r,e,t){const n=t.toFixed(0).slice(0,3).padStart(3,"0");return lk(`${new Date(r).toISOString().slice(0,-1)}${n}Z`)+e}function Jf(r){return typeof r._addRunToRunMap=="function"}class Np extends Fp{constructor(e){super(...arguments),Object.defineProperty(this,"runMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}copy(){return this}stringifyError(e){return e instanceof Error?e.message+(e!=null&&e.stack?` ${e.stack}`:""):typeof e=="string"?e:`${e}`}_addChildRun(e,t){e.child_runs.push(t)}_addRunToRunMap(e){const t=ck(e.start_time,e.id,e.execution_order),n={...e};if(n.parent_run_id!==void 0){const a=this.runMap.get(n.parent_run_id);a&&(this._addChildRun(a,n),a.child_execution_order=Math.max(a.child_execution_order,n.child_execution_order),n.trace_id=a.trace_id,a.dotted_order!==void 0&&(n.dotted_order=[a.dotted_order,t].join(".")))}else n.trace_id=n.id,n.dotted_order=t;return this.runMap.set(n.id,n),n}async _endTrace(e){var n;const t=e.parent_run_id!==void 0&&this.runMap.get(e.parent_run_id);t?t.child_execution_order=Math.max(t.child_execution_order,e.child_execution_order):await this.persistRun(e),this.runMap.delete(e.id),await((n=this.onRunUpdate)==null?void 0:n.call(this,e))}_getExecutionOrder(e){const t=e!==void 0&&this.runMap.get(e);return t?t.child_execution_order+1:1}_createRunForLLMStart(e,t,n,a,o,u,d,c){const h=this._getExecutionOrder(a),_=Date.now(),y=d?{...o,metadata:d}:o,w={id:n,name:c??e.id[e.id.length-1],parent_run_id:a,start_time:_,serialized:e,events:[{name:"start",time:new Date(_).toISOString()}],inputs:{prompts:t},execution_order:h,child_runs:[],child_execution_order:h,run_type:"llm",extra:y??{},tags:u||[]};return this._addRunToRunMap(w)}async handleLLMStart(e,t,n,a,o,u,d,c){var _,y;const h=this.runMap.get(n)??this._createRunForLLMStart(e,t,n,a,o,u,d,c);return await((_=this.onRunCreate)==null?void 0:_.call(this,h)),await((y=this.onLLMStart)==null?void 0:y.call(this,h)),h}_createRunForChatModelStart(e,t,n,a,o,u,d,c){const h=this._getExecutionOrder(a),_=Date.now(),y=d?{...o,metadata:d}:o,w={id:n,name:c??e.id[e.id.length-1],parent_run_id:a,start_time:_,serialized:e,events:[{name:"start",time:new Date(_).toISOString()}],inputs:{messages:t},execution_order:h,child_runs:[],child_execution_order:h,run_type:"llm",extra:y??{},tags:u||[]};return this._addRunToRunMap(w)}async handleChatModelStart(e,t,n,a,o,u,d,c){var _,y;const h=this.runMap.get(n)??this._createRunForChatModelStart(e,t,n,a,o,u,d,c);return await((_=this.onRunCreate)==null?void 0:_.call(this,h)),await((y=this.onLLMStart)==null?void 0:y.call(this,h)),h}async handleLLMEnd(e,t){var a;const n=this.runMap.get(t);if(!n||(n==null?void 0:n.run_type)!=="llm")throw new Error("No LLM run to end.");return n.end_time=Date.now(),n.outputs=e,n.events.push({name:"end",time:new Date(n.end_time).toISOString()}),await((a=this.onLLMEnd)==null?void 0:a.call(this,n)),await this._endTrace(n),n}async handleLLMError(e,t){var a;const n=this.runMap.get(t);if(!n||(n==null?void 0:n.run_type)!=="llm")throw new Error("No LLM run to end.");return n.end_time=Date.now(),n.error=this.stringifyError(e),n.events.push({name:"error",time:new Date(n.end_time).toISOString()}),await((a=this.onLLMError)==null?void 0:a.call(this,n)),await this._endTrace(n),n}_createRunForChainStart(e,t,n,a,o,u,d,c){const h=this._getExecutionOrder(a),_=Date.now(),y={id:n,name:c??e.id[e.id.length-1],parent_run_id:a,start_time:_,serialized:e,events:[{name:"start",time:new Date(_).toISOString()}],inputs:t,execution_order:h,child_execution_order:h,run_type:d??"chain",child_runs:[],extra:u?{metadata:u}:{},tags:o||[]};return this._addRunToRunMap(y)}async handleChainStart(e,t,n,a,o,u,d,c){var _,y;const h=this.runMap.get(n)??this._createRunForChainStart(e,t,n,a,o,u,d,c);return await((_=this.onRunCreate)==null?void 0:_.call(this,h)),await((y=this.onChainStart)==null?void 0:y.call(this,h)),h}async handleChainEnd(e,t,n,a,o){var d;const u=this.runMap.get(t);if(!u)throw new Error("No chain run to end.");return u.end_time=Date.now(),u.outputs=Zg(e,"output"),u.events.push({name:"end",time:new Date(u.end_time).toISOString()}),(o==null?void 0:o.inputs)!==void 0&&(u.inputs=Zg(o.inputs,"input")),await((d=this.onChainEnd)==null?void 0:d.call(this,u)),await this._endTrace(u),u}async handleChainError(e,t,n,a,o){var d;const u=this.runMap.get(t);if(!u)throw new Error("No chain run to end.");return u.end_time=Date.now(),u.error=this.stringifyError(e),u.events.push({name:"error",time:new Date(u.end_time).toISOString()}),(o==null?void 0:o.inputs)!==void 0&&(u.inputs=Zg(o.inputs,"input")),await((d=this.onChainError)==null?void 0:d.call(this,u)),await this._endTrace(u),u}_createRunForToolStart(e,t,n,a,o,u,d){const c=this._getExecutionOrder(a),h=Date.now(),_={id:n,name:d??e.id[e.id.length-1],parent_run_id:a,start_time:h,serialized:e,events:[{name:"start",time:new Date(h).toISOString()}],inputs:{input:t},execution_order:c,child_execution_order:c,run_type:"tool",child_runs:[],extra:u?{metadata:u}:{},tags:o||[]};return this._addRunToRunMap(_)}async handleToolStart(e,t,n,a,o,u,d){var h,_;const c=this.runMap.get(n)??this._createRunForToolStart(e,t,n,a,o,u,d);return await((h=this.onRunCreate)==null?void 0:h.call(this,c)),await((_=this.onToolStart)==null?void 0:_.call(this,c)),c}async handleToolEnd(e,t){var a;const n=this.runMap.get(t);if(!n||(n==null?void 0:n.run_type)!=="tool")throw new Error("No tool run to end");return n.end_time=Date.now(),n.outputs={output:e},n.events.push({name:"end",time:new Date(n.end_time).toISOString()}),await((a=this.onToolEnd)==null?void 0:a.call(this,n)),await this._endTrace(n),n}async handleToolError(e,t){var a;const n=this.runMap.get(t);if(!n||(n==null?void 0:n.run_type)!=="tool")throw new Error("No tool run to end");return n.end_time=Date.now(),n.error=this.stringifyError(e),n.events.push({name:"error",time:new Date(n.end_time).toISOString()}),await((a=this.onToolError)==null?void 0:a.call(this,n)),await this._endTrace(n),n}async handleAgentAction(e,t){var o;const n=this.runMap.get(t);if(!n||(n==null?void 0:n.run_type)!=="chain")return;const a=n;a.actions=a.actions||[],a.actions.push(e),a.events.push({name:"agent_action",time:new Date().toISOString(),kwargs:{action:e}}),await((o=this.onAgentAction)==null?void 0:o.call(this,n))}async handleAgentEnd(e,t){var a;const n=this.runMap.get(t);!n||(n==null?void 0:n.run_type)!=="chain"||(n.events.push({name:"agent_end",time:new Date().toISOString(),kwargs:{action:e}}),await((a=this.onAgentEnd)==null?void 0:a.call(this,n)))}_createRunForRetrieverStart(e,t,n,a,o,u,d){const c=this._getExecutionOrder(a),h=Date.now(),_={id:n,name:d??e.id[e.id.length-1],parent_run_id:a,start_time:h,serialized:e,events:[{name:"start",time:new Date(h).toISOString()}],inputs:{query:t},execution_order:c,child_execution_order:c,run_type:"retriever",child_runs:[],extra:u?{metadata:u}:{},tags:o||[]};return this._addRunToRunMap(_)}async handleRetrieverStart(e,t,n,a,o,u,d){var h,_;const c=this.runMap.get(n)??this._createRunForRetrieverStart(e,t,n,a,o,u,d);return await((h=this.onRunCreate)==null?void 0:h.call(this,c)),await((_=this.onRetrieverStart)==null?void 0:_.call(this,c)),c}async handleRetrieverEnd(e,t){var a;const n=this.runMap.get(t);if(!n||(n==null?void 0:n.run_type)!=="retriever")throw new Error("No retriever run to end");return n.end_time=Date.now(),n.outputs={documents:e},n.events.push({name:"end",time:new Date(n.end_time).toISOString()}),await((a=this.onRetrieverEnd)==null?void 0:a.call(this,n)),await this._endTrace(n),n}async handleRetrieverError(e,t){var a;const n=this.runMap.get(t);if(!n||(n==null?void 0:n.run_type)!=="retriever")throw new Error("No retriever run to end");return n.end_time=Date.now(),n.error=this.stringifyError(e),n.events.push({name:"error",time:new Date(n.end_time).toISOString()}),await((a=this.onRetrieverError)==null?void 0:a.call(this,n)),await this._endTrace(n),n}async handleText(e,t){var a;const n=this.runMap.get(t);!n||(n==null?void 0:n.run_type)!=="chain"||(n.events.push({name:"text",time:new Date().toISOString(),kwargs:{text:e}}),await((a=this.onText)==null?void 0:a.call(this,n)))}async handleLLMNewToken(e,t,n,a,o,u){var c;const d=this.runMap.get(n);if(!d||(d==null?void 0:d.run_type)!=="llm")throw new Error('Invalid "runId" provided to "handleLLMNewToken" callback.');return d.events.push({name:"new_token",time:new Date().toISOString(),kwargs:{token:e,idx:t,chunk:u==null?void 0:u.chunk}}),await((c=this.onLLMNewToken)==null?void 0:c.call(this,d,e,{chunk:u==null?void 0:u.chunk})),d}}var J0={exports:{}};J0.exports;(function(r){const t=(o=0)=>u=>`\x1B[${38+o};5;${u}m`,n=(o=0)=>(u,d,c)=>`\x1B[${38+o};2;${u};${d};${c}m`;function a(){const o=new Map,u={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};u.color.gray=u.color.blackBright,u.bgColor.bgGray=u.bgColor.bgBlackBright,u.color.grey=u.color.blackBright,u.bgColor.bgGrey=u.bgColor.bgBlackBright;for(const[d,c]of Object.entries(u)){for(const[h,_]of Object.entries(c))u[h]={open:`\x1B[${_[0]}m`,close:`\x1B[${_[1]}m`},c[h]=u[h],o.set(_[0],_[1]);Object.defineProperty(u,d,{value:c,enumerable:!1})}return Object.defineProperty(u,"codes",{value:o,enumerable:!1}),u.color.close="\x1B[39m",u.bgColor.close="\x1B[49m",u.color.ansi256=t(),u.color.ansi16m=n(),u.bgColor.ansi256=t(10),u.bgColor.ansi16m=n(10),Object.defineProperties(u,{rgbToAnsi256:{value:(d,c,h)=>d===c&&c===h?d<8?16:d>248?231:Math.round((d-8)/247*24)+232:16+36*Math.round(d/255*5)+6*Math.round(c/255*5)+Math.round(h/255*5),enumerable:!1},hexToRgb:{value:d=>{const c=/(?[a-f\d]{6}|[a-f\d]{3})/i.exec(d.toString(16));if(!c)return[0,0,0];let{colorString:h}=c.groups;h.length===3&&(h=h.split("").map(y=>y+y).join(""));const _=Number.parseInt(h,16);return[_>>16&255,_>>8&255,_&255]},enumerable:!1},hexToAnsi256:{value:d=>u.rgbToAnsi256(...u.hexToRgb(d)),enumerable:!1}}),u}Object.defineProperty(r,"exports",{enumerable:!0,get:a})})(J0);var dk=J0.exports,Pv=A_(dk);function Xn(r,e){return`${r.open}${e}${r.close}`}function $s(r,e){try{return JSON.stringify(r,null,2)}catch{return e}}function B1(r){return typeof r=="string"?r.trim():r==null?r:$s(r,r.toString())}function bi(r){if(!r.end_time)return"";const e=r.end_time-r.start_time;return e<1e3?`${e}ms`:`${(e/1e3).toFixed(2)}s`}const{color:cs}=Pv;class j1 extends Np{constructor(){super(...arguments),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"console_callback_handler"})}persistRun(e){return Promise.resolve()}getParents(e){const t=[];let n=e;for(;n.parent_run_id;){const a=this.runMap.get(n.parent_run_id);if(a)t.push(a),n=a;else break}return t}getBreadcrumbs(e){const n=[...this.getParents(e).reverse(),e].map((a,o,u)=>{const d=`${a.execution_order}:${a.run_type}:${a.name}`;return o===u.length-1?Xn(Pv.bold,d):d}).join(" > ");return Xn(cs.grey,n)}onChainStart(e){const t=this.getBreadcrumbs(e);console.log(`${Xn(cs.green,"[chain/start]")} [${t}] Entering Chain run with input: ${$s(e.inputs,"[inputs]")}`)}onChainEnd(e){const t=this.getBreadcrumbs(e);console.log(`${Xn(cs.cyan,"[chain/end]")} [${t}] [${bi(e)}] Exiting Chain run with output: ${$s(e.outputs,"[outputs]")}`)}onChainError(e){const t=this.getBreadcrumbs(e);console.log(`${Xn(cs.red,"[chain/error]")} [${t}] [${bi(e)}] Chain run errored with error: ${$s(e.error,"[error]")}`)}onLLMStart(e){const t=this.getBreadcrumbs(e),n="prompts"in e.inputs?{prompts:e.inputs.prompts.map(a=>a.trim())}:e.inputs;console.log(`${Xn(cs.green,"[llm/start]")} [${t}] Entering LLM run with input: ${$s(n,"[inputs]")}`)}onLLMEnd(e){const t=this.getBreadcrumbs(e);console.log(`${Xn(cs.cyan,"[llm/end]")} [${t}] [${bi(e)}] Exiting LLM run with output: ${$s(e.outputs,"[response]")}`)}onLLMError(e){const t=this.getBreadcrumbs(e);console.log(`${Xn(cs.red,"[llm/error]")} [${t}] [${bi(e)}] LLM run errored with error: ${$s(e.error,"[error]")}`)}onToolStart(e){const t=this.getBreadcrumbs(e);console.log(`${Xn(cs.green,"[tool/start]")} [${t}] Entering Tool run with input: "${B1(e.inputs.input)}"`)}onToolEnd(e){var n;const t=this.getBreadcrumbs(e);console.log(`${Xn(cs.cyan,"[tool/end]")} [${t}] [${bi(e)}] Exiting Tool run with output: "${B1((n=e.outputs)==null?void 0:n.output)}"`)}onToolError(e){const t=this.getBreadcrumbs(e);console.log(`${Xn(cs.red,"[tool/error]")} [${t}] [${bi(e)}] Tool run errored with error: ${$s(e.error,"[error]")}`)}onRetrieverStart(e){const t=this.getBreadcrumbs(e);console.log(`${Xn(cs.green,"[retriever/start]")} [${t}] Entering Retriever run with input: ${$s(e.inputs,"[inputs]")}`)}onRetrieverEnd(e){const t=this.getBreadcrumbs(e);console.log(`${Xn(cs.cyan,"[retriever/end]")} [${t}] [${bi(e)}] Exiting Retriever run with output: ${$s(e.outputs,"[outputs]")}`)}onRetrieverError(e){const t=this.getBreadcrumbs(e);console.log(`${Xn(cs.red,"[retriever/error]")} [${t}] [${bi(e)}] Retriever run errored with error: ${$s(e.error,"[error]")}`)}onAgentAction(e){const t=e,n=this.getBreadcrumbs(e);console.log(`${Xn(cs.blue,"[agent/action]")} [${n}] Agent selected action: ${$s(t.actions[t.actions.length-1],"[action]")}`)}}function hk(r){return!!(r&&typeof r=="object"&&"type"in r&&r.type==="tool_call")}class fk extends Error{constructor(e,t){super(e),Object.defineProperty(this,"output",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.output=t}}function pk(r){if(typeof r>"u")return null;try{return JSON.parse(r)}catch{}let e="";const t=[];let n=!1,a=!1;for(let o of r){if(n)o==='"'&&!a?n=!1:o===` `&&!a?o="\\n":o==="\\"?a=!a:a=!1;else if(o==='"')n=!0,a=!1;else if(o==="{")t.push("}");else if(o==="[")t.push("]");else if(o==="}"||o==="]")if(t&&t[t.length-1]===o)t.pop();else return null;e+=o}n&&(e+='"');for(let o=t.length-1;o>=0;o-=1)e+=t[o];try{return JSON.parse(e)}catch{return null}}function mk(r,e){return typeof r=="string"?typeof e=="string"?r+e:[{type:"text",text:r},...e]:Array.isArray(e)?eb(r,e)??[...r,...e]:[...r,{type:"text",text:e}]}function _k(r,e){function t(n,a){if(typeof n!="object"||n===null||n===void 0)return n;if(a>=e)return Array.isArray(n)?"[Array]":"[Object]";if(Array.isArray(n))return n.map(u=>t(u,a+1));const o={};for(const u of Object.keys(n))o[u]=t(n[u],a+1);return o}return JSON.stringify(t(r,0),null,2)}class gk extends Nl{get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}get text(){return typeof this.content=="string"?this.content:""}getType(){return this._getType()}constructor(e,t){typeof e=="string"&&(e={content:e,additional_kwargs:t,response_metadata:{}}),e.additional_kwargs||(e.additional_kwargs={}),e.response_metadata||(e.response_metadata={}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","messages"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"content",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"additional_kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"response_metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=e.name,this.content=e.content,this.additional_kwargs=e.additional_kwargs,this.response_metadata=e.response_metadata,this.id=e.id}toDict(){return{type:this._getType(),data:this.toJSON().kwargs}}static lc_name(){return"BaseMessage"}get _printableFields(){return{id:this.id,content:this.content,name:this.name,additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata}}_updateId(e){this.id=e,this.lc_kwargs.id=e}get[Symbol.toStringTag](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](e){if(e===null)return this;const t=_k(this._printableFields,Math.max(4,e));return`${this.constructor.lc_name()} ${t}`}}function y_(r,e){const t={...r};for(const[n,a]of Object.entries(e))if(t[n]==null)t[n]=a;else{if(a==null)continue;if(typeof t[n]!=typeof a||Array.isArray(t[n])!==Array.isArray(a))throw new Error(`field[${n}] already exists in the message chunk, but with a different type.`);if(typeof t[n]=="string"){if(n==="type")continue;t[n]+=a}else if(typeof t[n]=="object"&&!Array.isArray(t[n]))t[n]=y_(t[n],a);else if(Array.isArray(t[n]))t[n]=eb(t[n],a);else{if(t[n]===a)continue;console.warn(`field[${n}] already exists in this message chunk and value has unsupported type.`)}}return t}function eb(r,e){if(!(r===void 0&&e===void 0)){if(r===void 0||e===void 0)return r||e;{const t=[...r];for(const n of e)if(typeof n=="object"&&"index"in n&&typeof n.index=="number"){const a=t.findIndex(o=>o.index===n.index);a!==-1?t[a]=y_(t[a],n):t.push(n)}else{if(typeof n=="object"&&"text"in n&&n.text==="")continue;t.push(n)}return t}}}class bk extends gk{}class B_ extends bk{constructor(e){let t;if(typeof e=="string")t={content:e,tool_calls:[],invalid_tool_calls:[],tool_call_chunks:[]};else if(e.tool_call_chunks===void 0)t={...e,tool_calls:e.tool_calls??[],invalid_tool_calls:[],tool_call_chunks:[],usage_metadata:e.usage_metadata!==void 0?e.usage_metadata:void 0};else{const n=[],a=[];for(const o of e.tool_call_chunks){let u={};try{if(u=pk(o.args||"{}"),u===null||typeof u!="object"||Array.isArray(u))throw new Error("Malformed tool call chunk args.");n.push({name:o.name??"",args:u,id:o.id,type:"tool_call"})}catch{a.push({name:o.name,args:o.args,id:o.id,error:"Malformed args.",type:"invalid_tool_call"})}}t={...e,tool_calls:n,invalid_tool_calls:a,usage_metadata:e.usage_metadata!==void 0?e.usage_metadata:void 0}}super(t),Object.defineProperty(this,"tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"invalid_tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"tool_call_chunks",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"usage_metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.tool_call_chunks=t.tool_call_chunks??this.tool_call_chunks,this.tool_calls=t.tool_calls??this.tool_calls,this.invalid_tool_calls=t.invalid_tool_calls??this.invalid_tool_calls,this.usage_metadata=t.usage_metadata}get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls",tool_call_chunks:"tool_call_chunks"}}static lc_name(){return"AIMessageChunk"}_getType(){return"ai"}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,tool_call_chunks:this.tool_call_chunks,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}concat(e){var n,a,o,u,d,c,h,_,y,w,M,S,G,H,B,z,U,F,I,k,$,j,ce,ue,Pe,Te,ie,oe,re,ge,ve,me,Le,$e,pe,X,le,ke,Re,Xe;const t={content:mk(this.content,e.content),additional_kwargs:y_(this.additional_kwargs,e.additional_kwargs),response_metadata:y_(this.response_metadata,e.response_metadata),tool_call_chunks:[],id:this.id??e.id};if(this.tool_call_chunks!==void 0||e.tool_call_chunks!==void 0){const ae=eb(this.tool_call_chunks,e.tool_call_chunks);ae!==void 0&&ae.length>0&&(t.tool_call_chunks=ae)}if(this.usage_metadata!==void 0||e.usage_metadata!==void 0){const ae={...(((a=(n=this.usage_metadata)==null?void 0:n.input_token_details)==null?void 0:a.audio)!==void 0||((u=(o=e.usage_metadata)==null?void 0:o.input_token_details)==null?void 0:u.audio)!==void 0)&&{audio:(((c=(d=this.usage_metadata)==null?void 0:d.input_token_details)==null?void 0:c.audio)??0)+(((_=(h=e.usage_metadata)==null?void 0:h.input_token_details)==null?void 0:_.audio)??0)},...(((w=(y=this.usage_metadata)==null?void 0:y.input_token_details)==null?void 0:w.cache_read)!==void 0||((S=(M=e.usage_metadata)==null?void 0:M.input_token_details)==null?void 0:S.cache_read)!==void 0)&&{cache_read:(((H=(G=this.usage_metadata)==null?void 0:G.input_token_details)==null?void 0:H.cache_read)??0)+(((z=(B=e.usage_metadata)==null?void 0:B.input_token_details)==null?void 0:z.cache_read)??0)},...(((F=(U=this.usage_metadata)==null?void 0:U.input_token_details)==null?void 0:F.cache_creation)!==void 0||((k=(I=e.usage_metadata)==null?void 0:I.input_token_details)==null?void 0:k.cache_creation)!==void 0)&&{cache_creation:(((j=($=this.usage_metadata)==null?void 0:$.input_token_details)==null?void 0:j.cache_creation)??0)+(((ue=(ce=e.usage_metadata)==null?void 0:ce.input_token_details)==null?void 0:ue.cache_creation)??0)}},He={...(((Te=(Pe=this.usage_metadata)==null?void 0:Pe.output_token_details)==null?void 0:Te.audio)!==void 0||((oe=(ie=e.usage_metadata)==null?void 0:ie.output_token_details)==null?void 0:oe.audio)!==void 0)&&{audio:(((ge=(re=this.usage_metadata)==null?void 0:re.output_token_details)==null?void 0:ge.audio)??0)+(((me=(ve=e.usage_metadata)==null?void 0:ve.output_token_details)==null?void 0:me.audio)??0)},...((($e=(Le=this.usage_metadata)==null?void 0:Le.output_token_details)==null?void 0:$e.reasoning)!==void 0||((X=(pe=e.usage_metadata)==null?void 0:pe.output_token_details)==null?void 0:X.reasoning)!==void 0)&&{reasoning:(((ke=(le=this.usage_metadata)==null?void 0:le.output_token_details)==null?void 0:ke.reasoning)??0)+(((Xe=(Re=e.usage_metadata)==null?void 0:Re.output_token_details)==null?void 0:Xe.reasoning)??0)}},Ve=this.usage_metadata??{input_tokens:0,output_tokens:0,total_tokens:0},he=e.usage_metadata??{input_tokens:0,output_tokens:0,total_tokens:0},Se={input_tokens:Ve.input_tokens+he.input_tokens,output_tokens:Ve.output_tokens+he.output_tokens,total_tokens:Ve.total_tokens+he.total_tokens,...Object.keys(ae).length>0&&{input_token_details:ae},...Object.keys(He).length>0&&{output_token_details:He}};t.usage_metadata=Se}return new B_(t)}}function yk(r,e="Human",t="AI"){const n=[];for(const a of r){let o;if(a._getType()==="human")o=e;else if(a._getType()==="ai")o=t;else if(a._getType()==="system")o="System";else if(a._getType()==="function")o="Function";else if(a._getType()==="tool")o="Tool";else if(a._getType()==="generic")o=a.role;else throw new Error(`Got unsupported message type: ${a._getType()}`);const u=a.name?`${a.name}, `:"",d=typeof a.content=="string"?a.content:JSON.stringify(a.content,null,2);n.push(`${o}: ${u}${d}`)}return n.join(` `)}let Yg;const wk=()=>{if(Yg===void 0){const r=xi("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"?{blockOnRootRunFinalization:!0}:{};Yg=new Sp(r)}return Yg};class up extends Np{constructor(e={}){super(e),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"langchain_tracer"}),Object.defineProperty(this,"projectName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"exampleId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0});const{exampleId:t,projectName:n,client:a}=e;this.projectName=n??xi("LANGCHAIN_PROJECT")??xi("LANGCHAIN_SESSION"),this.exampleId=t,this.client=a??wk();const o=up.getTraceableRunTree();o&&this.updateFromRunTree(o)}async _convertToCreate(e,t=void 0){return{...e,extra:{...e.extra,runtime:await ik()},child_runs:void 0,session_name:this.projectName,reference_example_id:e.parent_run_id?void 0:t}}async persistRun(e){}async onRunCreate(e){const t=await this._convertToCreate(e,this.exampleId);await this.client.createRun(t)}async onRunUpdate(e){const t={end_time:e.end_time,error:e.error,outputs:e.outputs,events:e.events,inputs:e.inputs,trace_id:e.trace_id,dotted_order:e.dotted_order,parent_run_id:e.parent_run_id};await this.client.updateRun(e.id,t)}getRun(e){return this.runMap.get(e)}updateFromRunTree(e){let t=e;const n=new Set;for(;t.parent_run&&!(n.has(t.id)||(n.add(t.id),!t.parent_run));)t=t.parent_run;n.clear();const a=[t];for(;a.length>0;){const o=a.shift();!o||n.has(o.id)||(n.add(o.id),this.runMap.set(o.id,o),o.child_runs&&a.push(...o.child_runs))}this.client=e.client??this.client,this.projectName=e.project_name??this.projectName,this.exampleId=e.reference_example_id??this.exampleId}convertToRunTree(e){const t={},n=[];for(const[a,o]of this.runMap){const u=new ys({...o,child_runs:[],parent_run:void 0,client:this.client,project_name:this.projectName,reference_example_id:this.exampleId,tracingEnabled:!0});t[a]=u,n.push([a,o.dotted_order])}n.sort((a,o)=>!a[1]||!o[1]?0:a[1].localeCompare(o[1]));for(const[a]of n){const o=this.runMap.get(a),u=t[a];if(!(!o||!u)&&o.parent_run_id){const d=t[o.parent_run_id];d&&(d.child_runs.push(u),u.parent_run=d)}}return t[e]}static getTraceableRunTree(){try{return N3()}catch{return}}}const Cv=Symbol.for("ls:tracing_async_local_storage"),Ym=Symbol.for("lc:context_variables"),vk=r=>{globalThis[Cv]=r},Ap=()=>globalThis[Cv];let lp;function Ek(){const r="default"in Va?Va.default:Va;return new r({autoStart:!0,concurrency:1})}function Tk(){return typeof lp>"u"&&(lp=Ek()),lp}async function In(r,e){if(e===!0){const t=Ap();t!==void 0?await t.run(void 0,async()=>r()):await r()}else lp=Tk(),lp.add(async()=>{const t=Ap();t!==void 0?await t.run(void 0,async()=>r()):await r()})}const xk=r=>!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(t=>xi(t)==="true");function Sv(r){var n;const e=Ap();if(e===void 0)return;const t=e.getStore();return(n=t==null?void 0:t[Ym])==null?void 0:n[r]}const Mk=Symbol("lc:configure_hooks"),Pk=()=>Sv(Mk)||[];class Ck{setHandler(e){return this.setHandlers([e])}}class j_{constructor(e,t,n,a,o,u,d,c){Object.defineProperty(this,"runId",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"handlers",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"inheritableHandlers",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:a}),Object.defineProperty(this,"inheritableTags",{enumerable:!0,configurable:!0,writable:!0,value:o}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:u}),Object.defineProperty(this,"inheritableMetadata",{enumerable:!0,configurable:!0,writable:!0,value:d}),Object.defineProperty(this,"_parentRunId",{enumerable:!0,configurable:!0,writable:!0,value:c})}get parentRunId(){return this._parentRunId}async handleText(e){await Promise.all(this.handlers.map(t=>In(async()=>{var n;try{await((n=t.handleText)==null?void 0:n.call(t,e,this.runId,this._parentRunId,this.tags))}catch(a){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleText: ${a}`),t.raiseError)throw a}},t.awaitHandlers)))}async handleCustomEvent(e,t,n,a,o){await Promise.all(this.handlers.map(u=>In(async()=>{var d;try{await((d=u.handleCustomEvent)==null?void 0:d.call(u,e,t,this.runId,this.tags,this.metadata))}catch(c){if((u.raiseError?console.error:console.warn)(`Error in handler ${u.constructor.name}, handleCustomEvent: ${c}`),u.raiseError)throw c}},u.awaitHandlers)))}}class Sk extends j_{getChild(e){const t=new Ys(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleRetrieverEnd(e){await Promise.all(this.handlers.map(t=>In(async()=>{var n;if(!t.ignoreRetriever)try{await((n=t.handleRetrieverEnd)==null?void 0:n.call(t,e,this.runId,this._parentRunId,this.tags))}catch(a){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleRetriever`),t.raiseError)throw a}},t.awaitHandlers)))}async handleRetrieverError(e){await Promise.all(this.handlers.map(t=>In(async()=>{var n;if(!t.ignoreRetriever)try{await((n=t.handleRetrieverError)==null?void 0:n.call(t,e,this.runId,this._parentRunId,this.tags))}catch(a){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleRetrieverError: ${a}`),t.raiseError)throw e}},t.awaitHandlers)))}}class z1 extends j_{async handleLLMNewToken(e,t,n,a,o,u){await Promise.all(this.handlers.map(d=>In(async()=>{var c;if(!d.ignoreLLM)try{await((c=d.handleLLMNewToken)==null?void 0:c.call(d,e,t??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,u))}catch(h){if((d.raiseError?console.error:console.warn)(`Error in handler ${d.constructor.name}, handleLLMNewToken: ${h}`),d.raiseError)throw h}},d.awaitHandlers)))}async handleLLMError(e){await Promise.all(this.handlers.map(t=>In(async()=>{var n;if(!t.ignoreLLM)try{await((n=t.handleLLMError)==null?void 0:n.call(t,e,this.runId,this._parentRunId,this.tags))}catch(a){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleLLMError: ${a}`),t.raiseError)throw a}},t.awaitHandlers)))}async handleLLMEnd(e){await Promise.all(this.handlers.map(t=>In(async()=>{var n;if(!t.ignoreLLM)try{await((n=t.handleLLMEnd)==null?void 0:n.call(t,e,this.runId,this._parentRunId,this.tags))}catch(a){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleLLMEnd: ${a}`),t.raiseError)throw a}},t.awaitHandlers)))}}class Ak extends j_{getChild(e){const t=new Ys(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleChainError(e,t,n,a,o){await Promise.all(this.handlers.map(u=>In(async()=>{var d;if(!u.ignoreChain)try{await((d=u.handleChainError)==null?void 0:d.call(u,e,this.runId,this._parentRunId,this.tags,o))}catch(c){if((u.raiseError?console.error:console.warn)(`Error in handler ${u.constructor.name}, handleChainError: ${c}`),u.raiseError)throw c}},u.awaitHandlers)))}async handleChainEnd(e,t,n,a,o){await Promise.all(this.handlers.map(u=>In(async()=>{var d;if(!u.ignoreChain)try{await((d=u.handleChainEnd)==null?void 0:d.call(u,e,this.runId,this._parentRunId,this.tags,o))}catch(c){if((u.raiseError?console.error:console.warn)(`Error in handler ${u.constructor.name}, handleChainEnd: ${c}`),u.raiseError)throw c}},u.awaitHandlers)))}async handleAgentAction(e){await Promise.all(this.handlers.map(t=>In(async()=>{var n;if(!t.ignoreAgent)try{await((n=t.handleAgentAction)==null?void 0:n.call(t,e,this.runId,this._parentRunId,this.tags))}catch(a){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleAgentAction: ${a}`),t.raiseError)throw a}},t.awaitHandlers)))}async handleAgentEnd(e){await Promise.all(this.handlers.map(t=>In(async()=>{var n;if(!t.ignoreAgent)try{await((n=t.handleAgentEnd)==null?void 0:n.call(t,e,this.runId,this._parentRunId,this.tags))}catch(a){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleAgentEnd: ${a}`),t.raiseError)throw a}},t.awaitHandlers)))}}class kk extends j_{getChild(e){const t=new Ys(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleToolError(e){await Promise.all(this.handlers.map(t=>In(async()=>{var n;if(!t.ignoreAgent)try{await((n=t.handleToolError)==null?void 0:n.call(t,e,this.runId,this._parentRunId,this.tags))}catch(a){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleToolError: ${a}`),t.raiseError)throw a}},t.awaitHandlers)))}async handleToolEnd(e){await Promise.all(this.handlers.map(t=>In(async()=>{var n;if(!t.ignoreAgent)try{await((n=t.handleToolEnd)==null?void 0:n.call(t,e,this.runId,this._parentRunId,this.tags))}catch(a){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleToolEnd: ${a}`),t.raiseError)throw a}},t.awaitHandlers)))}}class Ys extends Ck{constructor(e,t){super(),Object.defineProperty(this,"handlers",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"inheritableHandlers",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"inheritableTags",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"inheritableMetadata",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"callback_manager"}),Object.defineProperty(this,"_parentRunId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.handlers=(t==null?void 0:t.handlers)??this.handlers,this.inheritableHandlers=(t==null?void 0:t.inheritableHandlers)??this.inheritableHandlers,this.tags=(t==null?void 0:t.tags)??this.tags,this.inheritableTags=(t==null?void 0:t.inheritableTags)??this.inheritableTags,this.metadata=(t==null?void 0:t.metadata)??this.metadata,this.inheritableMetadata=(t==null?void 0:t.inheritableMetadata)??this.inheritableMetadata,this._parentRunId=e}getParentRunId(){return this._parentRunId}async handleLLMStart(e,t,n=void 0,a=void 0,o=void 0,u=void 0,d=void 0,c=void 0){return Promise.all(t.map(async(h,_)=>{const y=_===0&&n?n:hs();return await Promise.all(this.handlers.map(w=>{if(!w.ignoreLLM)return Jf(w)&&w._createRunForLLMStart(e,[h],y,this._parentRunId,o,this.tags,this.metadata,c),In(async()=>{var M;try{await((M=w.handleLLMStart)==null?void 0:M.call(w,e,[h],y,this._parentRunId,o,this.tags,this.metadata,c))}catch(S){if((w.raiseError?console.error:console.warn)(`Error in handler ${w.constructor.name}, handleLLMStart: ${S}`),w.raiseError)throw S}},w.awaitHandlers)})),new z1(y,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart(e,t,n=void 0,a=void 0,o=void 0,u=void 0,d=void 0,c=void 0){return Promise.all(t.map(async(h,_)=>{const y=_===0&&n?n:hs();return await Promise.all(this.handlers.map(w=>{if(!w.ignoreLLM)return Jf(w)&&w._createRunForChatModelStart(e,[h],y,this._parentRunId,o,this.tags,this.metadata,c),In(async()=>{var M,S;try{if(w.handleChatModelStart)await((M=w.handleChatModelStart)==null?void 0:M.call(w,e,[h],y,this._parentRunId,o,this.tags,this.metadata,c));else if(w.handleLLMStart){const G=yk(h);await((S=w.handleLLMStart)==null?void 0:S.call(w,e,[G],y,this._parentRunId,o,this.tags,this.metadata,c))}}catch(G){if((w.raiseError?console.error:console.warn)(`Error in handler ${w.constructor.name}, handleLLMStart: ${G}`),w.raiseError)throw G}},w.awaitHandlers)})),new z1(y,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(e,t,n=hs(),a=void 0,o=void 0,u=void 0,d=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreChain)return Jf(c)&&c._createRunForChainStart(e,t,n,this._parentRunId,this.tags,this.metadata,a,d),In(async()=>{var h;try{await((h=c.handleChainStart)==null?void 0:h.call(c,e,t,n,this._parentRunId,this.tags,this.metadata,a,d))}catch(_){if((c.raiseError?console.error:console.warn)(`Error in handler ${c.constructor.name}, handleChainStart: ${_}`),c.raiseError)throw _}},c.awaitHandlers)})),new Ak(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(e,t,n=hs(),a=void 0,o=void 0,u=void 0,d=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreAgent)return Jf(c)&&c._createRunForToolStart(e,t,n,this._parentRunId,this.tags,this.metadata,d),In(async()=>{var h;try{await((h=c.handleToolStart)==null?void 0:h.call(c,e,t,n,this._parentRunId,this.tags,this.metadata,d))}catch(_){if((c.raiseError?console.error:console.warn)(`Error in handler ${c.constructor.name}, handleToolStart: ${_}`),c.raiseError)throw _}},c.awaitHandlers)})),new kk(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(e,t,n=hs(),a=void 0,o=void 0,u=void 0,d=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreRetriever)return Jf(c)&&c._createRunForRetrieverStart(e,t,n,this._parentRunId,this.tags,this.metadata,d),In(async()=>{var h;try{await((h=c.handleRetrieverStart)==null?void 0:h.call(c,e,t,n,this._parentRunId,this.tags,this.metadata,d))}catch(_){if((c.raiseError?console.error:console.warn)(`Error in handler ${c.constructor.name}, handleRetrieverStart: ${_}`),c.raiseError)throw _}},c.awaitHandlers)})),new Sk(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(e,t,n,a,o){await Promise.all(this.handlers.map(u=>In(async()=>{var d;if(!u.ignoreCustomEvent)try{await((d=u.handleCustomEvent)==null?void 0:d.call(u,e,t,n,this.tags,this.metadata))}catch(c){if((u.raiseError?console.error:console.warn)(`Error in handler ${u.constructor.name}, handleCustomEvent: ${c}`),u.raiseError)throw c}},u.awaitHandlers)))}addHandler(e,t=!0){this.handlers.push(e),t&&this.inheritableHandlers.push(e)}removeHandler(e){this.handlers=this.handlers.filter(t=>t!==e),this.inheritableHandlers=this.inheritableHandlers.filter(t=>t!==e)}setHandlers(e,t=!0){this.handlers=[],this.inheritableHandlers=[];for(const n of e)this.addHandler(n,t)}addTags(e,t=!0){this.removeTags(e),this.tags.push(...e),t&&this.inheritableTags.push(...e)}removeTags(e){this.tags=this.tags.filter(t=>!e.includes(t)),this.inheritableTags=this.inheritableTags.filter(t=>!e.includes(t))}addMetadata(e,t=!0){this.metadata={...this.metadata,...e},t&&(this.inheritableMetadata={...this.inheritableMetadata,...e})}removeMetadata(e){for(const t of Object.keys(e))delete this.metadata[t],delete this.inheritableMetadata[t]}copy(e=[],t=!0){const n=new Ys(this._parentRunId);for(const a of this.handlers){const o=this.inheritableHandlers.includes(a);n.addHandler(a,o)}for(const a of this.tags){const o=this.inheritableTags.includes(a);n.addTags([a],o)}for(const a of Object.keys(this.metadata)){const o=Object.keys(this.inheritableMetadata).includes(a);n.addMetadata({[a]:this.metadata[a]},o)}for(const a of e)n.handlers.filter(o=>o.name==="console_callback_handler").some(o=>o.name===a.name)||n.addHandler(a,t);return n}static fromHandlers(e){class t extends Fp{constructor(){super(),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:hs()}),Object.assign(this,e)}}const n=new this;return n.addHandler(new t),n}static configure(e,t,n,a,o,u,d){return this._configureSync(e,t,n,a,o,u,d)}static _configureSync(e,t,n,a,o,u,d){var w,M;let c;(e||t)&&(Array.isArray(e)||!e?(c=new Ys,c.setHandlers((e==null?void 0:e.map(w_))??[],!0)):c=e,c=c.copy(Array.isArray(t)?t.map(w_):t==null?void 0:t.handlers,!1));const h=xi("LANGCHAIN_VERBOSE")==="true"||(d==null?void 0:d.verbose),_=((w=up.getTraceableRunTree())==null?void 0:w.tracingEnabled)||xk(),y=_||(xi("LANGCHAIN_TRACING")??!1);if(h||y){if(c||(c=new Ys),h&&!c.handlers.some(S=>S.name===j1.prototype.name)){const S=new j1;c.addHandler(S,!0)}if(y&&!c.handlers.some(S=>S.name==="langchain_tracer")&&_){const S=new up;c.addHandler(S,!0),c._parentRunId=((M=up.getTraceableRunTree())==null?void 0:M.id)??c._parentRunId}}for(const{contextVar:S,inheritable:G=!0,handlerClass:H,envVar:B}of Pk()){const z=B&&xi(B)==="true"&&H;let U;const F=S!==void 0?Sv(S):void 0;F&&uk(F)?U=F:z&&(U=new H({})),U!==void 0&&(c||(c=new Ys),c.handlers.some(I=>I.name===U.name)||c.addHandler(U,G))}return(n||a)&&c&&(c.addTags(n??[]),c.addTags(a??[],!1)),(o||u)&&c&&(c.addMetadata(o??{}),c.addMetadata(u??{},!1)),c}}function w_(r){return"name"in r?r:Fp.fromMethods(r)}class Ik{getStore(){}run(e,t){return t()}enterWith(e){}}const $k=new Ik,U1=Symbol.for("lc:child_config");class Ok{getInstance(){return Ap()??$k}getRunnableConfig(){var t,n;return(n=(t=this.getInstance().getStore())==null?void 0:t.extra)==null?void 0:n[U1]}runWithConfig(e,t,n){var _;const a=Ys._configureSync(e==null?void 0:e.callbacks,void 0,e==null?void 0:e.tags,void 0,e==null?void 0:e.metadata),o=this.getInstance(),u=o.getStore(),d=a==null?void 0:a.getParentRunId(),c=(_=a==null?void 0:a.handlers)==null?void 0:_.find(y=>(y==null?void 0:y.name)==="langchain_tracer");let h;return c&&d?h=c.convertToRunTree(d):n||(h=new ys({name:"",tracingEnabled:!1})),h&&(h.extra={...h.extra,[U1]:e}),u!==void 0&&u[Ym]!==void 0&&(h[Ym]=u[Ym]),o.run(h,t)}initializeGlobalInstance(e){Ap()===void 0&&vk(e)}}const Ai=new Ok,Xg=25;async function Js(r){return Ys._configureSync(r==null?void 0:r.callbacks,void 0,r==null?void 0:r.tags,void 0,r==null?void 0:r.metadata)}function V1(...r){const e={};for(const t of r.filter(n=>!!n))for(const n of Object.keys(t))if(n==="metadata")e[n]={...e[n],...t[n]};else if(n==="tags"){const a=e[n]??[];e[n]=[...new Set(a.concat(t[n]??[]))]}else if(n==="configurable")e[n]={...e[n],...t[n]};else if(n==="timeout")e.timeout===void 0?e.timeout=t.timeout:t.timeout!==void 0&&(e.timeout=Math.min(e.timeout,t.timeout));else if(n==="signal")e.signal===void 0?e.signal=t.signal:t.signal!==void 0&&("any"in AbortSignal?e.signal=AbortSignal.any([e.signal,t.signal]):e.signal=t.signal);else if(n==="callbacks"){const a=e.callbacks,o=t.callbacks;if(Array.isArray(o))if(!a)e.callbacks=o;else if(Array.isArray(a))e.callbacks=a.concat(o);else{const u=a.copy();for(const d of o)u.addHandler(w_(d),!0);e.callbacks=u}else if(o)if(!a)e.callbacks=o;else if(Array.isArray(a)){const u=o.copy();for(const d of a)u.addHandler(w_(d),!0);e.callbacks=u}else e.callbacks=new Ys(o._parentRunId,{handlers:a.handlers.concat(o.handlers),inheritableHandlers:a.inheritableHandlers.concat(o.inheritableHandlers),tags:Array.from(new Set(a.tags.concat(o.tags))),inheritableTags:Array.from(new Set(a.inheritableTags.concat(o.inheritableTags))),metadata:{...a.metadata,...o.metadata}})}else{const a=n;e[a]=t[a]??e[a]}return e}const Lk=new Set(["string","number","boolean"]);function qr(r){var n;const e=Ai.getRunnableConfig();let t={tags:[],metadata:{},recursionLimit:25,runId:void 0};if(e){const{runId:a,runName:o,...u}=e;t=Object.entries(u).reduce((d,[c,h])=>(h!==void 0&&(d[c]=h),d),t)}if(r&&(t=Object.entries(r).reduce((a,[o,u])=>(u!==void 0&&(a[o]=u),a),t)),t!=null&&t.configurable)for(const a of Object.keys(t.configurable))Lk.has(typeof t.configurable[a])&&!((n=t.metadata)!=null&&n[a])&&(t.metadata||(t.metadata={}),t.metadata[a]=t.configurable[a]);if(t.timeout!==void 0){if(t.timeout<=0)throw new Error("Timeout must be a positive number");const a=AbortSignal.timeout(t.timeout);t.signal!==void 0?"any"in AbortSignal&&(t.signal=AbortSignal.any([t.signal,a])):t.signal=a,delete t.timeout}return t}function Gn(r={},{callbacks:e,maxConcurrency:t,recursionLimit:n,runName:a,configurable:o,runId:u}={}){const d=qr(r);return e!==void 0&&(delete d.runName,d.callbacks=e),n!==void 0&&(d.recursionLimit=n),t!==void 0&&(d.maxConcurrency=t),a!==void 0&&(d.runName=a),o!==void 0&&(d.configurable={...d.configurable,...o}),u!==void 0&&delete d.runId,d}function Dl(r){return r?{configurable:r.configurable,recursionLimit:r.recursionLimit,callbacks:r.callbacks,tags:r.tags,metadata:r.metadata,maxConcurrency:r.maxConcurrency,timeout:r.timeout,signal:r.signal}:void 0}async function ki(r,e){if(e===void 0)return r;let t;return Promise.race([r.catch(n=>{if(!(e!=null&&e.aborted))throw n}),new Promise((n,a)=>{t=()=>{a(new Error("Aborted"))},e.addEventListener("abort",t),e.aborted&&a(new Error("Aborted"))})]).finally(()=>e.removeEventListener("abort",t))}class vs extends ReadableStream{constructor(){super(...arguments),Object.defineProperty(this,"reader",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}ensureReader(){this.reader||(this.reader=this.getReader())}async next(){this.ensureReader();try{const e=await this.reader.read();return e.done?(this.reader.releaseLock(),{done:!0,value:void 0}):{done:!1,value:e.value}}catch(e){throw this.reader.releaseLock(),e}}async return(){if(this.ensureReader(),this.locked){const e=this.reader.cancel();this.reader.releaseLock(),await e}return{done:!0,value:void 0}}async throw(e){if(this.ensureReader(),this.locked){const t=this.reader.cancel();this.reader.releaseLock(),await t}throw e}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}static fromReadableStream(e){const t=e.getReader();return new vs({start(n){return a();function a(){return t.read().then(({done:o,value:u})=>{if(o){n.close();return}return n.enqueue(u),a()})}},cancel(){t.releaseLock()}})}static fromAsyncGenerator(e){return new vs({async pull(t){const{value:n,done:a}=await e.next();a&&t.close(),t.enqueue(n)},async cancel(t){await e.return(t)}})}}function Av(r,e=2){const t=Array.from({length:e},()=>[]);return t.map(async function*(a){for(;;)if(a.length===0){const o=await r.next();for(const u of t)u.push(o)}else{if(a[0].done)return;yield a.shift().value}})}function Wa(r,e){if(Array.isArray(r)&&Array.isArray(e))return r.concat(e);if(typeof r=="string"&&typeof e=="string")return r+e;if(typeof r=="number"&&typeof e=="number")return r+e;if("concat"in r&&typeof r.concat=="function")return r.concat(e);if(typeof r=="object"&&typeof e=="object"){const t={...r};for(const[n,a]of Object.entries(e))n in t&&!Array.isArray(t[n])?t[n]=Wa(t[n],a):t[n]=a;return t}else throw new Error(`Cannot concat ${typeof r} and ${typeof e}`)}class Gl{constructor(e){var t;Object.defineProperty(this,"generator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"setup",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"signal",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"firstResult",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"firstResultUsed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this.generator=e.generator,this.config=e.config,this.signal=e.signal??((t=this.config)==null?void 0:t.signal),this.setup=new Promise((n,a)=>{Ai.runWithConfig(Dl(e.config),async()=>{this.firstResult=e.generator.next(),e.startSetup?this.firstResult.then(e.startSetup).then(n,a):this.firstResult.then(o=>n(void 0),a)},!0)})}async next(...e){var t;return(t=this.signal)==null||t.throwIfAborted(),this.firstResultUsed?Ai.runWithConfig(Dl(this.config),this.signal?async()=>ki(this.generator.next(...e),this.signal):async()=>this.generator.next(...e),!0):(this.firstResultUsed=!0,this.firstResult)}async return(e){return this.generator.return(e)}async throw(e){return this.generator.throw(e)}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}}async function Rk(r,e,t,n,...a){const o=new Gl({generator:e,startSetup:t,signal:n}),u=await o.setup;return{output:r(o,u,...a),setup:u}}class wi{constructor(e){Object.defineProperty(this,"ops",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.ops=e.ops??[]}concat(e){const t=this.ops.concat(e.ops),n=g_({},t);return new kp({ops:t,state:n[n.length-1].newDocument})}}class kp extends wi{constructor(e){super(e),Object.defineProperty(this,"state",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.state=e.state}concat(e){const t=this.ops.concat(e.ops),n=g_(this.state,e.ops);return new kp({ops:t,state:n[n.length-1].newDocument})}static fromRunLogPatch(e){const t=g_({},e.ops);return new kp({ops:e.ops,state:t[t.length-1].newDocument})}}const Fk=r=>r.name==="log_stream_tracer";async function W1(r,e){if(e==="original")throw new Error("Do not assign inputs with original schema drop the key for now. When inputs are added to streamLog they should be added with standardized schema for streaming events.");const{inputs:t}=r;if(["retriever","llm","prompt"].includes(r.run_type))return t;if(!(Object.keys(t).length===1&&(t==null?void 0:t.input)===""))return t.input}async function G1(r,e){const{outputs:t}=r;return e==="original"||["retriever","llm","prompt"].includes(r.run_type)?t:t!==void 0&&Object.keys(t).length===1&&(t==null?void 0:t.output)!==void 0?t.output:t}function Nk(r){return r!==void 0&&r.message!==void 0}class H1 extends Np{constructor(e){super({_awaitHandler:!0,...e}),Object.defineProperty(this,"autoClose",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"includeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_schemaFormat",{enumerable:!0,configurable:!0,writable:!0,value:"original"}),Object.defineProperty(this,"rootId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"keyMapByRunId",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"counterMapByRunName",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"transformStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"writer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"receiveStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"log_stream_tracer"}),Object.defineProperty(this,"lc_prefer_streaming",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this.autoClose=(e==null?void 0:e.autoClose)??!0,this.includeNames=e==null?void 0:e.includeNames,this.includeTypes=e==null?void 0:e.includeTypes,this.includeTags=e==null?void 0:e.includeTags,this.excludeNames=e==null?void 0:e.excludeNames,this.excludeTypes=e==null?void 0:e.excludeTypes,this.excludeTags=e==null?void 0:e.excludeTags,this._schemaFormat=(e==null?void 0:e._schemaFormat)??this._schemaFormat,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=vs.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){if(e.id===this.rootId)return!1;const t=e.tags??[];let n=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(n=n||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(n=n||this.includeTypes.includes(e.run_type)),this.includeTags!==void 0&&(n=n||t.find(a=>{var o;return(o=this.includeTags)==null?void 0:o.includes(a)})!==void 0),this.excludeNames!==void 0&&(n=n&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(n=n&&!this.excludeTypes.includes(e.run_type)),this.excludeTags!==void 0&&(n=n&&t.every(a=>{var o;return!((o=this.excludeTags)!=null&&o.includes(a))})),n}async*tapOutputIterable(e,t){for await(const n of t){if(e!==this.rootId){const a=this.keyMapByRunId[e];a&&await this.writer.write(new wi({ops:[{op:"add",path:`/logs/${a}/streamed_output/-`,value:n}]}))}yield n}}async onRunCreate(e){var a;if(this.rootId===void 0&&(this.rootId=e.id,await this.writer.write(new wi({ops:[{op:"replace",path:"",value:{id:e.id,name:e.name,type:e.run_type,streamed_output:[],final_output:void 0,logs:{}}}]}))),!this._includeRun(e))return;this.counterMapByRunName[e.name]===void 0&&(this.counterMapByRunName[e.name]=0),this.counterMapByRunName[e.name]+=1;const t=this.counterMapByRunName[e.name];this.keyMapByRunId[e.id]=t===1?e.name:`${e.name}:${t}`;const n={id:e.id,name:e.name,type:e.run_type,tags:e.tags??[],metadata:((a=e.extra)==null?void 0:a.metadata)??{},start_time:new Date(e.start_time).toISOString(),streamed_output:[],streamed_output_str:[],final_output:void 0,end_time:void 0};this._schemaFormat==="streaming_events"&&(n.inputs=await W1(e,this._schemaFormat)),await this.writer.write(new wi({ops:[{op:"add",path:`/logs/${this.keyMapByRunId[e.id]}`,value:n}]}))}async onRunUpdate(e){try{const t=this.keyMapByRunId[e.id];if(t===void 0)return;const n=[];this._schemaFormat==="streaming_events"&&n.push({op:"replace",path:`/logs/${t}/inputs`,value:await W1(e,this._schemaFormat)}),n.push({op:"add",path:`/logs/${t}/final_output`,value:await G1(e,this._schemaFormat)}),e.end_time!==void 0&&n.push({op:"add",path:`/logs/${t}/end_time`,value:new Date(e.end_time).toISOString()});const a=new wi({ops:n});await this.writer.write(a)}finally{if(e.id===this.rootId){const t=new wi({ops:[{op:"replace",path:"/final_output",value:await G1(e,this._schemaFormat)}]});await this.writer.write(t),this.autoClose&&await this.writer.close()}}}async onLLMNewToken(e,t,n){const a=this.keyMapByRunId[e.id];if(a===void 0)return;const o=e.inputs.messages!==void 0;let u;o?Nk(n==null?void 0:n.chunk)?u=n==null?void 0:n.chunk:u=new B_({id:`run-${e.id}`,content:t}):u=t;const d=new wi({ops:[{op:"add",path:`/logs/${a}/streamed_output_str/-`,value:t},{op:"add",path:`/logs/${a}/streamed_output/-`,value:u}]});await this.writer.write(d)}}class v_{constructor(e){Object.defineProperty(this,"text",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"generationInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.text=e.text,this.generationInfo=e.generationInfo}concat(e){return new v_({text:this.text+e.text,generationInfo:{...this.generationInfo,...e.generationInfo}})}}function Km({name:r,serialized:e}){return r!==void 0?r:(e==null?void 0:e.name)!==void 0?e.name:(e==null?void 0:e.id)!==void 0&&Array.isArray(e==null?void 0:e.id)?e.id[e.id.length-1]:"Unnamed"}const Dk=r=>r.name==="event_stream_tracer";class Bk extends Np{constructor(e){super({_awaitHandler:!0,...e}),Object.defineProperty(this,"autoClose",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"includeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"runInfoMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"tappedPromises",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"transformStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"writer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"receiveStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"event_stream_tracer"}),Object.defineProperty(this,"lc_prefer_streaming",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this.autoClose=(e==null?void 0:e.autoClose)??!0,this.includeNames=e==null?void 0:e.includeNames,this.includeTypes=e==null?void 0:e.includeTypes,this.includeTags=e==null?void 0:e.includeTags,this.excludeNames=e==null?void 0:e.excludeNames,this.excludeTypes=e==null?void 0:e.excludeTypes,this.excludeTags=e==null?void 0:e.excludeTags,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=vs.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){const t=e.tags??[];let n=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(n=n||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(n=n||this.includeTypes.includes(e.runType)),this.includeTags!==void 0&&(n=n||t.find(a=>{var o;return(o=this.includeTags)==null?void 0:o.includes(a)})!==void 0),this.excludeNames!==void 0&&(n=n&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(n=n&&!this.excludeTypes.includes(e.runType)),this.excludeTags!==void 0&&(n=n&&t.every(a=>{var o;return!((o=this.excludeTags)!=null&&o.includes(a))})),n}async*tapOutputIterable(e,t){const n=await t.next();if(n.done)return;const a=this.runInfoMap.get(e);if(a===void 0){yield n.value;return}function o(d,c){return d==="llm"&&typeof c=="string"?new v_({text:c}):c}let u=this.tappedPromises.get(e);if(u===void 0){let d;u=new Promise(c=>{d=c}),this.tappedPromises.set(e,u);try{const c={event:`on_${a.runType}_stream`,run_id:e,name:a.name,tags:a.tags,metadata:a.metadata,data:{}};await this.send({...c,data:{chunk:o(a.runType,n.value)}},a),yield n.value;for await(const h of t)a.runType!=="tool"&&a.runType!=="retriever"&&await this.send({...c,data:{chunk:o(a.runType,h)}},a),yield h}finally{d()}}else{yield n.value;for await(const d of t)yield d}}async send(e,t){this._includeRun(t)&&await this.writer.write(e)}async sendEndEvent(e,t){const n=this.tappedPromises.get(e.run_id);n!==void 0?n.then(()=>{this.send(e,t)}):await this.send(e,t)}async onLLMStart(e){var u,d;const t=Km(e),n=e.inputs.messages!==void 0?"chat_model":"llm",a={tags:e.tags??[],metadata:((u=e.extra)==null?void 0:u.metadata)??{},name:t,runType:n,inputs:e.inputs};this.runInfoMap.set(e.id,a);const o=`on_${n}_start`;await this.send({event:o,data:{input:e.inputs},name:t,tags:e.tags??[],run_id:e.id,metadata:((d=e.extra)==null?void 0:d.metadata)??{}},a)}async onLLMNewToken(e,t,n){const a=this.runInfoMap.get(e.id);let o,u;if(a===void 0)throw new Error(`onLLMNewToken: Run ID ${e.id} not found in run map.`);if(this.runInfoMap.size!==1){if(a.runType==="chat_model")u="on_chat_model_stream",(n==null?void 0:n.chunk)===void 0?o=new B_({content:t,id:`run-${e.id}`}):o=n.chunk.message;else if(a.runType==="llm")u="on_llm_stream",(n==null?void 0:n.chunk)===void 0?o=new v_({text:t}):o=n.chunk;else throw new Error(`Unexpected run type ${a.runType}`);await this.send({event:u,data:{chunk:o},run_id:e.id,name:a.name,tags:a.tags,metadata:a.metadata},a)}}async onLLMEnd(e){var u,d,c;const t=this.runInfoMap.get(e.id);this.runInfoMap.delete(e.id);let n;if(t===void 0)throw new Error(`onLLMEnd: Run ID ${e.id} not found in run map.`);const a=(u=e.outputs)==null?void 0:u.generations;let o;if(t.runType==="chat_model"){for(const h of a??[]){if(o!==void 0)break;o=(d=h[0])==null?void 0:d.message}n="on_chat_model_end"}else if(t.runType==="llm")o={generations:a==null?void 0:a.map(h=>h.map(_=>({text:_.text,generationInfo:_.generationInfo}))),llmOutput:((c=e.outputs)==null?void 0:c.llmOutput)??{}},n="on_llm_end";else throw new Error(`onLLMEnd: Unexpected run type: ${t.runType}`);await this.sendEndEvent({event:n,data:{output:o,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onChainStart(e){var u,d;const t=Km(e),n=e.run_type??"chain",a={tags:e.tags??[],metadata:((u=e.extra)==null?void 0:u.metadata)??{},name:t,runType:e.run_type};let o={};e.inputs.input===""&&Object.keys(e.inputs).length===1?(o={},a.inputs={}):e.inputs.input!==void 0?(o.input=e.inputs.input,a.inputs=e.inputs.input):(o.input=e.inputs,a.inputs=e.inputs),this.runInfoMap.set(e.id,a),await this.send({event:`on_${n}_start`,data:o,name:t,tags:e.tags??[],run_id:e.id,metadata:((d=e.extra)==null?void 0:d.metadata)??{}},a)}async onChainEnd(e){var d;const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw new Error(`onChainEnd: Run ID ${e.id} not found in run map.`);const n=`on_${e.run_type}_end`,a=e.inputs??t.inputs??{},u={output:((d=e.outputs)==null?void 0:d.output)??e.outputs,input:a};a.input&&Object.keys(a).length===1&&(u.input=a.input,t.inputs=a.input),await this.sendEndEvent({event:n,data:u,run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata??{}},t)}async onToolStart(e){var a,o;const t=Km(e),n={tags:e.tags??[],metadata:((a=e.extra)==null?void 0:a.metadata)??{},name:t,runType:"tool",inputs:e.inputs??{}};this.runInfoMap.set(e.id,n),await this.send({event:"on_tool_start",data:{input:e.inputs??{}},name:t,run_id:e.id,tags:e.tags??[],metadata:((o=e.extra)==null?void 0:o.metadata)??{}},n)}async onToolEnd(e){var a;const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw new Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(t.inputs===void 0)throw new Error(`onToolEnd: Run ID ${e.id} is a tool call, and is expected to have traced inputs.`);const n=((a=e.outputs)==null?void 0:a.output)===void 0?e.outputs:e.outputs.output;await this.sendEndEvent({event:"on_tool_end",data:{output:n,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onRetrieverStart(e){var o,u;const t=Km(e),a={tags:e.tags??[],metadata:((o=e.extra)==null?void 0:o.metadata)??{},name:t,runType:"retriever",inputs:{query:e.inputs.query}};this.runInfoMap.set(e.id,a),await this.send({event:"on_retriever_start",data:{input:{query:e.inputs.query}},name:t,tags:e.tags??[],run_id:e.id,metadata:((u=e.extra)==null?void 0:u.metadata)??{}},a)}async onRetrieverEnd(e){var n;const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw new Error(`onRetrieverEnd: Run ID ${e.id} not found in run map.`);await this.sendEndEvent({event:"on_retriever_end",data:{output:((n=e.outputs)==null?void 0:n.documents)??e.outputs,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async handleCustomEvent(e,t,n){const a=this.runInfoMap.get(n);if(a===void 0)throw new Error(`handleCustomEvent: Run ID ${n} not found in run map.`);await this.send({event:"on_custom_event",run_id:n,name:e,tags:a.tags,metadata:a.metadata,data:t},a)}async finish(){const e=[...this.tappedPromises.values()];Promise.all(e).finally(()=>{this.writer.close()})}}const jk=[400,401,402,403,404,405,406,407,409],zk=r=>{var t,n;if(r.message.startsWith("Cancel")||r.message.startsWith("AbortError")||r.name==="AbortError"||(r==null?void 0:r.code)==="ECONNABORTED")throw r;const e=((t=r==null?void 0:r.response)==null?void 0:t.status)??(r==null?void 0:r.status);if(e&&jk.includes(+e))throw r;if(((n=r==null?void 0:r.error)==null?void 0:n.code)==="insufficient_quota"){const a=new Error(r==null?void 0:r.message);throw a.name="InsufficientQuotaError",a}};class Uk{constructor(e){Object.defineProperty(this,"maxConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxRetries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onFailedAttempt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.onFailedAttempt=e.onFailedAttempt??zk;const t="default"in Va?Va.default:Va;this.queue=new t({concurrency:this.maxConcurrency})}call(e,...t){return this.queue.add(()=>p_(()=>e(...t).catch(n=>{throw n instanceof Error?n:new Error(n)}),{onFailedAttempt:this.onFailedAttempt,retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(e,t,...n){return e.signal?Promise.race([this.call(t,...n),new Promise((a,o)=>{var u;(u=e.signal)==null||u.addEventListener("abort",()=>{o(new Error("AbortError"))})})]):this.call(t,...n)}fetch(...e){return this.call(()=>fetch(...e).then(t=>t.ok?t:Promise.reject(t)))}}class kv extends Np{constructor({config:e,onStart:t,onEnd:n,onError:a}){super({_awaitHandler:!0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RootListenersTracer"}),Object.defineProperty(this,"rootId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"argOnStart",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"argOnEnd",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"argOnError",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.config=e,this.argOnStart=t,this.argOnEnd=n,this.argOnError=a}persistRun(e){return Promise.resolve()}async onRunCreate(e){this.rootId||(this.rootId=e.id,this.argOnStart&&await this.argOnStart(e,this.config))}async onRunUpdate(e){e.id===this.rootId&&(e.error?this.argOnError&&await this.argOnError(e,this.config):this.argOnEnd&&await this.argOnEnd(e,this.config))}}function tb(r){return r?r.lc_runnable:!1}class Vk{constructor(e){Object.defineProperty(this,"includeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.includeNames=e.includeNames,this.includeTypes=e.includeTypes,this.includeTags=e.includeTags,this.excludeNames=e.excludeNames,this.excludeTypes=e.excludeTypes,this.excludeTags=e.excludeTags}includeEvent(e,t){let n=this.includeNames===void 0&&this.includeTypes===void 0&&this.includeTags===void 0;const a=e.tags??[];return this.includeNames!==void 0&&(n=n||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(n=n||this.includeTypes.includes(t)),this.includeTags!==void 0&&(n=n||a.some(o=>{var u;return(u=this.includeTags)==null?void 0:u.includes(o)})),this.excludeNames!==void 0&&(n=n&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(n=n&&!this.excludeTypes.includes(t)),this.excludeTags!==void 0&&(n=n&&a.every(o=>{var u;return!((u=this.excludeTags)!=null&&u.includes(o))})),n}}const Wk=Symbol("Let zodToJsonSchema decide on which parser to use"),K1={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},Gk=r=>typeof r=="string"?{...K1,name:r}:{...K1,...r},Hk=r=>{const e=Gk(r),t=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:t,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,a])=>[a._def,{def:a._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function Iv(r,e,t,n){n!=null&&n.errorMessages&&t&&(r.errorMessage={...r.errorMessage,[e]:t})}function Hr(r,e,t,n,a){r[e]=t,Iv(r,e,n,a)}function Kk(){return{}}function qk(r,e){var n,a,o;const t={type:"array"};return(n=r.type)!=null&&n._def&&((o=(a=r.type)==null?void 0:a._def)==null?void 0:o.typeName)!==vt.ZodAny&&(t.items=zr(r.type._def,{...e,currentPath:[...e.currentPath,"items"]})),r.minLength&&Hr(t,"minItems",r.minLength.value,r.minLength.message,e),r.maxLength&&Hr(t,"maxItems",r.maxLength.value,r.maxLength.message,e),r.exactLength&&(Hr(t,"minItems",r.exactLength.value,r.exactLength.message,e),Hr(t,"maxItems",r.exactLength.value,r.exactLength.message,e)),t}function Zk(r,e){const t={type:"integer",format:"int64"};if(!r.checks)return t;for(const n of r.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?Hr(t,"minimum",n.value,n.message,e):Hr(t,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(t.exclusiveMinimum=!0),Hr(t,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?Hr(t,"maximum",n.value,n.message,e):Hr(t,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(t.exclusiveMaximum=!0),Hr(t,"maximum",n.value,n.message,e));break;case"multipleOf":Hr(t,"multipleOf",n.value,n.message,e);break}return t}function Yk(){return{type:"boolean"}}function $v(r,e){return zr(r.type._def,e)}const Xk=(r,e)=>zr(r.innerType._def,e);function Ov(r,e,t){const n=t??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((a,o)=>Ov(r,e,a))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Qk(r,e)}}const Qk=(r,e)=>{const t={type:"integer",format:"unix-time"};if(e.target==="openApi3")return t;for(const n of r.checks)switch(n.kind){case"min":Hr(t,"minimum",n.value,n.message,e);break;case"max":Hr(t,"maximum",n.value,n.message,e);break}return t};function Jk(r,e){return{...zr(r.innerType._def,e),default:r.defaultValue()}}function eI(r,e){return e.effectStrategy==="input"?zr(r.schema._def,e):{}}function tI(r){return{type:"string",enum:Array.from(r.values)}}const rI=r=>"type"in r&&r.type==="string"?!1:"allOf"in r;function nI(r,e){const t=[zr(r.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),zr(r.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(o=>!!o);let n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const a=[];return t.forEach(o=>{if(rI(o))a.push(...o.allOf),o.unevaluatedProperties===void 0&&(n=void 0);else{let u=o;if("additionalProperties"in o&&o.additionalProperties===!1){const{additionalProperties:d,...c}=o;u=c}else n=void 0;a.push(u)}}),a.length?{allOf:a,...n}:void 0}function sI(r,e){const t=typeof r.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(r.value)?"array":"object"}:e.target==="openApi3"?{type:t==="bigint"?"integer":t,enum:[r.value]}:{type:t==="bigint"?"integer":t,const:r.value}}let Qg;const Ks={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Qg===void 0&&(Qg=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Qg),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function Lv(r,e){const t={type:"string"};if(r.checks)for(const n of r.checks)switch(n.kind){case"min":Hr(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,n.value):n.value,n.message,e);break;case"max":Hr(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":qs(t,"email",n.message,e);break;case"format:idn-email":qs(t,"idn-email",n.message,e);break;case"pattern:zod":Qn(t,Ks.email,n.message,e);break}break;case"url":qs(t,"uri",n.message,e);break;case"uuid":qs(t,"uuid",n.message,e);break;case"regex":Qn(t,n.regex,n.message,e);break;case"cuid":Qn(t,Ks.cuid,n.message,e);break;case"cuid2":Qn(t,Ks.cuid2,n.message,e);break;case"startsWith":Qn(t,RegExp(`^${Jg(n.value,e)}`),n.message,e);break;case"endsWith":Qn(t,RegExp(`${Jg(n.value,e)}$`),n.message,e);break;case"datetime":qs(t,"date-time",n.message,e);break;case"date":qs(t,"date",n.message,e);break;case"time":qs(t,"time",n.message,e);break;case"duration":qs(t,"duration",n.message,e);break;case"length":Hr(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,n.value):n.value,n.message,e),Hr(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,n.value):n.value,n.message,e);break;case"includes":{Qn(t,RegExp(Jg(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&qs(t,"ipv4",n.message,e),n.version!=="v4"&&qs(t,"ipv6",n.message,e);break}case"base64url":Qn(t,Ks.base64url,n.message,e);break;case"jwt":Qn(t,Ks.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&Qn(t,Ks.ipv4Cidr,n.message,e),n.version!=="v4"&&Qn(t,Ks.ipv6Cidr,n.message,e);break}case"emoji":Qn(t,Ks.emoji(),n.message,e);break;case"ulid":{Qn(t,Ks.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{qs(t,"binary",n.message,e);break}case"contentEncoding:base64":{Hr(t,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{Qn(t,Ks.base64,n.message,e);break}}break}case"nanoid":Qn(t,Ks.nanoid,n.message,e)}return t}function Jg(r,e){return e.patternStrategy==="escape"?iI(r):r}const aI=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function iI(r){let e="";for(let t=0;to.format)?(r.anyOf||(r.anyOf=[]),r.format&&(r.anyOf.push({format:r.format,...r.errorMessage&&n.errorMessages&&{errorMessage:{format:r.errorMessage.format}}}),delete r.format,r.errorMessage&&(delete r.errorMessage.format,Object.keys(r.errorMessage).length===0&&delete r.errorMessage)),r.anyOf.push({format:e,...t&&n.errorMessages&&{errorMessage:{format:t}}})):Hr(r,"format",e,t,n)}function Qn(r,e,t,n){var a;r.pattern||(a=r.allOf)!=null&&a.some(o=>o.pattern)?(r.allOf||(r.allOf=[]),r.pattern&&(r.allOf.push({pattern:r.pattern,...r.errorMessage&&n.errorMessages&&{errorMessage:{pattern:r.errorMessage.pattern}}}),delete r.pattern,r.errorMessage&&(delete r.errorMessage.pattern,Object.keys(r.errorMessage).length===0&&delete r.errorMessage)),r.allOf.push({pattern:q1(e,n),...t&&n.errorMessages&&{errorMessage:{pattern:t}}})):Hr(r,"pattern",q1(e,n),t,n)}function q1(r,e){var c;if(!e.applyRegexFlags||!r.flags)return r.source;const t={i:r.flags.includes("i"),m:r.flags.includes("m"),s:r.flags.includes("s")},n=t.i?r.source.toLowerCase():r.source;let a="",o=!1,u=!1,d=!1;for(let h=0;h({...h,[_]:zr(r.valueType._def,{...e,currentPath:[...e.currentPath,"properties",_]})??{}}),{}),additionalProperties:!1};const t={type:"object",additionalProperties:zr(r.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return t;if(((a=r.keyType)==null?void 0:a._def.typeName)===vt.ZodString&&((o=r.keyType._def.checks)!=null&&o.length)){const{type:h,..._}=Lv(r.keyType._def,e);return{...t,propertyNames:_}}else{if(((u=r.keyType)==null?void 0:u._def.typeName)===vt.ZodEnum)return{...t,propertyNames:{enum:r.keyType._def.values}};if(((d=r.keyType)==null?void 0:d._def.typeName)===vt.ZodBranded&&r.keyType._def.type._def.typeName===vt.ZodString&&((c=r.keyType._def.type._def.checks)!=null&&c.length)){const{type:h,..._}=$v(r.keyType._def,e);return{...t,propertyNames:_}}}return t}function oI(r,e){if(e.mapStrategy==="record")return Rv(r,e);const t=zr(r.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=zr(r.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[t,n],minItems:2,maxItems:2}}}function uI(r){const e=r.values,n=Object.keys(r.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),a=Array.from(new Set(n.map(o=>typeof o)));return{type:a.length===1?a[0]==="string"?"string":"number":["string","number"],enum:n}}function lI(){return{not:{}}}function cI(r){return r.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const E_={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function dI(r,e){if(e.target==="openApi3")return Z1(r,e);const t=r.options instanceof Map?Array.from(r.options.values()):r.options;if(t.every(n=>n._def.typeName in E_&&(!n._def.checks||!n._def.checks.length))){const n=t.reduce((a,o)=>{const u=E_[o._def.typeName];return u&&!a.includes(u)?[...a,u]:a},[]);return{type:n.length>1?n:n[0]}}else if(t.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){const n=t.reduce((a,o)=>{const u=typeof o._def.value;switch(u){case"string":case"number":case"boolean":return[...a,u];case"bigint":return[...a,"integer"];case"object":if(o._def.value===null)return[...a,"null"];case"symbol":case"undefined":case"function":default:return a}},[]);if(n.length===t.length){const a=n.filter((o,u,d)=>d.indexOf(o)===u);return{type:a.length>1?a:a[0],enum:t.reduce((o,u)=>o.includes(u._def.value)?o:[...o,u._def.value],[])}}}else if(t.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:t.reduce((n,a)=>[...n,...a._def.values.filter(o=>!n.includes(o))],[])};return Z1(r,e)}const Z1=(r,e)=>{const t=(r.options instanceof Map?Array.from(r.options.values()):r.options).map((n,a)=>zr(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${a}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return t.length?{anyOf:t}:void 0};function hI(r,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(r.innerType._def.typeName)&&(!r.innerType._def.checks||!r.innerType._def.checks.length))return e.target==="openApi3"?{type:E_[r.innerType._def.typeName],nullable:!0}:{type:[E_[r.innerType._def.typeName],"null"]};if(e.target==="openApi3"){const n=zr(r.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}const t=zr(r.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return t&&{anyOf:[t,{type:"null"}]}}function fI(r,e){const t={type:"number"};if(!r.checks)return t;for(const n of r.checks)switch(n.kind){case"int":t.type="integer",Iv(t,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?Hr(t,"minimum",n.value,n.message,e):Hr(t,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(t.exclusiveMinimum=!0),Hr(t,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?Hr(t,"maximum",n.value,n.message,e):Hr(t,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(t.exclusiveMaximum=!0),Hr(t,"maximum",n.value,n.message,e));break;case"multipleOf":Hr(t,"multipleOf",n.value,n.message,e);break}return t}function pI(r,e){return e.removeAdditionalStrategy==="strict"?r.catchall._def.typeName==="ZodNever"?r.unknownKeys!=="strict":zr(r.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:r.catchall._def.typeName==="ZodNever"?r.unknownKeys==="passthrough":zr(r.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function mI(r,e){const t=e.target==="openAi",n={type:"object",...Object.entries(r.shape()).reduce((a,[o,u])=>{if(u===void 0||u._def===void 0)return a;let d=u.isOptional();d&&t&&(u instanceof Qs&&(u=u._def.innerType),u.isNullable()||(u=u.nullable()),d=!1);const c=zr(u._def,{...e,currentPath:[...e.currentPath,"properties",o],propertyPath:[...e.currentPath,"properties",o]});return c===void 0?a:{properties:{...a.properties,[o]:c},required:d?a.required:[...a.required,o]}},{properties:{},required:[]}),additionalProperties:pI(r,e)};return n.required.length||delete n.required,n}const _I=(r,e)=>{var n;if(e.currentPath.toString()===((n=e.propertyPath)==null?void 0:n.toString()))return zr(r.innerType._def,e);const t=zr(r.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return t?{anyOf:[{not:{}},t]}:{}},gI=(r,e)=>{if(e.pipeStrategy==="input")return zr(r.in._def,e);if(e.pipeStrategy==="output")return zr(r.out._def,e);const t=zr(r.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=zr(r.out._def,{...e,currentPath:[...e.currentPath,"allOf",t?"1":"0"]});return{allOf:[t,n].filter(a=>a!==void 0)}};function bI(r,e){return zr(r.type._def,e)}function yI(r,e){const n={type:"array",uniqueItems:!0,items:zr(r.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return r.minSize&&Hr(n,"minItems",r.minSize.value,r.minSize.message,e),r.maxSize&&Hr(n,"maxItems",r.maxSize.value,r.maxSize.message,e),n}function wI(r,e){return r.rest?{type:"array",minItems:r.items.length,items:r.items.map((t,n)=>zr(t._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((t,n)=>n===void 0?t:[...t,n],[]),additionalItems:zr(r.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:r.items.length,maxItems:r.items.length,items:r.items.map((t,n)=>zr(t._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((t,n)=>n===void 0?t:[...t,n],[])}}function vI(){return{not:{}}}function EI(){return{}}const TI=(r,e)=>zr(r.innerType._def,e);function zr(r,e,t=!1){var u;const n=e.seen.get(r);if(e.override){const d=(u=e.override)==null?void 0:u.call(e,r,e,n,t);if(d!==Wk)return d}if(n&&!t){const d=xI(n,e);if(d!==void 0)return d}const a={def:r,path:e.currentPath,jsonSchema:void 0};e.seen.set(r,a);const o=PI(r,r.typeName,e);return o&&CI(r,e,o),a.jsonSchema=o,o}const xI=(r,e)=>{switch(e.$refStrategy){case"root":return{$ref:r.path.join("/")};case"relative":return{$ref:MI(e.currentPath,r.path)};case"none":case"seen":return r.path.lengthe.currentPath[n]===t)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},MI=(r,e)=>{let t=0;for(;t{switch(e){case vt.ZodString:return Lv(r,t);case vt.ZodNumber:return fI(r,t);case vt.ZodObject:return mI(r,t);case vt.ZodBigInt:return Zk(r,t);case vt.ZodBoolean:return Yk();case vt.ZodDate:return Ov(r,t);case vt.ZodUndefined:return vI();case vt.ZodNull:return cI(t);case vt.ZodArray:return qk(r,t);case vt.ZodUnion:case vt.ZodDiscriminatedUnion:return dI(r,t);case vt.ZodIntersection:return nI(r,t);case vt.ZodTuple:return wI(r,t);case vt.ZodRecord:return Rv(r,t);case vt.ZodLiteral:return sI(r,t);case vt.ZodEnum:return tI(r);case vt.ZodNativeEnum:return uI(r);case vt.ZodNullable:return hI(r,t);case vt.ZodOptional:return _I(r,t);case vt.ZodMap:return oI(r,t);case vt.ZodSet:return yI(r,t);case vt.ZodLazy:return zr(r.getter()._def,t);case vt.ZodPromise:return bI(r,t);case vt.ZodNaN:case vt.ZodNever:return lI();case vt.ZodEffects:return eI(r,t);case vt.ZodAny:return Kk();case vt.ZodUnknown:return EI();case vt.ZodDefault:return Jk(r,t);case vt.ZodBranded:return $v(r,t);case vt.ZodReadonly:return TI(r,t);case vt.ZodCatch:return Xk(r,t);case vt.ZodPipeline:return gI(r,t);case vt.ZodFunction:case vt.ZodVoid:case vt.ZodSymbol:return;default:return(n=>{})()}},CI=(r,e,t)=>(r.description&&(t.description=r.description,e.markdownDescription&&(t.markdownDescription=r.description)),t),SI=(r,e)=>{const t=Hk(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[h,_])=>({...c,[h]:zr(_._def,{...t,currentPath:[...t.basePath,t.definitionPath,h]},!0)??{}}),{}):void 0,a=typeof e=="string"?e:(e==null?void 0:e.nameStrategy)==="title"||e==null?void 0:e.name,o=zr(r._def,a===void 0?t:{...t,currentPath:[...t.basePath,t.definitionPath,a]},!1)??{},u=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;u!==void 0&&(o.title=u);const d=a===void 0?n?{...o,[t.definitionPath]:n}:o:{$ref:[...t.$refStrategy==="relative"?[]:t.basePath,t.definitionPath,a].join("/"),[t.definitionPath]:{...n,[a]:o}};return t.target==="jsonSchema7"?d.$schema="http://json-schema.org/draft-07/schema#":(t.target==="jsonSchema2019-09"||t.target==="openAi")&&(d.$schema="https://json-schema.org/draft/2019-09/schema#"),t.target==="openAi"&&("anyOf"in d||"oneOf"in d||"allOf"in d||"type"in d&&Array.isArray(d.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),d};function e0(r){return r.replace(/[^a-zA-Z-_0-9]/g,"_")}const AI=["*","_","`"];function kI(r){let e="";for(const[t,n]of Object.entries(r))e+=` classDef ${t} ${n}; `;return e}function II(r,e,t){const{firstNode:n,lastNode:a,nodeColors:o,withStyles:u=!0,curveStyle:d="linear",wrapLabelNWords:c=9}=t??{};let h=u?`%%{init: {'flowchart': {'curve': '${d}'}}}%% graph TD; `:`graph TD; `;if(u){const M="default",S={[M]:"{0}({1})"};n!==void 0&&(S[n]="{0}([{1}]):::first"),a!==void 0&&(S[a]="{0}([{1}]):::last");for(const[G,H]of Object.entries(r)){const B=H.name.split(":").pop()??"";let U=AI.some(I=>B.startsWith(I)&&B.endsWith(I))?`

${B}

`:B;Object.keys(H.metadata??{}).length&&(U+=`
${Object.entries(H.metadata??{}).map(([I,k])=>`${I} = ${k}`).join(` `)}`);const F=(S[G]??S[M]).replace("{0}",e0(G)).replace("{1}",U);h+=` ${F} `}}const _={};for(const M of e){const S=M.source.split(":"),G=M.target.split(":"),H=S.filter((B,z)=>B===G[z]).join(":");_[H]||(_[H]=[]),_[H].push(M)}const y=new Set;function w(M,S){const G=M.length===1&&M[0].source===M[0].target;if(S&&!G){const H=S.split(":").pop();if(y.has(H))throw new Error(`Found duplicate subgraph '${H}' -- this likely means that you're reusing a subgraph node with the same name. Please adjust your graph to have subgraph nodes with unique names.`);y.add(H),h+=` subgraph ${H} `}for(const H of M){const{source:B,target:z,data:U,conditional:F}=H;let I="";if(U!==void 0){let k=U;const $=k.split(" ");$.length>c&&(k=Array.from({length:Math.ceil($.length/c)},(j,ce)=>$.slice(ce*c,(ce+1)*c).join(" ")).join(" 
 ")),I=F?` -.  ${k}  .-> `:` --  ${k}  --> `}else I=F?" -.-> ":" --> ";h+=` ${e0(B)}${I}${e0(z)}; `}for(const H in _)H.startsWith(`${S}:`)&&H!==S&&w(_[H],H);S&&!G&&(h+=` end `)}w(_[""]??[],"");for(const M in _)!M.includes(":")&&M!==""&&w(_[M],M);return u&&(h+=kI(o??{})),h}async function $I(r,e){let{backgroundColor:t="white"}=e??{};const n=btoa(r);t!==void 0&&(/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(t)||(t=`!${t}`));const a=`https://mermaid.ink/img/${n}?bgColor=${t}`,o=await fetch(a);if(!o.ok)throw new Error(["Failed to render the graph using the Mermaid.INK API.",`Status code: ${o.status}`,`Status text: ${o.statusText}`].join(` `));return await o.blob()}function OI(r,e){if(r!==void 0&&!ap(r))return r;if(tb(e))try{let t=e.getName();return t=t.startsWith("Runnable")?t.slice(8):t,t}catch{return e.getName()}else return e.name??"UnknownSchema"}function LI(r){return tb(r.data)?{type:"runnable",data:{id:r.data.lc_id,name:r.data.getName()}}:{type:"schema",data:{...SI(r.data.schema),title:r.data.name}}}class z_{constructor(e){Object.defineProperty(this,"nodes",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"edges",{enumerable:!0,configurable:!0,writable:!0,value:[]}),this.nodes=(e==null?void 0:e.nodes)??this.nodes,this.edges=(e==null?void 0:e.edges)??this.edges}toJSON(){const e={};return Object.values(this.nodes).forEach((t,n)=>{e[t.id]=ap(t.id)?n:t.id}),{nodes:Object.values(this.nodes).map(t=>({id:e[t.id],...LI(t)})),edges:this.edges.map(t=>{const n={source:e[t.source],target:e[t.target]};return typeof t.data<"u"&&(n.data=t.data),typeof t.conditional<"u"&&(n.conditional=t.conditional),n})}}addNode(e,t,n){if(t!==void 0&&this.nodes[t]!==void 0)throw new Error(`Node with id ${t} already exists`);const a=t??hs(),o={id:a,data:e,name:OI(t,e),metadata:n};return this.nodes[a]=o,o}removeNode(e){delete this.nodes[e.id],this.edges=this.edges.filter(t=>t.source!==e.id&&t.target!==e.id)}addEdge(e,t,n,a){if(this.nodes[e.id]===void 0)throw new Error(`Source node ${e.id} not in graph`);if(this.nodes[t.id]===void 0)throw new Error(`Target node ${t.id} not in graph`);const o={source:e.id,target:t.id,data:n,conditional:a};return this.edges.push(o),o}firstNode(){return Y1(this)}lastNode(){return X1(this)}extend(e,t=""){let n=t;Object.values(e.nodes).map(h=>h.id).every(ap)&&(n="");const o=h=>n?`${n}:${h}`:h;Object.entries(e.nodes).forEach(([h,_])=>{this.nodes[o(h)]={..._,id:o(h)}});const u=e.edges.map(h=>({...h,source:o(h.source),target:o(h.target)}));this.edges=[...this.edges,...u];const d=e.firstNode(),c=e.lastNode();return[d?{id:o(d.id),data:d.data}:void 0,c?{id:o(c.id),data:c.data}:void 0]}trimFirstNode(){const e=this.firstNode();e&&Y1(this,[e.id])&&this.removeNode(e)}trimLastNode(){const e=this.lastNode();e&&X1(this,[e.id])&&this.removeNode(e)}reid(){const e=Object.fromEntries(Object.values(this.nodes).map(a=>[a.id,a.name])),t=new Map;Object.values(e).forEach(a=>{t.set(a,(t.get(a)||0)+1)});const n=a=>{const o=e[a];return ap(a)&&t.get(o)===1?o:a};return new z_({nodes:Object.fromEntries(Object.entries(this.nodes).map(([a,o])=>[n(a),{...o,id:n(a)}])),edges:this.edges.map(a=>({...a,source:n(a.source),target:n(a.target)}))})}drawMermaid(e){const{withStyles:t,curveStyle:n,nodeColors:a={default:"fill:#f2f0ff,line-height:1.2",first:"fill-opacity:0",last:"fill:#bfb6fc"},wrapLabelNWords:o}=e??{},u=this.reid(),d=u.firstNode(),c=u.lastNode();return II(u.nodes,u.edges,{firstNode:d==null?void 0:d.id,lastNode:c==null?void 0:c.id,withStyles:t,curveStyle:n,nodeColors:a,wrapLabelNWords:o})}async drawMermaidPng(e){const t=this.drawMermaid(e);return $I(t,{backgroundColor:e==null?void 0:e.backgroundColor})}}function Y1(r,e=[]){const t=new Set(r.edges.filter(a=>!e.includes(a.source)).map(a=>a.target)),n=[];for(const a of Object.values(r.nodes))!e.includes(a.id)&&!t.has(a.id)&&n.push(a);return n.length===1?n[0]:void 0}function X1(r,e=[]){const t=new Set(r.edges.filter(a=>!e.includes(a.target)).map(a=>a.source)),n=[];for(const a of Object.values(r.nodes))!e.includes(a.id)&&!t.has(a.id)&&n.push(a);return n.length===1?n[0]:void 0}function RI(r){const e=new TextEncoder,t=new ReadableStream({async start(n){for await(const a of r)n.enqueue(e.encode(`event: data data: ${JSON.stringify(a)} `));n.enqueue(e.encode(`event: end `)),n.close()}});return vs.fromReadableStream(t)}function Q1(r){return typeof r=="object"&&r!==null&&typeof r[Symbol.iterator]=="function"&&typeof r.next=="function"}const FI=r=>r!=null&&typeof r=="object"&&"next"in r&&typeof r.next=="function";function w0(r){return typeof r=="object"&&r!==null&&typeof r[Symbol.asyncIterator]=="function"}function*J1(r,e){for(;;){const{value:t,done:n}=Ai.runWithConfig(Dl(r),e.next.bind(e),!0);if(n)break;yield t}}async function*v0(r,e){const t=e[Symbol.asyncIterator]();for(;;){const{value:n,done:a}=await Ai.runWithConfig(Dl(r),t.next.bind(e),!0);if(a)break;yield n}}function Rn(r,e){return r&&!Array.isArray(r)&&!(r instanceof Date)&&typeof r=="object"?r:{[e]:r}}class Jn extends Nl{constructor(){super(...arguments),Object.defineProperty(this,"lc_runnable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}getName(e){const t=this.name??this.constructor.lc_name()??this.constructor.name;return e?`${t}${e}`:t}bind(e){return new vo({bound:this,kwargs:e,config:{}})}map(){return new T_({bound:this})}withRetry(e){return new NI({bound:this,kwargs:{},config:{},maxAttemptNumber:e==null?void 0:e.stopAfterAttempt,...e})}withConfig(e){return new vo({bound:this,config:e,kwargs:{}})}withFallbacks(e){const t=Array.isArray(e)?e:e.fallbacks;return new BI({runnable:this,fallbacks:t})}_getOptionsList(e,t=0){if(Array.isArray(e)&&e.length!==t)throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${e.length} options for ${t} inputs`);if(Array.isArray(e))return e.map(qr);if(t>1&&!Array.isArray(e)&&e.runId){console.warn("Provided runId will be used only for the first element of the batch.");const n=Object.fromEntries(Object.entries(e).filter(([a])=>a!=="runId"));return Array.from({length:t},(a,o)=>qr(o===0?e:n))}return Array.from({length:t},()=>qr(e))}async batch(e,t,n){var c;const a=this._getOptionsList(t??{},e.length),o=((c=a[0])==null?void 0:c.maxConcurrency)??(n==null?void 0:n.maxConcurrency),u=new Uk({maxConcurrency:o,onFailedAttempt:h=>{throw h}}),d=e.map((h,_)=>u.call(async()=>{try{return await this.invoke(h,a[_])}catch(y){if(n!=null&&n.returnExceptions)return y;throw y}}));return Promise.all(d)}async*_streamIterator(e,t){yield this.invoke(e,t)}async stream(e,t){const n=qr(t),a=new Gl({generator:this._streamIterator(e,n),config:n});return await a.setup,vs.fromAsyncGenerator(a)}_separateRunnableConfigFromCallOptions(e){let t;e===void 0?t=qr(e):t=qr({callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,runName:e.runName,configurable:e.configurable,recursionLimit:e.recursionLimit,maxConcurrency:e.maxConcurrency,runId:e.runId,timeout:e.timeout,signal:e.signal});const n={...e};return delete n.callbacks,delete n.tags,delete n.metadata,delete n.runName,delete n.configurable,delete n.recursionLimit,delete n.maxConcurrency,delete n.runId,delete n.timeout,delete n.signal,[t,n]}async _callWithConfig(e,t,n){const a=qr(n),o=await Js(a),u=await(o==null?void 0:o.handleChainStart(this.toJSON(),Rn(t,"input"),a.runId,a==null?void 0:a.runType,void 0,void 0,(a==null?void 0:a.runName)??this.getName()));delete a.runId;let d;try{const c=e.call(this,t,a,u);d=await ki(c,n==null?void 0:n.signal)}catch(c){throw await(u==null?void 0:u.handleChainError(c)),c}return await(u==null?void 0:u.handleChainEnd(Rn(d,"output"))),d}async _batchWithConfig(e,t,n,a){var h;const o=this._getOptionsList(n??{},t.length),u=await Promise.all(o.map(Js)),d=await Promise.all(u.map(async(_,y)=>{const w=await(_==null?void 0:_.handleChainStart(this.toJSON(),Rn(t[y],"input"),o[y].runId,o[y].runType,void 0,void 0,o[y].runName??this.getName()));return delete o[y].runId,w}));let c;try{const _=e.call(this,t,o,d,a);c=await ki(_,(h=o==null?void 0:o[0])==null?void 0:h.signal)}catch(_){throw await Promise.all(d.map(y=>y==null?void 0:y.handleChainError(_))),_}return await Promise.all(d.map(_=>_==null?void 0:_.handleChainEnd(Rn(c,"output")))),c}async*_transformStreamWithConfig(e,t,n){let a,o=!0,u,d=!0;const c=qr(n),h=await Js(c);async function*_(){for await(const w of e){if(o)if(a===void 0)a=w;else try{a=Wa(a,w)}catch{a=void 0,o=!1}yield w}}let y;try{const w=await Rk(t.bind(this),_(),async()=>h==null?void 0:h.handleChainStart(this.toJSON(),{input:""},c.runId,c.runType,void 0,void 0,c.runName??this.getName()),n==null?void 0:n.signal,c);delete c.runId,y=w.setup;const M=y==null?void 0:y.handlers.find(Dk);let S=w.output;M!==void 0&&y!==void 0&&(S=M.tapOutputIterable(y.runId,S));const G=y==null?void 0:y.handlers.find(Fk);G!==void 0&&y!==void 0&&(S=G.tapOutputIterable(y.runId,S));for await(const H of S)if(yield H,d)if(u===void 0)u=H;else try{u=Wa(u,H)}catch{u=void 0,d=!1}}catch(w){throw await(y==null?void 0:y.handleChainError(w,void 0,void 0,void 0,{inputs:Rn(a,"input")})),w}await(y==null?void 0:y.handleChainEnd(u??{},void 0,void 0,void 0,{inputs:Rn(a,"input")}))}getGraph(e){const t=new z_,n=t.addNode({name:`${this.getName()}Input`,schema:sp.any()}),a=t.addNode(this),o=t.addNode({name:`${this.getName()}Output`,schema:sp.any()});return t.addEdge(n,a),t.addEdge(a,o),t}pipe(e){return new bo({first:this,last:yo(e)})}pick(e){return this.pipe(new zI(e))}assign(e){return this.pipe(new jI(new Dp({steps:e})))}async*transform(e,t){let n;for await(const a of e)n===void 0?n=a:n=Wa(n,a);yield*this._streamIterator(n,qr(t))}async*streamLog(e,t,n){const a=new H1({...n,autoClose:!1,_schemaFormat:"original"}),o=qr(t);yield*this._streamLog(e,a,o)}async*_streamLog(e,t,n){const{callbacks:a}=n;if(a===void 0)n.callbacks=[t];else if(Array.isArray(a))n.callbacks=a.concat([t]);else{const c=a.copy();c.addHandler(t,!0),n.callbacks=c}const o=this.stream(e,n);async function u(){try{const c=await o;for await(const h of c){const _=new wi({ops:[{op:"add",path:"/streamed_output/-",value:h}]});await t.writer.write(_)}}finally{await t.writer.close()}}const d=u();try{for await(const c of t)yield c}finally{await d}}streamEvents(e,t,n){let a;if(t.version==="v1")a=this._streamEventsV1(e,t,n);else if(t.version==="v2")a=this._streamEventsV2(e,t,n);else throw new Error('Only versions "v1" and "v2" of the schema are currently supported.');return t.encoding==="text/event-stream"?RI(a):vs.fromAsyncGenerator(a)}async*_streamEventsV2(e,t,n){var M;const a=new Bk({...n,autoClose:!1}),o=qr(t),u=o.runId??hs();o.runId=u;const d=o.callbacks;if(d===void 0)o.callbacks=[a];else if(Array.isArray(d))o.callbacks=d.concat(a);else{const S=d.copy();S.addHandler(a,!0),o.callbacks=S}const c=this;async function h(){try{const S=await c.stream(e,o),G=a.tapOutputIterable(u,S);for await(const H of G);}finally{await a.finish()}}const _=h();let y=!1,w;try{for await(const S of a){if(!y){S.data.input=e,y=!0,w=S.run_id,yield S;continue}S.run_id===w&&S.event.endsWith("_end")&&(M=S.data)!=null&&M.input&&delete S.data.input,yield S}}finally{await _}}async*_streamEventsV1(e,t,n){let a,o=!1;const u=qr(t),d=u.tags??[],c=u.metadata??{},h=u.runName??this.getName(),_=new H1({...n,autoClose:!1,_schemaFormat:"streaming_events"}),y=new Vk({...n}),w=this._streamLog(e,_,u);for await(const S of w){if(a?a=a.concat(S):a=kp.fromRunLogPatch(S),a.state===void 0)throw new Error('Internal error: "streamEvents" state is missing. Please open a bug report.');if(!o){o=!0;const z={...a.state},U={run_id:z.id,event:`on_${z.type}_start`,name:h,tags:d,metadata:c,data:{input:e}};y.includeEvent(U,z.type)&&(yield U)}const G=S.ops.filter(z=>z.path.startsWith("/logs/")).map(z=>z.path.split("/")[2]),H=[...new Set(G)];for(const z of H){let U,F={};const I=a.state.logs[z];if(I.end_time===void 0?I.streamed_output.length>0?U="stream":U="start":U="end",U==="start")I.inputs!==void 0&&(F.input=I.inputs);else if(U==="end")I.inputs!==void 0&&(F.input=I.inputs),F.output=I.final_output;else if(U==="stream"){const k=I.streamed_output.length;if(k!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${k} instead. Encountered in: "${I.name}"`);F={chunk:I.streamed_output[0]},I.streamed_output=[]}yield{event:`on_${I.type}_${U}`,name:I.name,run_id:I.id,tags:I.tags,metadata:I.metadata,data:F}}const{state:B}=a;if(B.streamed_output.length>0){const z=B.streamed_output.length;if(z!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${z} instead. Encountered in: "${B.name}"`);const U={chunk:B.streamed_output[0]};B.streamed_output=[];const F={event:`on_${B.type}_stream`,run_id:B.id,tags:d,metadata:c,name:h,data:U};y.includeEvent(F,B.type)&&(yield F)}}const M=a==null?void 0:a.state;if(M!==void 0){const S={event:`on_${M.type}_end`,name:h,run_id:M.id,tags:d,metadata:c,data:{output:M.final_output}};y.includeEvent(S,M.type)&&(yield S)}}static isRunnable(e){return tb(e)}withListeners({onStart:e,onEnd:t,onError:n}){return new vo({bound:this,config:{},configFactories:[a=>({callbacks:[new kv({config:a,onStart:e,onEnd:t,onError:n})]})]})}asTool(e){return UI(this,e)}}class vo extends Jn{static lc_name(){return"RunnableBinding"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"bound",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"configFactories",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.bound=e.bound,this.kwargs=e.kwargs,this.config=e.config,this.configFactories=e.configFactories}getName(e){return this.bound.getName(e)}async _mergeConfig(...e){const t=V1(this.config,...e);return V1(t,...this.configFactories?await Promise.all(this.configFactories.map(async n=>await n(t))):[])}bind(e){return new this.constructor({bound:this.bound,kwargs:{...this.kwargs,...e},config:this.config})}withConfig(e){return new this.constructor({bound:this.bound,kwargs:this.kwargs,config:{...this.config,...e}})}withRetry(e){return new this.constructor({bound:this.bound.withRetry(e),kwargs:this.kwargs,config:this.config})}async invoke(e,t){return this.bound.invoke(e,await this._mergeConfig(qr(t),this.kwargs))}async batch(e,t,n){const a=Array.isArray(t)?await Promise.all(t.map(async o=>this._mergeConfig(qr(o),this.kwargs))):await this._mergeConfig(qr(t),this.kwargs);return this.bound.batch(e,a,n)}async*_streamIterator(e,t){yield*this.bound._streamIterator(e,await this._mergeConfig(qr(t),this.kwargs))}async stream(e,t){return this.bound.stream(e,await this._mergeConfig(qr(t),this.kwargs))}async*transform(e,t){yield*this.bound.transform(e,await this._mergeConfig(qr(t),this.kwargs))}streamEvents(e,t,n){const a=this,o=async function*(){yield*a.bound.streamEvents(e,{...await a._mergeConfig(qr(t),a.kwargs),version:t.version},n)};return vs.fromAsyncGenerator(o())}static isRunnableBinding(e){return e.bound&&Jn.isRunnable(e.bound)}withListeners({onStart:e,onEnd:t,onError:n}){return new vo({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[a=>({callbacks:[new kv({config:a,onStart:e,onEnd:t,onError:n})]})]})}}class T_ extends Jn{static lc_name(){return"RunnableEach"}constructor(e){super(e),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"bound",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.bound=e.bound}bind(e){return new T_({bound:this.bound.bind(e)})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async _invoke(e,t,n){return this.bound.batch(e,Gn(t,{callbacks:n==null?void 0:n.getChild()}))}withListeners({onStart:e,onEnd:t,onError:n}){return new T_({bound:this.bound.withListeners({onStart:e,onEnd:t,onError:n})})}}class NI extends vo{static lc_name(){return"RunnableRetry"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"maxAttemptNumber",{enumerable:!0,configurable:!0,writable:!0,value:3}),Object.defineProperty(this,"onFailedAttempt",{enumerable:!0,configurable:!0,writable:!0,value:()=>{}}),this.maxAttemptNumber=e.maxAttemptNumber??this.maxAttemptNumber,this.onFailedAttempt=e.onFailedAttempt??this.onFailedAttempt}_patchConfigForRetry(e,t,n){const a=e>1?`retry:attempt:${e}`:void 0;return Gn(t,{callbacks:n==null?void 0:n.getChild(a)})}async _invoke(e,t,n){return p_(a=>super.invoke(e,this._patchConfigForRetry(a,t,n)),{onFailedAttempt:a=>this.onFailedAttempt(a,e),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async _batch(e,t,n,a){const o={};try{await p_(async u=>{const d=e.map((w,M)=>M).filter(w=>o[w.toString()]===void 0||o[w.toString()]instanceof Error),c=d.map(w=>e[w]),h=d.map(w=>this._patchConfigForRetry(u,t==null?void 0:t[w],n==null?void 0:n[w])),_=await super.batch(c,h,{...a,returnExceptions:!0});let y;for(let w=0;w<_.length;w+=1){const M=_[w],S=d[w];M instanceof Error&&y===void 0&&(y=M,y.input=c[w]),o[S.toString()]=M}if(y)throw y;return _},{onFailedAttempt:u=>this.onFailedAttempt(u,u.input),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}catch(u){if((a==null?void 0:a.returnExceptions)!==!0)throw u}return Object.keys(o).sort((u,d)=>parseInt(u,10)-parseInt(d,10)).map(u=>o[parseInt(u,10)])}async batch(e,t,n){return this._batchWithConfig(this._batch.bind(this),e,t,n)}}class bo extends Jn{static lc_name(){return"RunnableSequence"}constructor(e){super(e),Object.defineProperty(this,"first",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"middle",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"last",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"omitSequenceTags",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),this.first=e.first,this.middle=e.middle??this.middle,this.last=e.last,this.name=e.name,this.omitSequenceTags=e.omitSequenceTags??this.omitSequenceTags}get steps(){return[this.first,...this.middle,this.last]}async invoke(e,t){var c;const n=qr(t),a=await Js(n),o=await(a==null?void 0:a.handleChainStart(this.toJSON(),Rn(e,"input"),n.runId,void 0,void 0,void 0,n==null?void 0:n.runName));delete n.runId;let u=e,d;try{const h=[this.first,...this.middle];for(let _=0;_{const y=await(h==null?void 0:h.handleChainStart(this.toJSON(),Rn(e[_],"input"),a[_].runId,void 0,void 0,void 0,a[_].runName));return delete a[_].runId,y}));let d=e;try{for(let h=0;h{const S=w==null?void 0:w.getChild(this.omitSequenceTags?void 0:`seq:step:${h+1}`);return Gn(a[M],{callbacks:S})}),n);d=await ki(y,(c=a[0])==null?void 0:c.signal)}}catch(h){throw await Promise.all(u.map(_=>_==null?void 0:_.handleChainError(h))),h}return await Promise.all(u.map(h=>h==null?void 0:h.handleChainEnd(Rn(d,"output")))),d}async*_streamIterator(e,t){var y;const n=await Js(t),{runId:a,...o}=t??{},u=await(n==null?void 0:n.handleChainStart(this.toJSON(),Rn(e,"input"),a,void 0,void 0,void 0,o==null?void 0:o.runName)),d=[this.first,...this.middle,this.last];let c=!0,h;async function*_(){yield e}try{let w=d[0].transform(_(),Gn(o,{callbacks:u==null?void 0:u.getChild(this.omitSequenceTags?void 0:"seq:step:1")}));for(let M=1;M{const u=a.getGraph(e);o!==0&&u.trimFirstNode(),o!==this.steps.length-1&&u.trimLastNode(),t.extend(u);const d=u.firstNode();if(!d)throw new Error(`Runnable ${a} has no first node`);n&&t.addEdge(n,d),n=u.lastNode()}),t}pipe(e){return bo.isRunnableSequence(e)?new bo({first:this.first,middle:this.middle.concat([this.last,e.first,...e.middle]),last:e.last,name:this.name??e.name}):new bo({first:this.first,middle:[...this.middle,this.last],last:yo(e),name:this.name})}static isRunnableSequence(e){return Array.isArray(e.middle)&&Jn.isRunnable(e)}static from([e,...t],n){let a={};return typeof n=="string"?a.name=n:n!==void 0&&(a=n),new bo({...a,first:yo(e),middle:t.slice(0,-1).map(yo),last:yo(t[t.length-1])})}}class Dp extends Jn{static lc_name(){return"RunnableMap"}getStepsKeys(){return Object.keys(this.steps)}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"steps",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.steps={};for(const[t,n]of Object.entries(e.steps))this.steps[t]=yo(n)}static from(e){return new Dp({steps:e})}async invoke(e,t){const n=qr(t),a=await Js(n),o=await(a==null?void 0:a.handleChainStart(this.toJSON(),{input:e},n.runId,void 0,void 0,void 0,n==null?void 0:n.runName));delete n.runId;const u={};try{const d=Object.entries(this.steps).map(async([c,h])=>{u[c]=await h.invoke(e,Gn(n,{callbacks:o==null?void 0:o.getChild(`map:key:${c}`)}))});await ki(Promise.all(d),t==null?void 0:t.signal)}catch(d){throw await(o==null?void 0:o.handleChainError(d)),d}return await(o==null?void 0:o.handleChainEnd(u)),u}async*_transform(e,t,n){const a={...this.steps},o=Av(e,Object.keys(a).length),u=new Map(Object.entries(a).map(([d,c],h)=>{const _=c.transform(o[h],Gn(n,{callbacks:t==null?void 0:t.getChild(`map:key:${d}`)}));return[d,_.next().then(y=>({key:d,gen:_,result:y}))]}));for(;u.size;){const d=Promise.race(u.values()),{key:c,result:h,gen:_}=await ki(d,n==null?void 0:n.signal);u.delete(c),h.done||(yield{[c]:h.value},u.set(c,_.next().then(y=>({key:c,gen:_,result:y}))))}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*n(){yield e}const a=qr(t),o=new Gl({generator:this.transform(n(),a),config:a});return await o.setup,vs.fromAsyncGenerator(o)}}class rb extends Jn{constructor(e){if(super(e),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"func",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),!X0(e.func))throw new Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function");this.func=e.func}async invoke(e,t){const[n]=this._getOptionsList(t??{},1),a=await Js(n),o=this.func(Gn(n,{callbacks:a}),e);return ki(o,n==null?void 0:n.signal)}async*_streamIterator(e,t){var o,u;const[n]=this._getOptionsList(t??{},1),a=await this.invoke(e,t);if(w0(a)){for await(const d of a)(o=n==null?void 0:n.signal)==null||o.throwIfAborted(),yield d;return}if(FI(a)){for(;;){(u=n==null?void 0:n.signal)==null||u.throwIfAborted();const d=a.next();if(d.done)break;yield d.value}return}yield a}static from(e){return new rb({func:e})}}function DI(r){if(X0(r))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}class U_ extends Jn{static lc_name(){return"RunnableLambda"}constructor(e){if(X0(e.func))return rb.from(e.func);super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"func",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),DI(e.func),this.func=e.func}static from(e){return new U_({func:e})}async _invoke(e,t,n){return new Promise((a,o)=>{const u=Gn(t,{callbacks:n==null?void 0:n.getChild(),recursionLimit:((t==null?void 0:t.recursionLimit)??Xg)-1});Ai.runWithConfig(Dl(u),async()=>{var d,c;try{let h=await this.func(e,{...u});if(h&&Jn.isRunnable(h)){if((t==null?void 0:t.recursionLimit)===0)throw new Error("Recursion limit reached.");h=await h.invoke(e,{...u,recursionLimit:(u.recursionLimit??Xg)-1})}else if(w0(h)){let _;for await(const y of v0(u,h))if((d=t==null?void 0:t.signal)==null||d.throwIfAborted(),_===void 0)_=y;else try{_=Wa(_,y)}catch{_=y}h=_}else if(Q1(h)){let _;for(const y of J1(u,h))if((c=t==null?void 0:t.signal)==null||c.throwIfAborted(),_===void 0)_=y;else try{_=Wa(_,y)}catch{_=y}h=_}a(h)}catch(h){o(h)}})})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async*_transform(e,t,n){var d,c;let a;for await(const h of e)if(a===void 0)a=h;else try{a=Wa(a,h)}catch{a=h}const o=Gn(n,{callbacks:t==null?void 0:t.getChild(),recursionLimit:((n==null?void 0:n.recursionLimit)??Xg)-1}),u=await new Promise((h,_)=>{Ai.runWithConfig(Dl(o),async()=>{try{const y=await this.func(a,{...o,config:o});h(y)}catch(y){_(y)}})});if(u&&Jn.isRunnable(u)){if((n==null?void 0:n.recursionLimit)===0)throw new Error("Recursion limit reached.");const h=await u.stream(a,o);for await(const _ of h)yield _}else if(w0(u))for await(const h of v0(o,u))(d=n==null?void 0:n.signal)==null||d.throwIfAborted(),yield h;else if(Q1(u))for(const h of J1(o,u))(c=n==null?void 0:n.signal)==null||c.throwIfAborted(),yield h;else yield u}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*n(){yield e}const a=qr(t),o=new Gl({generator:this.transform(n(),a),config:a});return await o.setup,vs.fromAsyncGenerator(o)}}class BI extends Jn{static lc_name(){return"RunnableWithFallbacks"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"runnable",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fallbacks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.runnable=e.runnable,this.fallbacks=e.fallbacks}*runnables(){yield this.runnable;for(const e of this.fallbacks)yield e}async invoke(e,t){const n=qr(t),a=await Js(n),{runId:o,...u}=n,d=await(a==null?void 0:a.handleChainStart(this.toJSON(),Rn(e,"input"),o,void 0,void 0,void 0,u==null?void 0:u.runName)),c=Gn(u,{callbacks:d==null?void 0:d.getChild()});return await Ai.runWithConfig(c,async()=>{var y;let _;for(const w of this.runnables()){(y=n==null?void 0:n.signal)==null||y.throwIfAborted();try{const M=await w.invoke(e,c);return await(d==null?void 0:d.handleChainEnd(Rn(M,"output"))),M}catch(M){_===void 0&&(_=M)}}throw _===void 0?new Error("No error stored at end of fallback."):(await(d==null?void 0:d.handleChainError(_)),_)})}async*_streamIterator(e,t){var y;const n=qr(t),a=await Js(n),{runId:o,...u}=n,d=await(a==null?void 0:a.handleChainStart(this.toJSON(),Rn(e,"input"),o,void 0,void 0,void 0,u==null?void 0:u.runName));let c,h;for(const w of this.runnables()){(y=n==null?void 0:n.signal)==null||y.throwIfAborted();const M=Gn(u,{callbacks:d==null?void 0:d.getChild()});try{const S=await w.stream(e,M);h=v0(M,S);break}catch(S){c===void 0&&(c=S)}}if(h===void 0){const w=c??new Error("No error stored at end of fallback.");throw await(d==null?void 0:d.handleChainError(w)),w}let _;try{for await(const w of h){yield w;try{_=_===void 0?_:Wa(_,w)}catch{_=void 0}}}catch(w){throw await(d==null?void 0:d.handleChainError(w)),w}await(d==null?void 0:d.handleChainEnd(Rn(_,"output")))}async batch(e,t,n){var c;if(n!=null&&n.returnExceptions)throw new Error("Not implemented.");const a=this._getOptionsList(t??{},e.length),o=await Promise.all(a.map(h=>Js(h))),u=await Promise.all(o.map(async(h,_)=>{const y=await(h==null?void 0:h.handleChainStart(this.toJSON(),Rn(e[_],"input"),a[_].runId,void 0,void 0,void 0,a[_].runName));return delete a[_].runId,y}));let d;for(const h of this.runnables()){(c=a[0].signal)==null||c.throwIfAborted();try{const _=await h.batch(e,u.map((y,w)=>Gn(a[w],{callbacks:y==null?void 0:y.getChild()})),n);return await Promise.all(u.map((y,w)=>y==null?void 0:y.handleChainEnd(Rn(_[w],"output")))),_}catch(_){d===void 0&&(d=_)}}throw d?(await Promise.all(u.map(h=>h==null?void 0:h.handleChainError(d))),d):new Error("No error stored at end of fallbacks.")}}function yo(r){if(typeof r=="function")return new U_({func:r});if(Jn.isRunnable(r))return r;if(!Array.isArray(r)&&typeof r=="object"){const e={};for(const[t,n]of Object.entries(r))e[t]=yo(n);return new Dp({steps:e})}else throw new Error(`Expected a Runnable, function or object. Instead got an unsupported type.`)}class jI extends Jn{static lc_name(){return"RunnableAssign"}constructor(e){e instanceof Dp&&(e={mapper:e}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"mapper",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.mapper=e.mapper}async invoke(e,t){const n=await this.mapper.invoke(e,t);return{...e,...n}}async*_transform(e,t,n){const a=this.mapper.getStepsKeys(),[o,u]=Av(e),d=this.mapper.transform(u,Gn(n,{callbacks:t==null?void 0:t.getChild()})),c=d.next();for await(const h of o){if(typeof h!="object"||Array.isArray(h))throw new Error(`RunnableAssign can only be used with objects as input, got ${typeof h}`);const _=Object.fromEntries(Object.entries(h).filter(([y])=>!a.includes(y)));Object.keys(_).length>0&&(yield _)}yield(await c).value;for await(const h of d)yield h}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*n(){yield e}const a=qr(t),o=new Gl({generator:this.transform(n(),a),config:a});return await o.setup,vs.fromAsyncGenerator(o)}}class zI extends Jn{static lc_name(){return"RunnablePick"}constructor(e){(typeof e=="string"||Array.isArray(e))&&(e={keys:e}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"keys",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.keys=e.keys}async _pick(e){if(typeof this.keys=="string")return e[this.keys];{const t=this.keys.map(n=>[n,e[n]]).filter(n=>n[1]!==void 0);return t.length===0?void 0:Object.fromEntries(t)}}async invoke(e,t){return this._callWithConfig(this._pick.bind(this),e,t)}async*_transform(e){for await(const t of e){const n=await this._pick(t);n!==void 0&&(yield n)}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*n(){yield e}const a=qr(t),o=new Gl({generator:this.transform(n(),a),config:a});return await o.setup,vs.fromAsyncGenerator(o)}}class ew extends vo{constructor(e){const t=bo.from([U_.from(async n=>{let a;if(hk(n))try{a=await this.schema.parseAsync(n.args)}catch{throw new fk("Received tool input did not match expected schema",JSON.stringify(n.args))}else a=n;return a}).withConfig({runName:`${e.name}:parse_input`}),e.bound]).withConfig({runName:e.name});super({bound:t,config:e.config??{}}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"description",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"schema",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=e.name,this.description=e.description,this.schema=e.schema}static lc_name(){return"RunnableToolLike"}}function UI(r,e){var a;const t=e.name??r.getName(),n=e.description??((a=e.schema)==null?void 0:a.description);return e.schema.constructor===sp.ZodString?new ew({name:t,description:n,schema:sp.object({input:sp.string()}).transform(o=>o.input),bound:r}):new ew({name:t,description:n,schema:e.schema,bound:r})}class VI extends Jn{constructor(){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","documents","transformers"]})}invoke(e,t){return this.transformDocuments(e)}}var V_={};V_.byteLength=HI;V_.toByteArray=qI;V_.fromByteArray=XI;var Ea=[],Os=[],WI=typeof Uint8Array<"u"?Uint8Array:Array,t0="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var Tl=0,GI=t0.length;Tl0)throw new Error("Invalid string. Length must be a multiple of 4");var t=r.indexOf("=");t===-1&&(t=e);var n=t===e?0:4-t%4;return[t,n]}function HI(r){var e=Fv(r),t=e[0],n=e[1];return(t+n)*3/4-n}function KI(r,e,t){return(e+t)*3/4-t}function qI(r){var e,t=Fv(r),n=t[0],a=t[1],o=new WI(KI(r,n,a)),u=0,d=a>0?n-4:n,c;for(c=0;c>16&255,o[u++]=e>>8&255,o[u++]=e&255;return a===2&&(e=Os[r.charCodeAt(c)]<<2|Os[r.charCodeAt(c+1)]>>4,o[u++]=e&255),a===1&&(e=Os[r.charCodeAt(c)]<<10|Os[r.charCodeAt(c+1)]<<4|Os[r.charCodeAt(c+2)]>>2,o[u++]=e>>8&255,o[u++]=e&255),o}function ZI(r){return Ea[r>>18&63]+Ea[r>>12&63]+Ea[r>>6&63]+Ea[r&63]}function YI(r,e,t){for(var n,a=[],o=e;od?d:u+o));return n===1?(e=r[t-1],a.push(Ea[e>>2]+Ea[e<<4&63]+"==")):n===2&&(e=(r[t-2]<<8)+r[t-1],a.push(Ea[e>>10]+Ea[e>>4&63]+Ea[e<<2&63]+"=")),a.join("")}var QI=Object.defineProperty,JI=(r,e,t)=>e in r?QI(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,e$=(r,e,t)=>(JI(r,e+"",t),t);function t$(r,e){let t=Array.from({length:r.length},(n,a)=>({start:a,end:a+1}));for(;t.length>1;){let n=null;for(let a=0;ae.get(r.slice(t.start,t.end).join(","))).filter(t=>t!=null)}function n$(r){return r.replace(/[\\^$*+?.()|[\]{}]/g,"\\$&")}var E0=class{constructor(r,e){we(this,"specialTokens");we(this,"inverseSpecialTokens");we(this,"patStr");we(this,"textEncoder",new TextEncoder);we(this,"textDecoder",new TextDecoder("utf-8"));we(this,"rankMap",new Map);we(this,"textMap",new Map);this.patStr=r.pat_str;const t=r.bpe_ranks.split(` `).filter(Boolean).reduce((n,a)=>{const[o,u,...d]=a.split(" "),c=Number.parseInt(u,10);return d.forEach((h,_)=>n[h]=c+_),n},{});for(const[n,a]of Object.entries(t)){const o=V_.toByteArray(n);this.rankMap.set(o.join(","),a),this.textMap.set(a,o)}this.specialTokens={...r.special_tokens,...e},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((n,[a,o])=>(n[o]=this.textEncoder.encode(a),n),{})}encode(r,e=[],t="all"){const n=new RegExp(this.patStr,"ug"),a=E0.specialTokenRegex(Object.keys(this.specialTokens)),o=[],u=new Set(e==="all"?Object.keys(this.specialTokens):e),d=new Set(t==="all"?Object.keys(this.specialTokens).filter(h=>!u.has(h)):t);if(d.size>0){const h=E0.specialTokenRegex([...d]),_=r.match(h);if(_!=null)throw new Error(`The text contains a special token that is not allowed: ${_[0]}`)}let c=0;for(;;){let h=null,_=c;for(;a.lastIndex=_,h=a.exec(r),!(h==null||u.has(h[0]));)_=h.index+1;const y=(h==null?void 0:h.index)??r.length;for(const M of r.substring(c,y).matchAll(n)){const S=this.textEncoder.encode(M[0]),G=this.rankMap.get(S.join(","));if(G!=null){o.push(G);continue}o.push(...r$(S,this.rankMap))}if(h==null)break;let w=this.specialTokens[h[0]];o.push(w),c=h.index+h[0].length}return o}decode(r){const e=[];let t=0;for(let o=0;onew RegExp(r.map(e=>n$(e)).join("|"),"g"));class a$ extends VI{constructor(e){if(super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","document_transformers","text_splitters"]}),Object.defineProperty(this,"chunkSize",{enumerable:!0,configurable:!0,writable:!0,value:1e3}),Object.defineProperty(this,"chunkOverlap",{enumerable:!0,configurable:!0,writable:!0,value:200}),Object.defineProperty(this,"keepSeparator",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lengthFunction",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.chunkSize=(e==null?void 0:e.chunkSize)??this.chunkSize,this.chunkOverlap=(e==null?void 0:e.chunkOverlap)??this.chunkOverlap,this.keepSeparator=(e==null?void 0:e.keepSeparator)??this.keepSeparator,this.lengthFunction=(e==null?void 0:e.lengthFunction)??(t=>t.length),this.chunkOverlap>=this.chunkSize)throw new Error("Cannot have chunkOverlap >= chunkSize")}async transformDocuments(e,t={}){return this.splitDocuments(e,t)}splitOnSeparator(e,t){let n;if(t)if(this.keepSeparator){const a=t.replace(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&");n=e.split(new RegExp(`(?=${a})`))}else n=e.split(t);else n=e.split("");return n.filter(a=>a!=="")}async createDocuments(e,t=[],n={}){const a=t.length>0?t:[...Array(e.length)].map(()=>({})),{chunkHeader:o="",chunkOverlapHeader:u="(cont'd) ",appendChunkOverlapHeader:d=!1}=n,c=new Array;for(let h=0;hH){const I=this.numberOfNewLines(_,H,F);y-=I}d&&(G+=u)}const B=this.numberOfNewLines(S),z=a[h].loc&&typeof a[h].loc=="object"?{...a[h].loc}:{};z.lines={from:y,to:y+B};const U={...a[h],loc:z};G+=S,c.push(new Uw({pageContent:G,metadata:U})),y+=B,w=S,M=H}}return c}numberOfNewLines(e,t,n){return(e.slice(t,n).match(/\n/g)||[]).length}async splitDocuments(e,t={}){const n=e.filter(u=>u.pageContent!==void 0),a=n.map(u=>u.pageContent),o=n.map(u=>u.metadata);return this.createDocuments(a,o,t)}joinDocs(e,t){const n=e.join(t).trim();return n===""?null:n}async mergeSplits(e,t){const n=[],a=[];let o=0;for(const d of e){const c=await this.lengthFunction(d);if(o+c+a.length*t.length>this.chunkSize&&(o>this.chunkSize&&console.warn(`Created a chunk of size ${o}, + which is longer than the specified ${this.chunkSize}`),a.length>0)){const h=this.joinDocs(a,t);for(h!==null&&n.push(h);o>this.chunkOverlap||o+c+a.length*t.length>this.chunkSize&&o>0;)o-=await this.lengthFunction(a[0]),a.shift()}a.push(d),o+=c}const u=this.joinDocs(a,t);return u!==null&&n.push(u),n}}class i$ extends a${static lc_name(){return"CharacterTextSplitter"}constructor(e){super(e),Object.defineProperty(this,"separator",{enumerable:!0,configurable:!0,writable:!0,value:` `}),this.separator=(e==null?void 0:e.separator)??this.separator}async splitText(e){const t=this.splitOnSeparator(e,this.separator);return this.mergeSplits(t,this.keepSeparator?"":this.separator)}}class o${async loadAndSplit(e){if(e===void 0)throw new Error("You must pass a text splitter to use this method.");const t=await this.load();return e.invoke(t)}}class nb extends o${constructor(e){super(),Object.defineProperty(this,"filePathOrBlob",{enumerable:!0,configurable:!0,writable:!0,value:e})}async parse(e){return[e]}async load(){let e,t;if(typeof this.filePathOrBlob=="string"){const{readFile:a}=await nb.imports();e=await a(this.filePathOrBlob,"utf8"),t={source:this.filePathOrBlob}}else e=await this.filePathOrBlob.text(),t={source:"blob",blobType:this.filePathOrBlob.type};const n=await this.parse(e);return n.forEach((a,o)=>{if(typeof a!="string")throw new Error(`Expected string, at position ${o} got ${typeof a}`)}),n.map((a,o)=>new Uw({pageContent:a,metadata:n.length===1?t:{...t,line:o+1}}))}static async imports(){try{const{readFile:e}=await import("./__vite-browser-external-l0sNRNKZ.js");return{readFile:e}}catch(e){throw console.error(e),new Error(`Failed to load fs/promises. TextLoader available only on environment 'node'. It appears you are running environment '${Mv()}'. See https:// for alternatives.`)}}}async function u$(r){console.log(r.size,r.type);const t=await new nb(r).load();return await new i$({chunkSize:500,chunkOverlap:50}).splitDocuments(t)}class cp{static async getInstance(e,t=null){return console.log("instance is : "),console.log(this.instance),this.instance===null&&(this.instance=_2(this.task,this.model,{progress_callback:t,dtype:"fp32",device:e})),this.instance}}we(cp,"task","feature-extraction"),we(cp,"model","Supabase/gte-small"),we(cp,"instance",null);async function sb(r,e){console.log("start embed"),console.log("get emb instance");const t=await r(e,{pooling:"mean",normalize:!0});return console.log("embed success"),Array.from(t.data)}class Nv{static async getInstance(e,t,n,a=null){return console.log("loading data from "+e),this.tokenizer??(this.tokenizer=f2.from_pretrained(e,{progress_callback:a})),this.model??(this.model=h2.from_pretrained(e,{dtype:n,device:t,progress_callback:a})),Promise.all([this.tokenizer,this.model])}}let r0;async function x_(){if(r0)return r0;const r=new c2("idb://browser-rag",{extensions:{vector:d2}});return await r.waitReady,r0=r,r}const Dv=async(r,e,t,n)=>await r.exec(` insert into embeddings (title , content, embedding) values ('${e}', '${t}', '[${n}]')`),l$=async(r,e,t=.8,n=3)=>(await r.query(` select * from embeddings -- The inner product is negative, so we negate match_threshold where embeddings.embedding <#> $1 < $2 -- Our embeddings are normalized to length 1, so cosine similarity -- and inner product will produce the same query results. -- Using inner product which can be computed faster. -- -- For the different distance functions, see https://github.com/pgvector/pgvector order by embeddings.embedding <#> $1 limit $3; `,[JSON.stringify(e),-Number(t),Number(n)])).rows;function Bv(r){const e=r.at(-1);let t="";return e.role=="user"&&(t=e.content),t}function c$(r){return Array.from({length:r},()=>Math.random().toString(36).charAt(2)).join("")}function d$(r,e,t,n){if(r=="HuggingFaceTB/SmolLM2-360M-Instruct"){let a=null;for(let d=e.length-1;d>=0;d--)if(e[d].role==="user"){a=e.splice(d,1)[0];break}const o=({retrievedContext:d,userQuery:c})=>` You are an AI assistant that enhances responses using relevant retrieved knowledge. Your goal is to generate accurate, concise, and well-structured answers based on both retrieved documents and general knowledge. Follow these rules strictly: 1. **Use Retrieved Knowledge First:** Always prioritize retrieved context when formulating answers. If the retrieved documents contain relevant information, synthesize a response based on them. 2. **Be Factual and Verifiable:** Provide only accurate and verifiable information. Avoid speculation or unverifiable claims. If uncertain, state the limitations clearly. 3. **Summarize and Synthesize:** Do not just repeat retrieved text—synthesize key points into a coherent, well-structured response. 4. **Be Concise Yet Informative:** Aim for clarity and efficiency. Avoid excessive verbosity, but provide enough detail to ensure a comprehensive answer. 5. **Cite Sources When Needed:** If the user asks for source details, provide references or indicate which retrieved documents were used. 6. **Maintain a Neutral Tone:** Do not introduce bias or personal opinions—stick to objective facts. ### **Retrieved Context:** ${d||"No relevant context found."} `;let u="";return t.forEach(d=>{u+=`<|context_item|>${d.content}<|context_item|>`}),e.push({role:"system",content:o({retrievedContext:u})}),a&&e.push(a),console.log(e),n.apply_chat_template(e,{add_generation_prompt:!0,return_dict:!0})}else if(r=="onnx-community/Pleias-Pico"){let o=`<|query_start|>${Bv(e)}<|query_end|>`;return t.forEach(u=>{o+=`<|source_start|><|source_id_start|>${u.id+c$(5)}<|source_id_end|>${u.content}<|source_end|>`}),o+="<|source_analysis_start|>",console.log(o),n(o,{add_generation_prompt:!0,return_dict:!0})}}let Ml=[],dp="webgpu";async function h$(){try{console.log("try to load gpu"),await navigator.gpu.requestAdapter()?console.log("webgpu ok !!!!!"):(console.log("webgpu not ok"),dp="wasm")}catch(r){console.log(r),dp="wasm"}}const Xm=new p2;async function f$(r){Ml.device=dp,console.log("generating with "+Ml.device);const[e,t]=await Nv.getInstance(Ml.model_id,dp,Ml.dtype),n=await x_(),a=Bv(r);self.postMessage({status:"side_notif",message:"Loading embedding model ..."});const o=await cp.getInstance(dp);self.postMessage({status:"side_notif",message:"embedding model ok"});const u=await sb(o,a),d=await l$(n,u),c=await d$(Ml.model_id,r,d,e);console.log(c);let h,_=0,y;const w=()=>{h??(h=performance.now()),_++>0&&(y=_/(performance.now()-h)*1e3)},M=z=>{self.postMessage({status:"update",output:z,tps:y,numTokens:_})},S=new m2(e,{skip_prompt:!0,skip_special_tokens:!0,callback_function:M,token_callback_function:w});self.postMessage({status:"start"});const{past_key_values:G,sequences:H}=await t.generate({...c,top_k:3,temperature:.1,max_new_tokens:4096,streamer:S,stopping_criteria:Xm,return_dict_in_generate:!0}),B=e.batch_decode(H,{skip_special_tokens:!0});self.postMessage({status:"complete",output:B})}async function p$(r){const e=await sb(r.content),t=await x_();await Dv(t,r.title,r.content,e)}async function m$(r){Ml=r,self.postMessage({status:"loading",data:"Loading model..."});const[e,t]=await Nv.getInstance(r.model_id,r.device,r.dtype,a=>{self.postMessage(a)});self.postMessage({status:"loading",data:"Compiling shaders and warming up model..."});const n=e("a");await t.generate({...n,max_new_tokens:1}),self.postMessage({status:"ready"})}self.addEventListener("message",async r=>{const{type:e,data:t}=r.data;switch(e){case"add_db":p$(t),self.postMessage({status:"db_update"});break;case"check":h$(),console.log("check");break;case"load":m$(t);break;case"generate":Xm.reset(),f$(t);break;case"interrupt":Xm.interrupt();break;case"add_pdf":self.postMessage({status:"start_embedding"}),console.log(t);const n=await u$(t),a=await x_(),o=t.name;console.log(o);const u=await x_();await Promise.all(n.map(async(c,h)=>{self.postMessage({status:"side_notif",message:"Loading embedding model ..."});const _=await cp.getInstance();self.postMessage({status:"side_notif",message:"embedding model ok"}),self.postMessage({status:"side_notif",message:`embedding ${o}...`});const y=await sb(_,c.pageContent);self.postMessage({status:"side_notif",message:`succes add of ${o}`}),await Dv(u,o,c.pageContent.replace(/'/g,""),y)}));const d=await a.query("SELECT DISTINCT title FROM embeddings;");self.postMessage({status:"db_update",rows:d.rows});break;case"reset":Xm.reset();break}});