@yuktishaalaa/yuktai 3.0.6 → 3.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,48 +1,9 @@
1
- "use strict";var y3=Object.create;var zi=Object.defineProperty;var D3=Object.getOwnPropertyDescriptor;var C3=Object.getOwnPropertyNames;var w3=Object.getPrototypeOf,N3=Object.prototype.hasOwnProperty;var u1=e=>t=>{var r=e[t];if(r)return r();throw new Error("Module not found in bundle: "+t)};var Qe=(e,t)=>()=>(e&&(t=e(e=0)),t);var ae=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),hl=(e,t)=>{for(var r in t)zi(e,r,{get:t[r],enumerable:!0})},d1=(e,t,r,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of C3(t))!N3.call(e,n)&&n!==r&&zi(e,n,{get:()=>t[n],enumerable:!(a=D3(t,n))||a.enumerable});return e};var Dr=(e,t,r)=>(r=e!=null?y3(w3(e)):{},d1(t||!e||!e.__esModule?zi(r,"default",{value:e,enumerable:!0}):r,e)),B3=e=>d1(zi({},"__esModule",{value:!0}),e);var O1={};hl(O1,{askPage:()=>Tl});function n5(){return new Promise(e=>{let t=setTimeout(e,1500),r=new MutationObserver(()=>{clearTimeout(t),t=setTimeout(()=>{r.disconnect(),e()},500)});r.observe(document.body,{childList:!0,subtree:!0})})}function s5(){let e=[],t=document.querySelectorAll("*");for(let r of t){if(r.closest("[data-yuktai-panel]"))continue;let a=r.innerText?.trim();a&&a.length>30&&e.push(a);let n=r.getAttribute("aria-label");if(n&&n.length>10&&e.push(n),(r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement)&&(r.placeholder&&e.push(r.placeholder),r.value&&e.push(r.value)),r instanceof HTMLButtonElement){let s=r.innerText||r.getAttribute("aria-label");s&&e.push(s)}}return e.join(" ").slice(0,3500)}async function Tl(e){if(!e.trim())return{success:!1,answer:"",error:"Please type a question."};try{let t=window,r=t.LanguageModel||t.ai?.languageModel;if(!r)return{success:!1,answer:"",error:"Gemini Nano not available."};await n5();let a=s5();if(!a||a.length<100)return{success:!1,answer:"",error:"Page content not readable."};let n;try{n=await r.create({systemPrompt:`Answer ONLY using page content.
1
+ "use strict";var dt=Object.create;var X=Object.defineProperty;var ut=Object.getOwnPropertyDescriptor;var pt=Object.getOwnPropertyNames;var ft=Object.getPrototypeOf,mt=Object.prototype.hasOwnProperty;var gt=(e,t)=>()=>(e&&(t=e(e=0)),t);var Ce=(e,t)=>{for(var a in t)X(e,a,{get:t[a],enumerable:!0})},Le=(e,t,a,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of pt(t))!mt.call(e,n)&&n!==a&&X(e,n,{get:()=>t[n],enumerable:!(i=ut(t,n))||i.enumerable});return e};var Me=(e,t,a)=>(a=e!=null?dt(ft(e)):{},Le(t||!e||!e.__esModule?X(a,"default",{value:e,enumerable:!0}):a,e)),bt=e=>Le(X({},"__esModule",{value:!0}),e);var tt={};Ce(tt,{askPage:()=>ve});function Ot(){return new Promise(e=>{let t=setTimeout(e,1500),a=new MutationObserver(()=>{clearTimeout(t),t=setTimeout(()=>{a.disconnect(),e()},500)});a.observe(document.body,{childList:!0,subtree:!0})})}function qt(){let e=[],t=document.querySelectorAll("*");for(let a of t){if(a.closest("[data-yuktai-panel]"))continue;let i=a.innerText?.trim();i&&i.length>30&&e.push(i);let n=a.getAttribute("aria-label");if(n&&n.length>10&&e.push(n),(a instanceof HTMLInputElement||a instanceof HTMLTextAreaElement)&&(a.placeholder&&e.push(a.placeholder),a.value&&e.push(a.value)),a instanceof HTMLButtonElement){let s=a.innerText||a.getAttribute("aria-label");s&&e.push(s)}}return e.join(" ").slice(0,3500)}async function ve(e){if(!e.trim())return{success:!1,answer:"",error:"Please type a question."};try{let t=window,a=t.LanguageModel||t.ai?.languageModel;if(!a)return{success:!1,answer:"",error:"Gemini Nano not available."};await Ot();let i=qt();if(!i||i.length<100)return{success:!1,answer:"",error:"Page content not readable."};let n;try{n=await a.create({systemPrompt:`Answer ONLY using page content.
2
2
  Keep answer short (2\u20133 sentences).
3
- If not found say: "I could not find that on this page."`,outputLanguage:"en"})}catch{n=await r.create()}let s=`Page:
4
- ${a}
3
+ If not found say: "I could not find that on this page."`,outputLanguage:"en"})}catch{n=await a.create()}let s=`Page:
4
+ ${i}
5
5
 
6
- Q: ${e}`,i=await n.prompt(s);return n?.destroy&&n.destroy(),{success:!0,answer:i?.trim()||"No answer found."}}catch(t){return{success:!1,answer:"",error:t instanceof Error?t.message:"Error occurred"}}}var xl=Qe(()=>{"use strict"});var vl=ae(Bn=>{"use strict";Object.defineProperty(Bn,"__esModule",{value:!0});Bn.resolveBackendAndExecutionProviders=Bn.registerBackend=void 0;var so=new Map,Pa=[],i5=(e,t,r)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let a=so.get(e);if(a===void 0)so.set(e,{backend:t,priority:r});else{if(a.priority>r)return;if(a.priority===r&&a.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${r}`)}if(r>=0){let n=Pa.indexOf(e);n!==-1&&Pa.splice(n,1);for(let s=0;s<Pa.length;s++)if(so.get(Pa[s]).priority<=r){Pa.splice(s,0,e);return}Pa.push(e)}return}throw new TypeError("not a valid backend")};Bn.registerBackend=i5;var o5=async e=>{let t=so.get(e);if(!t)return"backend not found.";if(t.initialized)return t.backend;if(t.aborted)return t.error;{let r=!!t.initPromise;try{return r||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(a){return r||(t.error=`${a}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},H5=async e=>{let t=e.executionProviders||[],r=t.map(H=>typeof H=="string"?H:H.name),a=r.length===0?Pa:r,n,s=[],i=new Set;for(let H of a){let _=await o5(H);typeof _=="string"?s.push({name:H,err:_}):(n||(n=_),n===_&&i.add(H))}if(!n)throw new Error(`no available backend found. ERR: ${s.map(H=>`[${H.name}] ${H.err}`).join(", ")}`);for(let{name:H,err:_}of s)r.includes(H)&&console.warn(`removing requested execution provider "${H}" from session options because it is not available: ${_}`);let o=t.filter(H=>i.has(typeof H=="string"?H:H.name));return[n,new Proxy(e,{get:(H,_)=>_==="executionProviders"?o:Reflect.get(H,_)})]};Bn.resolveBackendAndExecutionProviders=H5});var G1=ae(io=>{"use strict";Object.defineProperty(io,"__esModule",{value:!0});io.registerBackend=void 0;var _5=vl();Object.defineProperty(io,"registerBackend",{enumerable:!0,get:function(){return _5.registerBackend}})});var F1=ae(oo=>{"use strict";Object.defineProperty(oo,"__esModule",{value:!0});oo.version=void 0;oo.version="1.24.3"});var yl=ae(Ps=>{"use strict";Object.defineProperty(Ps,"__esModule",{value:!0});Ps.env=void 0;var c5=F1(),Z1="warning";Ps.env={wasm:{},webgl:{},webgpu:{},versions:{common:c5.version},set logLevel(e){if(e!==void 0){if(typeof e!="string"||["verbose","info","warning","error","fatal"].indexOf(e)===-1)throw new Error(`Unsupported logging level: ${e}`);Z1=e}},get logLevel(){return Z1}};Object.defineProperty(Ps.env,"logLevel",{enumerable:!0})});var U1=ae(Ho=>{"use strict";Object.defineProperty(Ho,"__esModule",{value:!0});Ho.env=void 0;var l5=yl();Ho.env=l5.env});var W1=ae(Mn=>{"use strict";Object.defineProperty(Mn,"__esModule",{value:!0});Mn.tensorToImageData=Mn.tensorToDataURL=void 0;var u5=(e,t)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=e.dims[3],r.height=e.dims[2];let a=r.getContext("2d");if(a!=null){let n,s;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(n=e.dims[2],s=e.dims[3]):(n=e.dims[3],s=e.dims[2]);let i=t?.format!==void 0?t.format:"RGB",o=t?.norm,H,_;o===void 0||o.mean===void 0?H=[255,255,255,255]:typeof o.mean=="number"?H=[o.mean,o.mean,o.mean,o.mean]:(H=[o.mean[0],o.mean[1],o.mean[2],0],o.mean[3]!==void 0&&(H[3]=o.mean[3])),o===void 0||o.bias===void 0?_=[0,0,0,0]:typeof o.bias=="number"?_=[o.bias,o.bias,o.bias,o.bias]:(_=[o.bias[0],o.bias[1],o.bias[2],0],o.bias[3]!==void 0&&(_[3]=o.bias[3]));let c=s*n,l=0,d=c,h=c*2,$=-1;i==="RGBA"?(l=0,d=c,h=c*2,$=c*3):i==="RGB"?(l=0,d=c,h=c*2):i==="RBG"&&(l=0,h=c,d=c*2);for(let m=0;m<s;m++)for(let S=0;S<n;S++){let I=(e.data[l++]-_[0])*H[0],g=(e.data[d++]-_[1])*H[1],T=(e.data[h++]-_[2])*H[2],x=$===-1?255:(e.data[$++]-_[3])*H[3];a.fillStyle="rgba("+I+","+g+","+T+","+x+")",a.fillRect(S,m,1,1)}if("toDataURL"in r)return r.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")};Mn.tensorToDataURL=u5;var d5=(e,t)=>{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),a;if(r!=null){let n,s,i;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(n=e.dims[2],s=e.dims[1],i=e.dims[3]):(n=e.dims[3],s=e.dims[2],i=e.dims[1]);let o=t!==void 0&&t.format!==void 0?t.format:"RGB",H=t?.norm,_,c;H===void 0||H.mean===void 0?_=[255,255,255,255]:typeof H.mean=="number"?_=[H.mean,H.mean,H.mean,H.mean]:(_=[H.mean[0],H.mean[1],H.mean[2],255],H.mean[3]!==void 0&&(_[3]=H.mean[3])),H===void 0||H.bias===void 0?c=[0,0,0,0]:typeof H.bias=="number"?c=[H.bias,H.bias,H.bias,H.bias]:(c=[H.bias[0],H.bias[1],H.bias[2],0],H.bias[3]!==void 0&&(c[3]=H.bias[3]));let l=s*n;if(t!==void 0&&(t.format!==void 0&&i===4&&t.format!=="RGBA"||i===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let d=4,h=0,$=1,m=2,S=3,I=0,g=l,T=l*2,x=-1;o==="RGBA"?(I=0,g=l,T=l*2,x=l*3):o==="RGB"?(I=0,g=l,T=l*2):o==="RBG"&&(I=0,T=l,g=l*2),a=r.createImageData(n,s);for(let v=0;v<s*n;h+=d,$+=d,m+=d,S+=d,v++)a.data[h]=(e.data[I++]-c[0])*_[0],a.data[$]=(e.data[g++]-c[1])*_[1],a.data[m]=(e.data[T++]-c[2])*_[2],a.data[S]=x===-1?255:(e.data[x++]-c[3])*_[3]}else throw new Error("Can not access image data");return a};Mn.tensorToImageData=d5});var K1=ae(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.tensorFromPinnedBuffer=gt.tensorFromMLTensor=gt.tensorFromGpuBuffer=gt.tensorFromTexture=gt.tensorFromImage=gt.bufferToTensor=void 0;var Pn=_o(),p5=(e,t)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:a}=t,n=t.norm??{mean:255,bias:0},s,i;typeof n.mean=="number"?s=[n.mean,n.mean,n.mean,n.mean]:s=[n.mean[0],n.mean[1],n.mean[2],n.mean[3]??255],typeof n.bias=="number"?i=[n.bias,n.bias,n.bias,n.bias]:i=[n.bias[0],n.bias[1],n.bias[2],n.bias[3]??0];let o=t.format!==void 0?t.format:"RGBA",H=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",_=r*a,c=H==="RGBA"?new Float32Array(_*4):new Float32Array(_*3),l=4,d=0,h=1,$=2,m=3,S=0,I=_,g=_*2,T=-1;o==="RGB"&&(l=3,d=0,h=1,$=2,m=-1),H==="RGBA"?T=_*3:H==="RBG"?(S=0,g=_,I=_*2):H==="BGR"&&(g=0,I=_,S=_*2);for(let v=0;v<_;v++,d+=l,$+=l,h+=l,m+=l)c[S++]=(e[d]+i[0])/s[0],c[I++]=(e[h]+i[1])/s[1],c[g++]=(e[$]+i[2])/s[2],T!==-1&&m!==-1&&(c[T++]=(e[m]+i[3])/s[3]);return H==="RGBA"?new Pn.Tensor("float32",c,[1,4,r,a]):new Pn.Tensor("float32",c,[1,3,r,a])};gt.bufferToTensor=p5;var h5=async(e,t)=>{let r=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,a=typeof ImageData<"u"&&e instanceof ImageData,n=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,s=typeof e=="string",i,o=t??{},H=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},_=c=>typeof HTMLCanvasElement<"u"&&c instanceof HTMLCanvasElement||c instanceof OffscreenCanvas?c.getContext("2d"):null;if(r){let c=H();c.width=e.width,c.height=e.height;let l=_(c);if(l!=null){let d=e.height,h=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(d=t.resizedHeight,h=t.resizedWidth),t!==void 0){if(o=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");o.tensorFormat="RGBA",o.height=d,o.width=h}else o.tensorFormat="RGBA",o.height=d,o.width=h;l.drawImage(e,0,0),i=l.getImageData(0,0,h,d).data}else throw new Error("Can not access image data")}else if(a){let c,l;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(c=t.resizedHeight,l=t.resizedWidth):(c=e.height,l=e.width),t!==void 0&&(o=t),o.format="RGBA",o.height=c,o.width=l,t!==void 0){let d=H();d.width=l,d.height=c;let h=_(d);if(h!=null)h.putImageData(e,0,0),i=h.getImageData(0,0,l,c).data;else throw new Error("Can not access image data")}else i=e.data}else if(n){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let c=H();c.width=e.width,c.height=e.height;let l=_(c);if(l!=null){let d=e.height,h=e.width;return l.drawImage(e,0,0,h,d),i=l.getImageData(0,0,h,d).data,o.height=d,o.width=h,(0,gt.bufferToTensor)(i,o)}else throw new Error("Can not access image data")}else{if(s)return new Promise((c,l)=>{let d=H(),h=_(d);if(!e||!h)return l();let $=new Image;$.crossOrigin="Anonymous",$.src=e,$.onload=()=>{d.width=$.width,d.height=$.height,h.drawImage($,0,0,d.width,d.height);let m=h.getImageData(0,0,d.width,d.height);o.height=d.height,o.width=d.width,c((0,gt.bufferToTensor)(m.data,o))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(i!==void 0)return(0,gt.bufferToTensor)(i,o);throw new Error("Input data provided is not supported - aborted tensor creation")};gt.tensorFromImage=h5;var f5=(e,t)=>{let{width:r,height:a,download:n,dispose:s}=t,i=[1,a,r,4];return new Pn.Tensor({location:"texture",type:"float32",texture:e,dims:i,download:n,dispose:s})};gt.tensorFromTexture=f5;var E5=(e,t)=>{let{dataType:r,dims:a,download:n,dispose:s}=t;return new Pn.Tensor({location:"gpu-buffer",type:r??"float32",gpuBuffer:e,dims:a,download:n,dispose:s})};gt.tensorFromGpuBuffer=E5;var $5=(e,t)=>{let{dataType:r,dims:a,download:n,dispose:s}=t;return new Pn.Tensor({location:"ml-tensor",type:r??"float32",mlTensor:e,dims:a,download:n,dispose:s})};gt.tensorFromMLTensor=$5;var m5=(e,t,r)=>new Pn.Tensor({location:"cpu-pinned",type:e,data:t,dims:r??[t.length]});gt.tensorFromPinnedBuffer=m5});var j1=ae(Rt=>{"use strict";Object.defineProperty(Rt,"__esModule",{value:!0});Rt.checkTypedArray=Rt.NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP=Rt.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP=void 0;Rt.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]);Rt.NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);var V1=!1,I5=()=>{if(!V1){V1=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,a=typeof r<"u"&&r.from;e&&(Rt.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set("int64",BigInt64Array),Rt.NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigInt64Array,"int64")),t&&(Rt.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set("uint64",BigUint64Array),Rt.NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigUint64Array,"uint64")),a?(Rt.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set("float16",r),Rt.NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(r,"float16")):Rt.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set("float16",Uint16Array)}};Rt.checkTypedArray=I5});var q1=ae(kn=>{"use strict";Object.defineProperty(kn,"__esModule",{value:!0});kn.tensorReshape=kn.calculateSize=void 0;var ks=_o(),S5=e=>{let t=1;for(let r=0;r<e.length;r++){let a=e[r];if(typeof a!="number"||!Number.isSafeInteger(a))throw new TypeError(`dims[${r}] must be an integer, got: ${a}`);if(a<0)throw new RangeError(`dims[${r}] must be a non-negative integer, got: ${a}`);t*=a}return t};kn.calculateSize=S5;var L5=(e,t)=>{switch(e.location){case"cpu":return new ks.Tensor(e.type,e.data,t);case"cpu-pinned":return new ks.Tensor({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new ks.Tensor({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new ks.Tensor({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new ks.Tensor({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}};kn.tensorReshape=L5});var _o=ae(lo=>{"use strict";Object.defineProperty(lo,"__esModule",{value:!0});lo.Tensor=void 0;var X1=W1(),Rs=K1(),co=j1(),z1=q1(),Dl=class{constructor(t,r,a){(0,co.checkTypedArray)();let n,s;if(typeof t=="object"&&"location"in t)switch(this.dataLocation=t.location,n=t.type,s=t.dims,t.location){case"cpu-pinned":{let o=co.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(n);if(!o)throw new TypeError(`unsupported type "${n}" to create tensor from pinned buffer`);if(!(t.data instanceof o))throw new TypeError(`buffer should be of type ${o.name}`);this.cpuData=t.data;break}case"texture":{if(n!=="float32")throw new TypeError(`unsupported type "${n}" to create tensor from texture`);this.gpuTextureData=t.texture,this.downloader=t.download,this.disposer=t.dispose;break}case"gpu-buffer":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from gpu buffer`);this.gpuBufferData=t.gpuBuffer,this.downloader=t.download,this.disposer=t.dispose;break}case"ml-tensor":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint64"&&n!=="int8"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from MLTensor`);this.mlTensorData=t.mlTensor,this.downloader=t.download,this.disposer=t.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let o,H;if(typeof t=="string")if(n=t,H=a,t==="string"){if(!Array.isArray(r))throw new TypeError("A string tensor's data must be a string array.");o=r}else{let _=co.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(t);if(_===void 0)throw new TypeError(`Unsupported tensor type: ${t}.`);if(Array.isArray(r)){if(t==="float16"&&_===Uint16Array||t==="uint4"||t==="int4")throw new TypeError(`Creating a ${t} tensor from number array is not supported. Please use ${_.name} as data.`);t==="uint64"||t==="int64"?o=_.from(r,BigInt):o=_.from(r)}else if(r instanceof _)o=r;else if(r instanceof Uint8ClampedArray)if(t==="uint8")o=Uint8Array.from(r);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(t==="float16"&&r instanceof Uint16Array&&_!==Uint16Array)o=new globalThis.Float16Array(r.buffer,r.byteOffset,r.length);else throw new TypeError(`A ${n} tensor's data must be type of ${_}`)}else if(H=r,Array.isArray(t)){if(t.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let _=typeof t[0];if(_==="string")n="string",o=t;else if(_==="boolean")n="bool",o=Uint8Array.from(t);else throw new TypeError(`Invalid element type of data array: ${_}.`)}else if(t instanceof Uint8ClampedArray)n="uint8",o=Uint8Array.from(t);else{let _=co.NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(t.constructor);if(_===void 0)throw new TypeError(`Unsupported type for tensor data: ${t.constructor}.`);n=_,o=t}if(H===void 0)H=[o.length];else if(!Array.isArray(H))throw new TypeError("A tensor's dims must be a number array");s=H,this.cpuData=o,this.dataLocation="cpu"}let i=(0,z1.calculateSize)(s);if(this.cpuData&&i!==this.cpuData.length&&!((n==="uint4"||n==="int4")&&Math.ceil(i/2)===this.cpuData.length))throw new Error(`Tensor's size(${i}) does not match data length(${this.cpuData.length}).`);this.type=n,this.dims=s,this.size=i}static async fromImage(t,r){return(0,Rs.tensorFromImage)(t,r)}static fromTexture(t,r){return(0,Rs.tensorFromTexture)(t,r)}static fromGpuBuffer(t,r){return(0,Rs.tensorFromGpuBuffer)(t,r)}static fromMLTensor(t,r){return(0,Rs.tensorFromMLTensor)(t,r)}static fromPinnedBuffer(t,r,a){return(0,Rs.tensorFromPinnedBuffer)(t,r,a)}toDataURL(t){return(0,X1.tensorToDataURL)(this,t)}toImageData(t){return(0,X1.tensorToImageData)(this,t)}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(t){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 r=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=r,t&&this.disposer&&(this.disposer(),this.disposer=void 0),r}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(t){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return(0,z1.tensorReshape)(this,t)}};lo.Tensor=Dl});var Cl=ae(uo=>{"use strict";Object.defineProperty(uo,"__esModule",{value:!0});uo.Tensor=void 0;var A5=_o();uo.Tensor=A5.Tensor});var wl=ae(Qt=>{"use strict";Object.defineProperty(Qt,"__esModule",{value:!0});Qt.TRACE_EVENT_END=Qt.TRACE_EVENT_BEGIN=Qt.TRACE_FUNC_END=Qt.TRACE_FUNC_BEGIN=Qt.TRACE=void 0;var Ot=yl(),g5=(e,t)=>{(typeof Ot.env.trace>"u"?!Ot.env.wasm.trace:!Ot.env.trace)||console.timeStamp(`${e}::ORT::${t}`)};Qt.TRACE=g5;var J1=(e,t)=>{let r=new Error().stack?.split(/\r\n|\r|\n/g)||[],a=!1;for(let n=0;n<r.length;n++){if(a&&!r[n].includes("TRACE_FUNC")){let s=`FUNC_${e}::${r[n].trim().split(" ")[1]}`;t&&(s+=`::${t}`),(0,Qt.TRACE)("CPU",s);return}r[n].includes("TRACE_FUNC")&&(a=!0)}},b5=e=>{(typeof Ot.env.trace>"u"?!Ot.env.wasm.trace:!Ot.env.trace)||J1("BEGIN",e)};Qt.TRACE_FUNC_BEGIN=b5;var T5=e=>{(typeof Ot.env.trace>"u"?!Ot.env.wasm.trace:!Ot.env.trace)||J1("END",e)};Qt.TRACE_FUNC_END=T5;var x5=e=>{(typeof Ot.env.trace>"u"?!Ot.env.wasm.trace:!Ot.env.trace)||console.time(`ORT::${e}`)};Qt.TRACE_EVENT_BEGIN=x5;var v5=e=>{(typeof Ot.env.trace>"u"?!Ot.env.wasm.trace:!Ot.env.trace)||console.timeEnd(`ORT::${e}`)};Qt.TRACE_EVENT_END=v5});var Q1=ae(po=>{"use strict";Object.defineProperty(po,"__esModule",{value:!0});po.InferenceSession=void 0;var y5=vl(),Os=Cl(),fa=wl(),Nl=class e{constructor(t){this.handler=t}async run(t,r,a){(0,fa.TRACE_FUNC_BEGIN)(),(0,fa.TRACE_EVENT_BEGIN)("InferenceSession.run");let n={},s={};if(typeof t!="object"||t===null||t instanceof Os.Tensor||Array.isArray(t))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let i=!0;if(typeof r=="object"){if(r===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof Os.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(r)){if(r.length===0)throw new TypeError("'fetches' cannot be an empty array.");i=!1;for(let _ of r){if(typeof _!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(_)===-1)throw new RangeError(`'fetches' contains invalid output name: ${_}.`);n[_]=null}if(typeof a=="object"&&a!==null)s=a;else if(typeof a<"u")throw new TypeError("'options' must be an object.")}else{let _=!1,c=Object.getOwnPropertyNames(r);for(let l of this.outputNames)if(c.indexOf(l)!==-1){let d=r[l];(d===null||d instanceof Os.Tensor)&&(_=!0,i=!1,n[l]=d)}if(_){if(typeof a=="object"&&a!==null)s=a;else if(typeof a<"u")throw new TypeError("'options' must be an object.")}else s=r}}else if(typeof r<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let _ of this.inputNames)if(typeof t[_]>"u")throw new Error(`input '${_}' is missing in 'feeds'.`);if(i)for(let _ of this.outputNames)n[_]=null;let o=await this.handler.run(t,n,s),H={};for(let _ in o)if(Object.hasOwnProperty.call(o,_)){let c=o[_];c instanceof Os.Tensor?H[_]=c:H[_]=new Os.Tensor(c.type,c.data,c.dims)}return(0,fa.TRACE_EVENT_END)("InferenceSession.run"),(0,fa.TRACE_FUNC_END)(),H}async release(){return this.handler.dispose()}static async create(t,r,a,n){(0,fa.TRACE_FUNC_BEGIN)(),(0,fa.TRACE_EVENT_BEGIN)("InferenceSession.create");let s,i={};if(typeof t=="string"){if(s=t,typeof r=="object"&&r!==null)i=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(s=t,typeof r=="object"&&r!==null)i=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer){let c=t,l=0,d=t.byteLength;if(typeof r=="object"&&r!==null)i=r;else if(typeof r=="number"){if(l=r,!Number.isSafeInteger(l))throw new RangeError("'byteOffset' must be an integer.");if(l<0||l>=c.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${c.byteLength}).`);if(d=t.byteLength-l,typeof a=="number"){if(d=a,!Number.isSafeInteger(d))throw new RangeError("'byteLength' must be an integer.");if(d<=0||l+d>c.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${c.byteLength-l}].`);if(typeof n=="object"&&n!==null)i=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(typeof a<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof r<"u")throw new TypeError("'options' must be an object.");s=new Uint8Array(c,l,d)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[o,H]=await(0,y5.resolveBackendAndExecutionProviders)(i),_=await o.createInferenceSessionHandler(s,H);return(0,fa.TRACE_EVENT_END)("InferenceSession.create"),(0,fa.TRACE_FUNC_END)(),new e(_)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}};po.InferenceSession=Nl});var Y1=ae(ho=>{"use strict";Object.defineProperty(ho,"__esModule",{value:!0});ho.InferenceSession=void 0;var D5=Q1();ho.InferenceSession=D5.InferenceSession});var t$=ae(e$=>{"use strict";Object.defineProperty(e$,"__esModule",{value:!0})});var a$=ae(r$=>{"use strict";Object.defineProperty(r$,"__esModule",{value:!0})});var s$=ae(n$=>{"use strict";Object.defineProperty(n$,"__esModule",{value:!0})});var o$=ae(i$=>{"use strict";Object.defineProperty(i$,"__esModule",{value:!0})});var fo=ae(Gt=>{"use strict";var C5=Gt&&Gt.__createBinding||(Object.create?(function(e,t,r,a){a===void 0&&(a=r);var n=Object.getOwnPropertyDescriptor(t,r);(!n||("get"in n?!t.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,a,n)}):(function(e,t,r,a){a===void 0&&(a=r),e[a]=t[r]})),ta=Gt&&Gt.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&C5(t,e,r)};Object.defineProperty(Gt,"__esModule",{value:!0});ta(G1(),Gt);ta(U1(),Gt);ta(Y1(),Gt);ta(Cl(),Gt);ta(t$(),Gt);ta(a$(),Gt);ta(wl(),Gt);ta(s$(),Gt);ta(o$(),Gt)});var H$=ae((OU,w5)=>{w5.exports="./onnxruntime_binding-EKZT2NRK.node"});var _$=ae((GU,N5)=>{N5.exports="./onnxruntime_binding-6Q6HXASN.node"});var c$=ae((FU,B5)=>{B5.exports="./onnxruntime_binding-UN6SPTQK.node"});var l$=ae((ZU,M5)=>{M5.exports="./onnxruntime_binding-PJNNIIUO.node"});var u$=ae((UU,P5)=>{P5.exports="./onnxruntime_binding-P6S7V3CI.node"});var k5,Bl=Qe(()=>{k5=u1({"../bin/napi-v6/darwin/arm64/onnxruntime_binding.node":()=>H$(),"../bin/napi-v6/linux/arm64/onnxruntime_binding.node":()=>_$(),"../bin/napi-v6/linux/x64/onnxruntime_binding.node":()=>c$(),"../bin/napi-v6/win32/arm64/onnxruntime_binding.node":()=>l$(),"../bin/napi-v6/win32/x64/onnxruntime_binding.node":()=>u$()})});var p$=ae(ka=>{"use strict";Bl();Object.defineProperty(ka,"__esModule",{value:!0});ka.initOrt=ka.binding=void 0;var Eo=fo();ka.binding=k5(`../bin/napi-v6/${process.platform}/${process.arch}/onnxruntime_binding.node`);var d$=!1,R5=()=>{if(!d$){d$=!0;let e=2;if(Eo.env.logLevel)switch(Eo.env.logLevel){case"verbose":e=0;break;case"info":e=1;break;case"warning":e=2;break;case"error":e=3;break;case"fatal":e=4;break;default:throw new Error(`Unsupported log level: ${Eo.env.logLevel}`)}ka.binding.initOrtOnce(e,Eo.Tensor)}};ka.initOrt=R5});var Rl=ae(wr=>{"use strict";var O5=wr&&wr.__classPrivateFieldSet||function(e,t,r,a,n){if(a==="m")throw new TypeError("Private method is not writable");if(a==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return a==="a"?n.call(e,r):n?n.value=r:t.set(e,r),r},Ra=wr&&wr.__classPrivateFieldGet||function(e,t,r,a){if(r==="a"&&!a)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!a:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?a:r==="a"?a.call(e):a?a.value:t.get(e)},Cr;Object.defineProperty(wr,"__esModule",{value:!0});wr.listSupportedBackends=wr.onnxruntimeBackend=void 0;var Ml=p$(),G5=[void 0,"float32","uint8","int8","uint16","int16","int32","int64","string","bool","float16","float64","uint32","uint64",void 0,void 0,void 0,void 0,void 0,void 0,void 0,"uint4","int4"],Pl=class{constructor(t,r){Cr.set(this,void 0),(0,Ml.initOrt)(),O5(this,Cr,new Ml.binding.InferenceSession,"f"),typeof t=="string"?Ra(this,Cr,"f").loadModel(t,r):Ra(this,Cr,"f").loadModel(t.buffer,t.byteOffset,t.byteLength,r),this.inputNames=[],this.outputNames=[],this.inputMetadata=[],this.outputMetadata=[];let a=n=>{let s=[],i=[];for(let o of n)if(s.push(o.name),!o.isTensor)i.push({name:o.name,isTensor:!1});else{let H=G5[o.type];if(H===void 0)throw new Error(`Unsupported data type: ${o.type}`);let _=[];for(let c=0;c<o.shape.length;++c){let l=o.shape[c];if(l===-1)_.push(o.symbolicDimensions[c]);else if(l>=0)_.push(l);else throw new Error(`Invalid dimension: ${l}`)}i.push({name:o.name,isTensor:o.isTensor,type:H,shape:_})}return[s,i]};[this.inputNames,this.inputMetadata]=a(Ra(this,Cr,"f").inputMetadata),[this.outputNames,this.outputMetadata]=a(Ra(this,Cr,"f").outputMetadata)}async dispose(){Ra(this,Cr,"f").dispose()}startProfiling(){}endProfiling(){Ra(this,Cr,"f").endProfiling()}async run(t,r,a){return new Promise((n,s)=>{setImmediate(()=>{try{n(Ra(this,Cr,"f").run(t,r,a))}catch(i){s(i)}})})}};Cr=new WeakMap;var kl=class{async init(){return Promise.resolve()}async createInferenceSessionHandler(t,r){return new Promise((a,n)=>{setImmediate(()=>{try{a(new Pl(t,r||{}))}catch(s){n(s)}})})}};wr.onnxruntimeBackend=new kl;wr.listSupportedBackends=Ml.binding.listSupportedBackends});var h$=ae($o=>{"use strict";Object.defineProperty($o,"__esModule",{value:!0});$o.version=void 0;$o.version="1.24.3"});var $$=ae(ra=>{"use strict";var F5=ra&&ra.__createBinding||(Object.create?(function(e,t,r,a){a===void 0&&(a=r);var n=Object.getOwnPropertyDescriptor(t,r);(!n||("get"in n?!t.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,a,n)}):(function(e,t,r,a){a===void 0&&(a=r),e[a]=t[r]})),Z5=ra&&ra.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&F5(t,e,r)};Object.defineProperty(ra,"__esModule",{value:!0});ra.listSupportedBackends=void 0;Z5(fo(),ra);var U5=Rl();Object.defineProperty(ra,"listSupportedBackends",{enumerable:!0,get:function(){return U5.listSupportedBackends}});var f$=fo(),W5=h$(),E$=Rl(),K5=(0,E$.listSupportedBackends)();for(let e of K5)(0,f$.registerBackend)(e.name,E$.onnxruntimeBackend,100);Object.defineProperty(f$.env.versions,"node",{value:W5.version,enumerable:!0})});var Ol=Qe(()=>{"use strict"});var m$=Qe(()=>{"use strict";Ol()});var I$,S$=Qe(()=>{"use strict";I$="1.24.3"});var L$,Gl,Fl=Qe(()=>{"use strict";S$();L$="warning",Gl={wasm:{},webgl:{},webgpu:{},versions:{common:I$},set logLevel(e){if(e!==void 0){if(typeof e!="string"||["verbose","info","warning","error","fatal"].indexOf(e)===-1)throw new Error(`Unsupported logging level: ${e}`);L$=e}},get logLevel(){return L$}};Object.defineProperty(Gl,"logLevel",{enumerable:!0})});var A$=Qe(()=>{"use strict";Fl()});var g$,b$,T$=Qe(()=>{"use strict";g$=(e,t)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=e.dims[3],r.height=e.dims[2];let a=r.getContext("2d");if(a!=null){let n,s;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(n=e.dims[2],s=e.dims[3]):(n=e.dims[3],s=e.dims[2]);let i=t?.format!==void 0?t.format:"RGB",o=t?.norm,H,_;o===void 0||o.mean===void 0?H=[255,255,255,255]:typeof o.mean=="number"?H=[o.mean,o.mean,o.mean,o.mean]:(H=[o.mean[0],o.mean[1],o.mean[2],0],o.mean[3]!==void 0&&(H[3]=o.mean[3])),o===void 0||o.bias===void 0?_=[0,0,0,0]:typeof o.bias=="number"?_=[o.bias,o.bias,o.bias,o.bias]:(_=[o.bias[0],o.bias[1],o.bias[2],0],o.bias[3]!==void 0&&(_[3]=o.bias[3]));let c=s*n,l=0,d=c,h=c*2,$=-1;i==="RGBA"?(l=0,d=c,h=c*2,$=c*3):i==="RGB"?(l=0,d=c,h=c*2):i==="RBG"&&(l=0,h=c,d=c*2);for(let m=0;m<s;m++)for(let S=0;S<n;S++){let I=(e.data[l++]-_[0])*H[0],g=(e.data[d++]-_[1])*H[1],T=(e.data[h++]-_[2])*H[2],x=$===-1?255:(e.data[$++]-_[3])*H[3];a.fillStyle="rgba("+I+","+g+","+T+","+x+")",a.fillRect(S,m,1,1)}if("toDataURL"in r)return r.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},b$=(e,t)=>{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),a;if(r!=null){let n,s,i;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(n=e.dims[2],s=e.dims[1],i=e.dims[3]):(n=e.dims[3],s=e.dims[2],i=e.dims[1]);let o=t!==void 0&&t.format!==void 0?t.format:"RGB",H=t?.norm,_,c;H===void 0||H.mean===void 0?_=[255,255,255,255]:typeof H.mean=="number"?_=[H.mean,H.mean,H.mean,H.mean]:(_=[H.mean[0],H.mean[1],H.mean[2],255],H.mean[3]!==void 0&&(_[3]=H.mean[3])),H===void 0||H.bias===void 0?c=[0,0,0,0]:typeof H.bias=="number"?c=[H.bias,H.bias,H.bias,H.bias]:(c=[H.bias[0],H.bias[1],H.bias[2],0],H.bias[3]!==void 0&&(c[3]=H.bias[3]));let l=s*n;if(t!==void 0&&(t.format!==void 0&&i===4&&t.format!=="RGBA"||i===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let d=4,h=0,$=1,m=2,S=3,I=0,g=l,T=l*2,x=-1;o==="RGBA"?(I=0,g=l,T=l*2,x=l*3):o==="RGB"?(I=0,g=l,T=l*2):o==="RBG"&&(I=0,T=l,g=l*2),a=r.createImageData(n,s);for(let v=0;v<s*n;h+=d,$+=d,m+=d,S+=d,v++)a.data[h]=(e.data[I++]-c[0])*_[0],a.data[$]=(e.data[g++]-c[1])*_[1],a.data[m]=(e.data[T++]-c[2])*_[2],a.data[S]=x===-1?255:(e.data[x++]-c[3])*_[3]}else throw new Error("Can not access image data");return a}});var Zl,x$,v$,y$,D$,C$,w$=Qe(()=>{"use strict";mo();Zl=(e,t)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:a}=t,n=t.norm??{mean:255,bias:0},s,i;typeof n.mean=="number"?s=[n.mean,n.mean,n.mean,n.mean]:s=[n.mean[0],n.mean[1],n.mean[2],n.mean[3]??255],typeof n.bias=="number"?i=[n.bias,n.bias,n.bias,n.bias]:i=[n.bias[0],n.bias[1],n.bias[2],n.bias[3]??0];let o=t.format!==void 0?t.format:"RGBA",H=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",_=r*a,c=H==="RGBA"?new Float32Array(_*4):new Float32Array(_*3),l=4,d=0,h=1,$=2,m=3,S=0,I=_,g=_*2,T=-1;o==="RGB"&&(l=3,d=0,h=1,$=2,m=-1),H==="RGBA"?T=_*3:H==="RBG"?(S=0,g=_,I=_*2):H==="BGR"&&(g=0,I=_,S=_*2);for(let v=0;v<_;v++,d+=l,$+=l,h+=l,m+=l)c[S++]=(e[d]+i[0])/s[0],c[I++]=(e[h]+i[1])/s[1],c[g++]=(e[$]+i[2])/s[2],T!==-1&&m!==-1&&(c[T++]=(e[m]+i[3])/s[3]);return H==="RGBA"?new bt("float32",c,[1,4,r,a]):new bt("float32",c,[1,3,r,a])},x$=async(e,t)=>{let r=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,a=typeof ImageData<"u"&&e instanceof ImageData,n=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,s=typeof e=="string",i,o=t??{},H=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},_=c=>typeof HTMLCanvasElement<"u"&&c instanceof HTMLCanvasElement||c instanceof OffscreenCanvas?c.getContext("2d"):null;if(r){let c=H();c.width=e.width,c.height=e.height;let l=_(c);if(l!=null){let d=e.height,h=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(d=t.resizedHeight,h=t.resizedWidth),t!==void 0){if(o=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");o.tensorFormat="RGBA",o.height=d,o.width=h}else o.tensorFormat="RGBA",o.height=d,o.width=h;l.drawImage(e,0,0),i=l.getImageData(0,0,h,d).data}else throw new Error("Can not access image data")}else if(a){let c,l;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(c=t.resizedHeight,l=t.resizedWidth):(c=e.height,l=e.width),t!==void 0&&(o=t),o.format="RGBA",o.height=c,o.width=l,t!==void 0){let d=H();d.width=l,d.height=c;let h=_(d);if(h!=null)h.putImageData(e,0,0),i=h.getImageData(0,0,l,c).data;else throw new Error("Can not access image data")}else i=e.data}else if(n){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let c=H();c.width=e.width,c.height=e.height;let l=_(c);if(l!=null){let d=e.height,h=e.width;return l.drawImage(e,0,0,h,d),i=l.getImageData(0,0,h,d).data,o.height=d,o.width=h,Zl(i,o)}else throw new Error("Can not access image data")}else{if(s)return new Promise((c,l)=>{let d=H(),h=_(d);if(!e||!h)return l();let $=new Image;$.crossOrigin="Anonymous",$.src=e,$.onload=()=>{d.width=$.width,d.height=$.height,h.drawImage($,0,0,d.width,d.height);let m=h.getImageData(0,0,d.width,d.height);o.height=d.height,o.width=d.width,c(Zl(m.data,o))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(i!==void 0)return Zl(i,o);throw new Error("Input data provided is not supported - aborted tensor creation")},v$=(e,t)=>{let{width:r,height:a,download:n,dispose:s}=t,i=[1,a,r,4];return new bt({location:"texture",type:"float32",texture:e,dims:i,download:n,dispose:s})},y$=(e,t)=>{let{dataType:r,dims:a,download:n,dispose:s}=t;return new bt({location:"gpu-buffer",type:r??"float32",gpuBuffer:e,dims:a,download:n,dispose:s})},D$=(e,t)=>{let{dataType:r,dims:a,download:n,dispose:s}=t;return new bt({location:"ml-tensor",type:r??"float32",mlTensor:e,dims:a,download:n,dispose:s})},C$=(e,t,r)=>new bt({location:"cpu-pinned",type:e,data:t,dims:r??[t.length]})});var Oa,Gs,N$,B$,M$=Qe(()=>{"use strict";Oa=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Gs=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),N$=!1,B$=()=>{if(!N$){N$=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,a=typeof r<"u"&&r.from;e&&(Oa.set("int64",BigInt64Array),Gs.set(BigInt64Array,"int64")),t&&(Oa.set("uint64",BigUint64Array),Gs.set(BigUint64Array,"uint64")),a?(Oa.set("float16",r),Gs.set(r,"float16")):Oa.set("float16",Uint16Array)}}});var P$,k$,R$=Qe(()=>{"use strict";mo();P$=e=>{let t=1;for(let r=0;r<e.length;r++){let a=e[r];if(typeof a!="number"||!Number.isSafeInteger(a))throw new TypeError(`dims[${r}] must be an integer, got: ${a}`);if(a<0)throw new RangeError(`dims[${r}] must be a non-negative integer, got: ${a}`);t*=a}return t},k$=(e,t)=>{switch(e.location){case"cpu":return new bt(e.type,e.data,t);case"cpu-pinned":return new bt({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new bt({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new bt({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new bt({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}});var bt,mo=Qe(()=>{"use strict";T$();w$();M$();R$();bt=class{constructor(t,r,a){B$();let n,s;if(typeof t=="object"&&"location"in t)switch(this.dataLocation=t.location,n=t.type,s=t.dims,t.location){case"cpu-pinned":{let o=Oa.get(n);if(!o)throw new TypeError(`unsupported type "${n}" to create tensor from pinned buffer`);if(!(t.data instanceof o))throw new TypeError(`buffer should be of type ${o.name}`);this.cpuData=t.data;break}case"texture":{if(n!=="float32")throw new TypeError(`unsupported type "${n}" to create tensor from texture`);this.gpuTextureData=t.texture,this.downloader=t.download,this.disposer=t.dispose;break}case"gpu-buffer":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from gpu buffer`);this.gpuBufferData=t.gpuBuffer,this.downloader=t.download,this.disposer=t.dispose;break}case"ml-tensor":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint64"&&n!=="int8"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from MLTensor`);this.mlTensorData=t.mlTensor,this.downloader=t.download,this.disposer=t.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let o,H;if(typeof t=="string")if(n=t,H=a,t==="string"){if(!Array.isArray(r))throw new TypeError("A string tensor's data must be a string array.");o=r}else{let _=Oa.get(t);if(_===void 0)throw new TypeError(`Unsupported tensor type: ${t}.`);if(Array.isArray(r)){if(t==="float16"&&_===Uint16Array||t==="uint4"||t==="int4")throw new TypeError(`Creating a ${t} tensor from number array is not supported. Please use ${_.name} as data.`);t==="uint64"||t==="int64"?o=_.from(r,BigInt):o=_.from(r)}else if(r instanceof _)o=r;else if(r instanceof Uint8ClampedArray)if(t==="uint8")o=Uint8Array.from(r);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(t==="float16"&&r instanceof Uint16Array&&_!==Uint16Array)o=new globalThis.Float16Array(r.buffer,r.byteOffset,r.length);else throw new TypeError(`A ${n} tensor's data must be type of ${_}`)}else if(H=r,Array.isArray(t)){if(t.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let _=typeof t[0];if(_==="string")n="string",o=t;else if(_==="boolean")n="bool",o=Uint8Array.from(t);else throw new TypeError(`Invalid element type of data array: ${_}.`)}else if(t instanceof Uint8ClampedArray)n="uint8",o=Uint8Array.from(t);else{let _=Gs.get(t.constructor);if(_===void 0)throw new TypeError(`Unsupported type for tensor data: ${t.constructor}.`);n=_,o=t}if(H===void 0)H=[o.length];else if(!Array.isArray(H))throw new TypeError("A tensor's dims must be a number array");s=H,this.cpuData=o,this.dataLocation="cpu"}let i=P$(s);if(this.cpuData&&i!==this.cpuData.length&&!((n==="uint4"||n==="int4")&&Math.ceil(i/2)===this.cpuData.length))throw new Error(`Tensor's size(${i}) does not match data length(${this.cpuData.length}).`);this.type=n,this.dims=s,this.size=i}static async fromImage(t,r){return x$(t,r)}static fromTexture(t,r){return v$(t,r)}static fromGpuBuffer(t,r){return y$(t,r)}static fromMLTensor(t,r){return D$(t,r)}static fromPinnedBuffer(t,r,a){return C$(t,r,a)}toDataURL(t){return g$(this,t)}toImageData(t){return b$(this,t)}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(t){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 r=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=r,t&&this.disposer&&(this.disposer(),this.disposer=void 0),r}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(t){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return k$(this,t)}}});var Ul,Wl=Qe(()=>{"use strict";mo();Ul=bt});var Kl=Qe(()=>{"use strict";Fl()});var O$=Qe(()=>{"use strict";Ol();Wl();Kl()});var G$=Qe(()=>{"use strict";O$()});var F$=Qe(()=>{"use strict"});var Z$=Qe(()=>{"use strict"});var U$=Qe(()=>{"use strict"});var W$=Qe(()=>{"use strict"});var K$=Qe(()=>{"use strict";m$();A$();G$();Wl();F$();Z$();Kl();U$();W$()});var Nr=ae((UW,j$)=>{"use strict";var V$=e=>typeof e<"u"&&e!==null,V5=e=>typeof e=="object",j5=e=>Object.prototype.toString.call(e)==="[object Object]",q5=e=>typeof e=="function",X5=e=>typeof e=="boolean",z5=e=>e instanceof Buffer,J5=e=>{if(V$(e))switch(e.constructor){case Uint8Array:case Uint8ClampedArray:case Int8Array:case Uint16Array:case Int16Array:case Uint32Array:case Int32Array:case Float32Array:case Float64Array:return!0}return!1},Q5=e=>e instanceof ArrayBuffer,Y5=e=>typeof e=="string"&&e.length>0,ek=e=>typeof e=="number"&&!Number.isNaN(e),tk=e=>Number.isInteger(e),rk=(e,t,r)=>e>=t&&e<=r,ak=(e,t)=>t.includes(e),nk=(e,t,r)=>new Error(`Expected ${t} for ${e} but received ${r} of type ${typeof r}`),sk=(e,t)=>(t.message=e.message,t);j$.exports={defined:V$,object:V5,plainObject:j5,fn:q5,bool:X5,buffer:z5,typedArray:J5,arrayBuffer:Q5,string:Y5,number:ek,integer:tk,inRange:rk,inArray:ak,invalidParameterError:nk,nativeError:sk}});var z$=ae((WW,X$)=>{"use strict";var q$=()=>process.platform==="linux",Io=null,ik=()=>{if(!Io)if(q$()&&process.report){let e=process.report.excludeNetwork;process.report.excludeNetwork=!0,Io=process.report.getReport(),process.report.excludeNetwork=e}else Io={};return Io};X$.exports={isLinux:q$,getReport:ik}});var Q$=ae((KW,J$)=>{"use strict";var Rn=require("fs"),ok="/usr/bin/ldd",Hk="/proc/self/exe",So=2048,_k=e=>{let t=Rn.openSync(e,"r"),r=Buffer.alloc(So),a=Rn.readSync(t,r,0,So,0);return Rn.close(t,()=>{}),r.subarray(0,a)},ck=e=>new Promise((t,r)=>{Rn.open(e,"r",(a,n)=>{if(a)r(a);else{let s=Buffer.alloc(So);Rn.read(n,s,0,So,0,(i,o)=>{t(s.subarray(0,o)),Rn.close(n,()=>{})})}})});J$.exports={LDD_PATH:ok,SELF_PATH:Hk,readFileSync:_k,readFile:ck}});var e0=ae((VW,Y$)=>{"use strict";var lk=e=>{if(e.length<64||e.readUInt32BE(0)!==2135247942||e.readUInt8(4)!==2||e.readUInt8(5)!==1)return null;let t=e.readUInt32LE(32),r=e.readUInt16LE(54),a=e.readUInt16LE(56);for(let n=0;n<a;n++){let s=t+n*r;if(e.readUInt32LE(s)===3){let o=e.readUInt32LE(s+8),H=e.readUInt32LE(s+32);return e.subarray(o,o+H).toString().replace(/\0.*$/g,"")}}return null};Y$.exports={interpreterPath:lk}});var Ao=ae((jW,$0)=>{"use strict";var r0=require("child_process"),{isLinux:On,getReport:a0}=z$(),{LDD_PATH:Lo,SELF_PATH:n0,readFile:Vl,readFileSync:jl}=Q$(),{interpreterPath:s0}=e0(),Br,Mr,Pr,i0="getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true",Ea="",o0=()=>Ea||new Promise(e=>{r0.exec(i0,(t,r)=>{Ea=t?" ":r,e(Ea)})}),H0=()=>{if(!Ea)try{Ea=r0.execSync(i0,{encoding:"utf8"})}catch{Ea=" "}return Ea},aa="glibc",_0=/LIBC[a-z0-9 \-).]*?(\d+\.\d+)/i,Ga="musl",uk=e=>e.includes("libc.musl-")||e.includes("ld-musl-"),c0=()=>{let e=a0();return e.header&&e.header.glibcVersionRuntime?aa:Array.isArray(e.sharedObjects)&&e.sharedObjects.some(uk)?Ga:null},l0=e=>{let[t,r]=e.split(/[\r\n]+/);return t&&t.includes(aa)?aa:r&&r.includes(Ga)?Ga:null},u0=e=>{if(e){if(e.includes("/ld-musl-"))return Ga;if(e.includes("/ld-linux-"))return aa}return null},d0=e=>(e=e.toString(),e.includes("musl")?Ga:e.includes("GNU C Library")?aa:null),dk=async()=>{if(Mr!==void 0)return Mr;Mr=null;try{let e=await Vl(Lo);Mr=d0(e)}catch{}return Mr},pk=()=>{if(Mr!==void 0)return Mr;Mr=null;try{let e=jl(Lo);Mr=d0(e)}catch{}return Mr},hk=async()=>{if(Br!==void 0)return Br;Br=null;try{let e=await Vl(n0),t=s0(e);Br=u0(t)}catch{}return Br},fk=()=>{if(Br!==void 0)return Br;Br=null;try{let e=jl(n0),t=s0(e);Br=u0(t)}catch{}return Br},p0=async()=>{let e=null;if(On()&&(e=await hk(),!e&&(e=await dk(),e||(e=c0()),!e))){let t=await o0();e=l0(t)}return e},h0=()=>{let e=null;if(On()&&(e=fk(),!e&&(e=pk(),e||(e=c0()),!e))){let t=H0();e=l0(t)}return e},Ek=async()=>On()&&await p0()!==aa,$k=()=>On()&&h0()!==aa,mk=async()=>{if(Pr!==void 0)return Pr;Pr=null;try{let t=(await Vl(Lo)).match(_0);t&&(Pr=t[1])}catch{}return Pr},Ik=()=>{if(Pr!==void 0)return Pr;Pr=null;try{let t=jl(Lo).match(_0);t&&(Pr=t[1])}catch{}return Pr},f0=()=>{let e=a0();return e.header&&e.header.glibcVersionRuntime?e.header.glibcVersionRuntime:null},t0=e=>e.trim().split(/\s+/)[1],E0=e=>{let[t,r,a]=e.split(/[\r\n]+/);return t&&t.includes(aa)?t0(t):r&&a&&r.includes(Ga)?t0(a):null},Sk=async()=>{let e=null;if(On()&&(e=await mk(),e||(e=f0()),!e)){let t=await o0();e=E0(t)}return e},Lk=()=>{let e=null;if(On()&&(e=Ik(),e||(e=f0()),!e)){let t=H0();e=E0(t)}return e};$0.exports={GLIBC:aa,MUSL:Ga,family:p0,familySync:h0,isNonGlibcLinux:Ek,isNonGlibcLinuxSync:$k,version:Sk,versionSync:Lk}});var Fs=ae((qW,m0)=>{"use strict";var Ak=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{};m0.exports=Ak});var go=ae((XW,I0)=>{"use strict";var gk="2.0.0",bk=Number.MAX_SAFE_INTEGER||9007199254740991,Tk=16,xk=250,vk=["major","premajor","minor","preminor","patch","prepatch","prerelease"];I0.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:Tk,MAX_SAFE_BUILD_LENGTH:xk,MAX_SAFE_INTEGER:bk,RELEASE_TYPES:vk,SEMVER_SPEC_VERSION:gk,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var Zs=ae((kr,S0)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:ql,MAX_SAFE_BUILD_LENGTH:yk,MAX_LENGTH:Dk}=go(),Ck=Fs();kr=S0.exports={};var wk=kr.re=[],Nk=kr.safeRe=[],ne=kr.src=[],Bk=kr.safeSrc=[],se=kr.t={},Mk=0,Xl="[a-zA-Z0-9-]",Pk=[["\\s",1],["\\d",Dk],[Xl,yk]],kk=e=>{for(let[t,r]of Pk)e=e.split(`${t}*`).join(`${t}{0,${r}}`).split(`${t}+`).join(`${t}{1,${r}}`);return e},$e=(e,t,r)=>{let a=kk(t),n=Mk++;Ck(e,n,t),se[e]=n,ne[n]=t,Bk[n]=a,wk[n]=new RegExp(t,r?"g":void 0),Nk[n]=new RegExp(a,r?"g":void 0)};$e("NUMERICIDENTIFIER","0|[1-9]\\d*");$e("NUMERICIDENTIFIERLOOSE","\\d+");$e("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${Xl}*`);$e("MAINVERSION",`(${ne[se.NUMERICIDENTIFIER]})\\.(${ne[se.NUMERICIDENTIFIER]})\\.(${ne[se.NUMERICIDENTIFIER]})`);$e("MAINVERSIONLOOSE",`(${ne[se.NUMERICIDENTIFIERLOOSE]})\\.(${ne[se.NUMERICIDENTIFIERLOOSE]})\\.(${ne[se.NUMERICIDENTIFIERLOOSE]})`);$e("PRERELEASEIDENTIFIER",`(?:${ne[se.NONNUMERICIDENTIFIER]}|${ne[se.NUMERICIDENTIFIER]})`);$e("PRERELEASEIDENTIFIERLOOSE",`(?:${ne[se.NONNUMERICIDENTIFIER]}|${ne[se.NUMERICIDENTIFIERLOOSE]})`);$e("PRERELEASE",`(?:-(${ne[se.PRERELEASEIDENTIFIER]}(?:\\.${ne[se.PRERELEASEIDENTIFIER]})*))`);$e("PRERELEASELOOSE",`(?:-?(${ne[se.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${ne[se.PRERELEASEIDENTIFIERLOOSE]})*))`);$e("BUILDIDENTIFIER",`${Xl}+`);$e("BUILD",`(?:\\+(${ne[se.BUILDIDENTIFIER]}(?:\\.${ne[se.BUILDIDENTIFIER]})*))`);$e("FULLPLAIN",`v?${ne[se.MAINVERSION]}${ne[se.PRERELEASE]}?${ne[se.BUILD]}?`);$e("FULL",`^${ne[se.FULLPLAIN]}$`);$e("LOOSEPLAIN",`[v=\\s]*${ne[se.MAINVERSIONLOOSE]}${ne[se.PRERELEASELOOSE]}?${ne[se.BUILD]}?`);$e("LOOSE",`^${ne[se.LOOSEPLAIN]}$`);$e("GTLT","((?:<|>)?=?)");$e("XRANGEIDENTIFIERLOOSE",`${ne[se.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);$e("XRANGEIDENTIFIER",`${ne[se.NUMERICIDENTIFIER]}|x|X|\\*`);$e("XRANGEPLAIN",`[v=\\s]*(${ne[se.XRANGEIDENTIFIER]})(?:\\.(${ne[se.XRANGEIDENTIFIER]})(?:\\.(${ne[se.XRANGEIDENTIFIER]})(?:${ne[se.PRERELEASE]})?${ne[se.BUILD]}?)?)?`);$e("XRANGEPLAINLOOSE",`[v=\\s]*(${ne[se.XRANGEIDENTIFIERLOOSE]})(?:\\.(${ne[se.XRANGEIDENTIFIERLOOSE]})(?:\\.(${ne[se.XRANGEIDENTIFIERLOOSE]})(?:${ne[se.PRERELEASELOOSE]})?${ne[se.BUILD]}?)?)?`);$e("XRANGE",`^${ne[se.GTLT]}\\s*${ne[se.XRANGEPLAIN]}$`);$e("XRANGELOOSE",`^${ne[se.GTLT]}\\s*${ne[se.XRANGEPLAINLOOSE]}$`);$e("COERCEPLAIN",`(^|[^\\d])(\\d{1,${ql}})(?:\\.(\\d{1,${ql}}))?(?:\\.(\\d{1,${ql}}))?`);$e("COERCE",`${ne[se.COERCEPLAIN]}(?:$|[^\\d])`);$e("COERCEFULL",ne[se.COERCEPLAIN]+`(?:${ne[se.PRERELEASE]})?(?:${ne[se.BUILD]})?(?:$|[^\\d])`);$e("COERCERTL",ne[se.COERCE],!0);$e("COERCERTLFULL",ne[se.COERCEFULL],!0);$e("LONETILDE","(?:~>?)");$e("TILDETRIM",`(\\s*)${ne[se.LONETILDE]}\\s+`,!0);kr.tildeTrimReplace="$1~";$e("TILDE",`^${ne[se.LONETILDE]}${ne[se.XRANGEPLAIN]}$`);$e("TILDELOOSE",`^${ne[se.LONETILDE]}${ne[se.XRANGEPLAINLOOSE]}$`);$e("LONECARET","(?:\\^)");$e("CARETTRIM",`(\\s*)${ne[se.LONECARET]}\\s+`,!0);kr.caretTrimReplace="$1^";$e("CARET",`^${ne[se.LONECARET]}${ne[se.XRANGEPLAIN]}$`);$e("CARETLOOSE",`^${ne[se.LONECARET]}${ne[se.XRANGEPLAINLOOSE]}$`);$e("COMPARATORLOOSE",`^${ne[se.GTLT]}\\s*(${ne[se.LOOSEPLAIN]})$|^$`);$e("COMPARATOR",`^${ne[se.GTLT]}\\s*(${ne[se.FULLPLAIN]})$|^$`);$e("COMPARATORTRIM",`(\\s*)${ne[se.GTLT]}\\s*(${ne[se.LOOSEPLAIN]}|${ne[se.XRANGEPLAIN]})`,!0);kr.comparatorTrimReplace="$1$2$3";$e("HYPHENRANGE",`^\\s*(${ne[se.XRANGEPLAIN]})\\s+-\\s+(${ne[se.XRANGEPLAIN]})\\s*$`);$e("HYPHENRANGELOOSE",`^\\s*(${ne[se.XRANGEPLAINLOOSE]})\\s+-\\s+(${ne[se.XRANGEPLAINLOOSE]})\\s*$`);$e("STAR","(<|>)?=?\\s*\\*");$e("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");$e("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var bo=ae((zW,L0)=>{"use strict";var Rk=Object.freeze({loose:!0}),Ok=Object.freeze({}),Gk=e=>e?typeof e!="object"?Rk:e:Ok;L0.exports=Gk});var T0=ae((JW,b0)=>{"use strict";var A0=/^[0-9]+$/,g0=(e,t)=>{if(typeof e=="number"&&typeof t=="number")return e===t?0:e<t?-1:1;let r=A0.test(e),a=A0.test(t);return r&&a&&(e=+e,t=+t),e===t?0:r&&!a?-1:a&&!r?1:e<t?-1:1},Fk=(e,t)=>g0(t,e);b0.exports={compareIdentifiers:g0,rcompareIdentifiers:Fk}});var Gn=ae((QW,v0)=>{"use strict";var To=Fs(),{MAX_LENGTH:x0,MAX_SAFE_INTEGER:xo}=go(),{safeRe:vo,t:yo}=Zs(),Zk=bo(),{compareIdentifiers:zl}=T0(),Jl=class e{constructor(t,r){if(r=Zk(r),t instanceof e){if(t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease)return t;t=t.version}else if(typeof t!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof t}".`);if(t.length>x0)throw new TypeError(`version is longer than ${x0} characters`);To("SemVer",t,r),this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease;let a=t.trim().match(r.loose?vo[yo.LOOSE]:vo[yo.FULL]);if(!a)throw new TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+a[1],this.minor=+a[2],this.patch=+a[3],this.major>xo||this.major<0)throw new TypeError("Invalid major version");if(this.minor>xo||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>xo||this.patch<0)throw new TypeError("Invalid patch version");a[4]?this.prerelease=a[4].split(".").map(n=>{if(/^[0-9]+$/.test(n)){let s=+n;if(s>=0&&s<xo)return s}return n}):this.prerelease=[],this.build=a[5]?a[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(t){if(To("SemVer.compare",this.version,this.options,t),!(t instanceof e)){if(typeof t=="string"&&t===this.version)return 0;t=new e(t,this.options)}return t.version===this.version?0:this.compareMain(t)||this.comparePre(t)}compareMain(t){return t instanceof e||(t=new e(t,this.options)),this.major<t.major?-1:this.major>t.major?1:this.minor<t.minor?-1:this.minor>t.minor?1:this.patch<t.patch?-1:this.patch>t.patch?1:0}comparePre(t){if(t instanceof e||(t=new e(t,this.options)),this.prerelease.length&&!t.prerelease.length)return-1;if(!this.prerelease.length&&t.prerelease.length)return 1;if(!this.prerelease.length&&!t.prerelease.length)return 0;let r=0;do{let a=this.prerelease[r],n=t.prerelease[r];if(To("prerelease compare",r,a,n),a===void 0&&n===void 0)return 0;if(n===void 0)return 1;if(a===void 0)return-1;if(a===n)continue;return zl(a,n)}while(++r)}compareBuild(t){t instanceof e||(t=new e(t,this.options));let r=0;do{let a=this.build[r],n=t.build[r];if(To("build compare",r,a,n),a===void 0&&n===void 0)return 0;if(n===void 0)return 1;if(a===void 0)return-1;if(a===n)continue;return zl(a,n)}while(++r)}inc(t,r,a){if(t.startsWith("pre")){if(!r&&a===!1)throw new Error("invalid increment argument: identifier is empty");if(r){let n=`-${r}`.match(this.options.loose?vo[yo.PRERELEASELOOSE]:vo[yo.PRERELEASE]);if(!n||n[1]!==r)throw new Error(`invalid identifier: ${r}`)}}switch(t){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",r,a);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",r,a);break;case"prepatch":this.prerelease.length=0,this.inc("patch",r,a),this.inc("pre",r,a);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",r,a),this.inc("pre",r,a);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{let n=Number(a)?1:0;if(this.prerelease.length===0)this.prerelease=[n];else{let s=this.prerelease.length;for(;--s>=0;)typeof this.prerelease[s]=="number"&&(this.prerelease[s]++,s=-2);if(s===-1){if(r===this.prerelease.join(".")&&a===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(n)}}if(r){let s=[r,n];a===!1&&(s=[r]),zl(this.prerelease[0],r)===0?isNaN(this.prerelease[1])&&(this.prerelease=s):this.prerelease=s}break}default:throw new Error(`invalid increment argument: ${t}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};v0.exports=Jl});var C0=ae((YW,D0)=>{"use strict";var y0=Gn(),Uk=(e,t,r=!1)=>{if(e instanceof y0)return e;try{return new y0(e,t)}catch(a){if(!r)return null;throw a}};D0.exports=Uk});var N0=ae((eK,w0)=>{"use strict";var Wk=Gn(),Kk=C0(),{safeRe:Do,t:Co}=Zs(),Vk=(e,t)=>{if(e instanceof Wk)return e;if(typeof e=="number"&&(e=String(e)),typeof e!="string")return null;t=t||{};let r=null;if(!t.rtl)r=e.match(t.includePrerelease?Do[Co.COERCEFULL]:Do[Co.COERCE]);else{let H=t.includePrerelease?Do[Co.COERCERTLFULL]:Do[Co.COERCERTL],_;for(;(_=H.exec(e))&&(!r||r.index+r[0].length!==e.length);)(!r||_.index+_[0].length!==r.index+r[0].length)&&(r=_),H.lastIndex=_.index+_[1].length+_[2].length;H.lastIndex=-1}if(r===null)return null;let a=r[2],n=r[3]||"0",s=r[4]||"0",i=t.includePrerelease&&r[5]?`-${r[5]}`:"",o=t.includePrerelease&&r[6]?`+${r[6]}`:"";return Kk(`${a}.${n}.${s}${i}${o}`,t)};w0.exports=Vk});var Fa=ae((tK,M0)=>{"use strict";var B0=Gn(),jk=(e,t,r)=>new B0(e,r).compare(new B0(t,r));M0.exports=jk});var Ql=ae((rK,P0)=>{"use strict";var qk=Fa(),Xk=(e,t,r)=>qk(e,t,r)>=0;P0.exports=Xk});var R0=ae((aK,k0)=>{"use strict";var Yl=class{constructor(){this.max=1e3,this.map=new Map}get(t){let r=this.map.get(t);if(r!==void 0)return this.map.delete(t),this.map.set(t,r),r}delete(t){return this.map.delete(t)}set(t,r){if(!this.delete(t)&&r!==void 0){if(this.map.size>=this.max){let n=this.map.keys().next().value;this.delete(n)}this.map.set(t,r)}return this}};k0.exports=Yl});var G0=ae((nK,O0)=>{"use strict";var zk=Fa(),Jk=(e,t,r)=>zk(e,t,r)===0;O0.exports=Jk});var Z0=ae((sK,F0)=>{"use strict";var Qk=Fa(),Yk=(e,t,r)=>Qk(e,t,r)!==0;F0.exports=Yk});var W0=ae((iK,U0)=>{"use strict";var eR=Fa(),tR=(e,t,r)=>eR(e,t,r)>0;U0.exports=tR});var V0=ae((oK,K0)=>{"use strict";var rR=Fa(),aR=(e,t,r)=>rR(e,t,r)<0;K0.exports=aR});var q0=ae((HK,j0)=>{"use strict";var nR=Fa(),sR=(e,t,r)=>nR(e,t,r)<=0;j0.exports=sR});var z0=ae((_K,X0)=>{"use strict";var iR=G0(),oR=Z0(),HR=W0(),_R=Ql(),cR=V0(),lR=q0(),uR=(e,t,r,a)=>{switch(t){case"===":return typeof e=="object"&&(e=e.version),typeof r=="object"&&(r=r.version),e===r;case"!==":return typeof e=="object"&&(e=e.version),typeof r=="object"&&(r=r.version),e!==r;case"":case"=":case"==":return iR(e,r,a);case"!=":return oR(e,r,a);case">":return HR(e,r,a);case">=":return _R(e,r,a);case"<":return cR(e,r,a);case"<=":return lR(e,r,a);default:throw new TypeError(`Invalid operator: ${t}`)}};X0.exports=uR});var am=ae((cK,rm)=>{"use strict";var Us=Symbol("SemVer ANY"),ru=class e{static get ANY(){return Us}constructor(t,r){if(r=J0(r),t instanceof e){if(t.loose===!!r.loose)return t;t=t.value}t=t.trim().split(/\s+/).join(" "),tu("comparator",t,r),this.options=r,this.loose=!!r.loose,this.parse(t),this.semver===Us?this.value="":this.value=this.operator+this.semver.version,tu("comp",this)}parse(t){let r=this.options.loose?Q0[Y0.COMPARATORLOOSE]:Q0[Y0.COMPARATOR],a=t.match(r);if(!a)throw new TypeError(`Invalid comparator: ${t}`);this.operator=a[1]!==void 0?a[1]:"",this.operator==="="&&(this.operator=""),a[2]?this.semver=new em(a[2],this.options.loose):this.semver=Us}toString(){return this.value}test(t){if(tu("Comparator.test",t,this.options.loose),this.semver===Us||t===Us)return!0;if(typeof t=="string")try{t=new em(t,this.options)}catch{return!1}return eu(t,this.operator,this.semver,this.options)}intersects(t,r){if(!(t instanceof e))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new tm(t.value,r).test(this.value):t.operator===""?t.value===""?!0:new tm(this.value,r).test(t.semver):(r=J0(r),r.includePrerelease&&(this.value==="<0.0.0-0"||t.value==="<0.0.0-0")||!r.includePrerelease&&(this.value.startsWith("<0.0.0")||t.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&t.operator.startsWith(">")||this.operator.startsWith("<")&&t.operator.startsWith("<")||this.semver.version===t.semver.version&&this.operator.includes("=")&&t.operator.includes("=")||eu(this.semver,"<",t.semver,r)&&this.operator.startsWith(">")&&t.operator.startsWith("<")||eu(this.semver,">",t.semver,r)&&this.operator.startsWith("<")&&t.operator.startsWith(">")))}};rm.exports=ru;var J0=bo(),{safeRe:Q0,t:Y0}=Zs(),eu=z0(),tu=Fs(),em=Gn(),tm=au()});var au=ae((lK,om)=>{"use strict";var dR=/\s+/g,nu=class e{constructor(t,r){if(r=hR(r),t instanceof e)return t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease?t:new e(t.raw,r);if(t instanceof su)return this.raw=t.value,this.set=[[t]],this.formatted=void 0,this;if(this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease,this.raw=t.trim().replace(dR," "),this.set=this.raw.split("||").map(a=>this.parseRange(a.trim())).filter(a=>a.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let a=this.set[0];if(this.set=this.set.filter(n=>!sm(n[0])),this.set.length===0)this.set=[a];else if(this.set.length>1){for(let n of this.set)if(n.length===1&&LR(n[0])){this.set=[n];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let t=0;t<this.set.length;t++){t>0&&(this.formatted+="||");let r=this.set[t];for(let a=0;a<r.length;a++)a>0&&(this.formatted+=" "),this.formatted+=r[a].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(t){let a=((this.options.includePrerelease&&IR)|(this.options.loose&&SR))+":"+t,n=nm.get(a);if(n)return n;let s=this.options.loose,i=s?Ft[Ct.HYPHENRANGELOOSE]:Ft[Ct.HYPHENRANGE];t=t.replace(i,wR(this.options.includePrerelease)),Ve("hyphen replace",t),t=t.replace(Ft[Ct.COMPARATORTRIM],ER),Ve("comparator trim",t),t=t.replace(Ft[Ct.TILDETRIM],$R),Ve("tilde trim",t),t=t.replace(Ft[Ct.CARETTRIM],mR),Ve("caret trim",t);let o=t.split(" ").map(l=>AR(l,this.options)).join(" ").split(/\s+/).map(l=>CR(l,this.options));s&&(o=o.filter(l=>(Ve("loose invalid filter",l,this.options),!!l.match(Ft[Ct.COMPARATORLOOSE])))),Ve("range list",o);let H=new Map,_=o.map(l=>new su(l,this.options));for(let l of _){if(sm(l))return[l];H.set(l.value,l)}H.size>1&&H.has("")&&H.delete("");let c=[...H.values()];return nm.set(a,c),c}intersects(t,r){if(!(t instanceof e))throw new TypeError("a Range is required");return this.set.some(a=>im(a,r)&&t.set.some(n=>im(n,r)&&a.every(s=>n.every(i=>s.intersects(i,r)))))}test(t){if(!t)return!1;if(typeof t=="string")try{t=new fR(t,this.options)}catch{return!1}for(let r=0;r<this.set.length;r++)if(NR(this.set[r],t,this.options))return!0;return!1}};om.exports=nu;var pR=R0(),nm=new pR,hR=bo(),su=am(),Ve=Fs(),fR=Gn(),{safeRe:Ft,t:Ct,comparatorTrimReplace:ER,tildeTrimReplace:$R,caretTrimReplace:mR}=Zs(),{FLAG_INCLUDE_PRERELEASE:IR,FLAG_LOOSE:SR}=go(),sm=e=>e.value==="<0.0.0-0",LR=e=>e.value==="",im=(e,t)=>{let r=!0,a=e.slice(),n=a.pop();for(;r&&a.length;)r=a.every(s=>n.intersects(s,t)),n=a.pop();return r},AR=(e,t)=>(e=e.replace(Ft[Ct.BUILD],""),Ve("comp",e,t),e=TR(e,t),Ve("caret",e),e=gR(e,t),Ve("tildes",e),e=vR(e,t),Ve("xrange",e),e=DR(e,t),Ve("stars",e),e),Zt=e=>!e||e.toLowerCase()==="x"||e==="*",gR=(e,t)=>e.trim().split(/\s+/).map(r=>bR(r,t)).join(" "),bR=(e,t)=>{let r=t.loose?Ft[Ct.TILDELOOSE]:Ft[Ct.TILDE];return e.replace(r,(a,n,s,i,o)=>{Ve("tilde",e,a,n,s,i,o);let H;return Zt(n)?H="":Zt(s)?H=`>=${n}.0.0 <${+n+1}.0.0-0`:Zt(i)?H=`>=${n}.${s}.0 <${n}.${+s+1}.0-0`:o?(Ve("replaceTilde pr",o),H=`>=${n}.${s}.${i}-${o} <${n}.${+s+1}.0-0`):H=`>=${n}.${s}.${i} <${n}.${+s+1}.0-0`,Ve("tilde return",H),H})},TR=(e,t)=>e.trim().split(/\s+/).map(r=>xR(r,t)).join(" "),xR=(e,t)=>{Ve("caret",e,t);let r=t.loose?Ft[Ct.CARETLOOSE]:Ft[Ct.CARET],a=t.includePrerelease?"-0":"";return e.replace(r,(n,s,i,o,H)=>{Ve("caret",e,n,s,i,o,H);let _;return Zt(s)?_="":Zt(i)?_=`>=${s}.0.0${a} <${+s+1}.0.0-0`:Zt(o)?s==="0"?_=`>=${s}.${i}.0${a} <${s}.${+i+1}.0-0`:_=`>=${s}.${i}.0${a} <${+s+1}.0.0-0`:H?(Ve("replaceCaret pr",H),s==="0"?i==="0"?_=`>=${s}.${i}.${o}-${H} <${s}.${i}.${+o+1}-0`:_=`>=${s}.${i}.${o}-${H} <${s}.${+i+1}.0-0`:_=`>=${s}.${i}.${o}-${H} <${+s+1}.0.0-0`):(Ve("no pr"),s==="0"?i==="0"?_=`>=${s}.${i}.${o}${a} <${s}.${i}.${+o+1}-0`:_=`>=${s}.${i}.${o}${a} <${s}.${+i+1}.0-0`:_=`>=${s}.${i}.${o} <${+s+1}.0.0-0`),Ve("caret return",_),_})},vR=(e,t)=>(Ve("replaceXRanges",e,t),e.split(/\s+/).map(r=>yR(r,t)).join(" ")),yR=(e,t)=>{e=e.trim();let r=t.loose?Ft[Ct.XRANGELOOSE]:Ft[Ct.XRANGE];return e.replace(r,(a,n,s,i,o,H)=>{Ve("xRange",e,a,n,s,i,o,H);let _=Zt(s),c=_||Zt(i),l=c||Zt(o),d=l;return n==="="&&d&&(n=""),H=t.includePrerelease?"-0":"",_?n===">"||n==="<"?a="<0.0.0-0":a="*":n&&d?(c&&(i=0),o=0,n===">"?(n=">=",c?(s=+s+1,i=0,o=0):(i=+i+1,o=0)):n==="<="&&(n="<",c?s=+s+1:i=+i+1),n==="<"&&(H="-0"),a=`${n+s}.${i}.${o}${H}`):c?a=`>=${s}.0.0${H} <${+s+1}.0.0-0`:l&&(a=`>=${s}.${i}.0${H} <${s}.${+i+1}.0-0`),Ve("xRange return",a),a})},DR=(e,t)=>(Ve("replaceStars",e,t),e.trim().replace(Ft[Ct.STAR],"")),CR=(e,t)=>(Ve("replaceGTE0",e,t),e.trim().replace(Ft[t.includePrerelease?Ct.GTE0PRE:Ct.GTE0],"")),wR=e=>(t,r,a,n,s,i,o,H,_,c,l,d)=>(Zt(a)?r="":Zt(n)?r=`>=${a}.0.0${e?"-0":""}`:Zt(s)?r=`>=${a}.${n}.0${e?"-0":""}`:i?r=`>=${r}`:r=`>=${r}${e?"-0":""}`,Zt(_)?H="":Zt(c)?H=`<${+_+1}.0.0-0`:Zt(l)?H=`<${_}.${+c+1}.0-0`:d?H=`<=${_}.${c}.${l}-${d}`:e?H=`<${_}.${c}.${+l+1}-0`:H=`<=${H}`,`${r} ${H}`.trim()),NR=(e,t,r)=>{for(let a=0;a<e.length;a++)if(!e[a].test(t))return!1;if(t.prerelease.length&&!r.includePrerelease){for(let a=0;a<e.length;a++)if(Ve(e[a].semver),e[a].semver!==su.ANY&&e[a].semver.prerelease.length>0){let n=e[a].semver;if(n.major===t.major&&n.minor===t.minor&&n.patch===t.patch)return!0}return!1}return!0}});var _m=ae((uK,Hm)=>{"use strict";var BR=au(),MR=(e,t,r)=>{try{t=new BR(t,r)}catch{return!1}return t.test(e)};Hm.exports=MR});var iu=ae((dK,PR)=>{PR.exports={name:"sharp",description:"High performance Node.js image processing, the fastest module to resize JPEG, PNG, WebP, GIF, AVIF and TIFF images",version:"0.34.5",author:"Lovell Fuller <npm@lovell.info>",homepage:"https://sharp.pixelplumbing.com",contributors:["Pierre Inglebert <pierre.inglebert@gmail.com>","Jonathan Ong <jonathanrichardong@gmail.com>","Chanon Sajjamanochai <chanon.s@gmail.com>","Juliano Julio <julianojulio@gmail.com>","Daniel Gasienica <daniel@gasienica.ch>","Julian Walker <julian@fiftythree.com>","Amit Pitaru <pitaru.amit@gmail.com>","Brandon Aaron <hello.brandon@aaron.sh>","Andreas Lind <andreas@one.com>","Maurus Cuelenaere <mcuelenaere@gmail.com>","Linus Unneb\xE4ck <linus@folkdatorn.se>","Victor Mateevitsi <mvictoras@gmail.com>","Alaric Holloway <alaric.holloway@gmail.com>","Bernhard K. Weisshuhn <bkw@codingforce.com>","Chris Riley <criley@primedia.com>","David Carley <dacarley@gmail.com>","John Tobin <john@limelightmobileinc.com>","Kenton Gray <kentongray@gmail.com>","Felix B\xFCnemann <Felix.Buenemann@gmail.com>","Samy Al Zahrani <samyalzahrany@gmail.com>","Chintan Thakkar <lemnisk8@gmail.com>","F. Orlando Galashan <frulo@gmx.de>","Kleis Auke Wolthuizen <info@kleisauke.nl>","Matt Hirsch <mhirsch@media.mit.edu>","Matthias Thoemmes <thoemmes@gmail.com>","Patrick Paskaris <patrick@paskaris.gr>","J\xE9r\xE9my Lal <kapouer@melix.org>","Rahul Nanwani <r.nanwani@gmail.com>","Alice Monday <alice0meta@gmail.com>","Kristo Jorgenson <kristo.jorgenson@gmail.com>","YvesBos <yves_bos@outlook.com>","Guy Maliar <guy@tailorbrands.com>","Nicolas Coden <nicolas@ncoden.fr>","Matt Parrish <matt.r.parrish@gmail.com>","Marcel Bretschneider <marcel.bretschneider@gmail.com>","Matthew McEachen <matthew+github@mceachen.org>","Jarda Kot\u011B\u0161ovec <jarda.kotesovec@gmail.com>","Kenric D'Souza <kenric.dsouza@gmail.com>","Oleh Aleinyk <oleg.aleynik@gmail.com>","Marcel Bretschneider <marcel.bretschneider@gmail.com>","Andrea Bianco <andrea.bianco@unibas.ch>","Rik Heywood <rik@rik.org>","Thomas Parisot <hi@oncletom.io>","Nathan Graves <nathanrgraves+github@gmail.com>","Tom Lokhorst <tom@lokhorst.eu>","Espen Hovlandsdal <espen@hovlandsdal.com>","Sylvain Dumont <sylvain.dumont35@gmail.com>","Alun Davies <alun.owain.davies@googlemail.com>","Aidan Hoolachan <ajhoolachan21@gmail.com>","Axel Eirola <axel.eirola@iki.fi>","Freezy <freezy@xbmc.org>","Daiz <taneli.vatanen@gmail.com>","Julian Aubourg <j@ubourg.net>","Keith Belovay <keith@picthrive.com>","Michael B. Klein <mbklein@gmail.com>","Jordan Prudhomme <jordan@raboland.fr>","Ilya Ovdin <iovdin@gmail.com>","Andargor <andargor@yahoo.com>","Paul Neave <paul.neave@gmail.com>","Brendan Kennedy <brenwken@gmail.com>","Brychan Bennett-Odlum <git@brychan.io>","Edward Silverton <e.silverton@gmail.com>","Roman Malieiev <aromaleev@gmail.com>","Tomas Szabo <tomas.szabo@deftomat.com>","Robert O'Rourke <robert@o-rourke.org>","Guillermo Alfonso Varela Chouci\xF1o <guillevch@gmail.com>","Christian Flintrup <chr@gigahost.dk>","Manan Jadhav <manan@motionden.com>","Leon Radley <leon@radley.se>","alza54 <alza54@thiocod.in>","Jacob Smith <jacob@frende.me>","Michael Nutt <michael@nutt.im>","Brad Parham <baparham@gmail.com>","Taneli Vatanen <taneli.vatanen@gmail.com>","Joris Dugu\xE9 <zaruike10@gmail.com>","Chris Banks <christopher.bradley.banks@gmail.com>","Ompal Singh <ompal.hitm09@gmail.com>","Brodan <christopher.hranj@gmail.com>","Ankur Parihar <ankur.github@gmail.com>","Brahim Ait elhaj <brahima@gmail.com>","Mart Jansink <m.jansink@gmail.com>","Lachlan Newman <lachnewman007@gmail.com>","Dennis Beatty <dennis@dcbeatty.com>","Ingvar Stepanyan <me@rreverser.com>","Don Denton <don@happycollision.com>"],scripts:{build:"node install/build.js",install:"node install/check.js || npm run build",clean:"rm -rf src/build/ .nyc_output/ coverage/ test/fixtures/output.*",test:"npm run lint && npm run test-unit",lint:"npm run lint-cpp && npm run lint-js && npm run lint-types","lint-cpp":"cpplint --quiet src/*.h src/*.cc","lint-js":"biome lint","lint-types":"tsd --files ./test/types/sharp.test-d.ts","test-leak":"./test/leak/leak.sh","test-unit":"node --experimental-test-coverage test/unit.mjs","package-from-local-build":"node npm/from-local-build.js","package-release-notes":"node npm/release-notes.js","docs-build":"node docs/build.mjs","docs-serve":"cd docs && npm start","docs-publish":"cd docs && npm run build && npx firebase-tools deploy --project pixelplumbing --only hosting:pixelplumbing-sharp"},type:"commonjs",main:"lib/index.js",types:"lib/index.d.ts",files:["install","lib","src/*.{cc,h,gyp}"],repository:{type:"git",url:"git://github.com/lovell/sharp.git"},keywords:["jpeg","png","webp","avif","tiff","gif","svg","jp2","dzi","image","resize","thumbnail","crop","embed","libvips","vips"],dependencies:{"@img/colour":"^1.0.0","detect-libc":"^2.1.2",semver:"^7.7.3"},optionalDependencies:{"@img/sharp-darwin-arm64":"0.34.5","@img/sharp-darwin-x64":"0.34.5","@img/sharp-libvips-darwin-arm64":"1.2.4","@img/sharp-libvips-darwin-x64":"1.2.4","@img/sharp-libvips-linux-arm":"1.2.4","@img/sharp-libvips-linux-arm64":"1.2.4","@img/sharp-libvips-linux-ppc64":"1.2.4","@img/sharp-libvips-linux-riscv64":"1.2.4","@img/sharp-libvips-linux-s390x":"1.2.4","@img/sharp-libvips-linux-x64":"1.2.4","@img/sharp-libvips-linuxmusl-arm64":"1.2.4","@img/sharp-libvips-linuxmusl-x64":"1.2.4","@img/sharp-linux-arm":"0.34.5","@img/sharp-linux-arm64":"0.34.5","@img/sharp-linux-ppc64":"0.34.5","@img/sharp-linux-riscv64":"0.34.5","@img/sharp-linux-s390x":"0.34.5","@img/sharp-linux-x64":"0.34.5","@img/sharp-linuxmusl-arm64":"0.34.5","@img/sharp-linuxmusl-x64":"0.34.5","@img/sharp-wasm32":"0.34.5","@img/sharp-win32-arm64":"0.34.5","@img/sharp-win32-ia32":"0.34.5","@img/sharp-win32-x64":"0.34.5"},devDependencies:{"@biomejs/biome":"^2.3.4","@cpplint/cli":"^0.1.0","@emnapi/runtime":"^1.7.0","@img/sharp-libvips-dev":"1.2.4","@img/sharp-libvips-dev-wasm32":"1.2.4","@img/sharp-libvips-win32-arm64":"1.2.4","@img/sharp-libvips-win32-ia32":"1.2.4","@img/sharp-libvips-win32-x64":"1.2.4","@types/node":"*",emnapi:"^1.7.0","exif-reader":"^2.0.2","extract-zip":"^2.0.1",icc:"^3.0.0","jsdoc-to-markdown":"^9.1.3","node-addon-api":"^8.5.0","node-gyp":"^11.5.0","tar-fs":"^3.1.1",tsd:"^0.33.0"},license:"Apache-2.0",engines:{node:"^18.17.0 || ^20.3.0 || >=21.0.0"},config:{libvips:">=8.17.3"},funding:{url:"https://opencollective.com/libvips"}}});var Hu=ae((pK,mm)=>{"use strict";var{spawnSync:wo}=require("child_process"),{createHash:kR}=require("crypto"),dm=N0(),RR=Ql(),OR=_m(),cm=Ao(),{config:GR,engines:lm,optionalDependencies:FR}=iu(),ZR=process.env.npm_package_config_libvips||GR.libvips,pm=dm(ZR).version,UR=["darwin-arm64","darwin-x64","linux-arm","linux-arm64","linux-ppc64","linux-riscv64","linux-s390x","linux-x64","linuxmusl-arm64","linuxmusl-x64","win32-arm64","win32-ia32","win32-x64"],No={encoding:"utf8",shell:!0},WR=e=>{e instanceof Error?console.error(`sharp: Installation error: ${e.message}`):console.log(`sharp: ${e}`)},hm=()=>cm.isNonGlibcLinuxSync()?cm.familySync():"",KR=()=>`${process.platform}${hm()}-${process.arch}`,Fn=()=>{if(fm())return"wasm32";let{npm_config_arch:e,npm_config_platform:t,npm_config_libc:r}=process.env,a=typeof r=="string"?r:hm();return`${t||process.platform}${a}-${e||process.arch}`},VR=()=>{try{return require(`@img/sharp-libvips-dev-${Fn()}/include`)}catch{try{return require("@img/sharp-libvips-dev/include")}catch{}}return""},jR=()=>{try{return require("@img/sharp-libvips-dev/cplusplus")}catch{}return""},qR=()=>{try{return require(`@img/sharp-libvips-dev-${Fn()}/lib`)}catch{try{return require(`@img/sharp-libvips-${Fn()}/lib`)}catch{}}return""},XR=()=>{if(process.release?.name==="node"&&process.versions&&!OR(process.versions.node,lm.node))return{found:process.versions.node,expected:lm.node}},fm=()=>{let{CC:e}=process.env;return!!e?.endsWith("/emcc")},zR=()=>process.platform==="darwin"&&process.arch==="x64"?(wo("sysctl sysctl.proc_translated",No).stdout||"").trim()==="sysctl.proc_translated: 1":!1,um=e=>kR("sha512").update(e).digest("hex"),JR=()=>{try{let e=um(`imgsharp-libvips-${Fn()}`),t=dm(FR[`@img/sharp-libvips-${Fn()}`],{includePrerelease:!0}).version;return um(`${e}npm:${t}`).slice(0,10)}catch{}return""},QR=()=>wo(`node-gyp rebuild --directory=src ${fm()?"--nodedir=emscripten":""}`,{...No,stdio:"inherit"}).status,Em=()=>process.platform!=="win32"?(wo("pkg-config --modversion vips-cpp",{...No,env:{...process.env,PKG_CONFIG_PATH:$m()}}).stdout||"").trim():"",$m=()=>process.platform!=="win32"?[(wo('which brew >/dev/null 2>&1 && brew environment --plain | grep PKG_CONFIG_LIBDIR | cut -d" " -f2',No).stdout||"").trim(),process.env.PKG_CONFIG_PATH,"/usr/local/lib/pkgconfig","/usr/lib/pkgconfig","/usr/local/libdata/pkgconfig","/usr/libdata/pkgconfig"].filter(Boolean).join(":"):"",ou=(e,t,r)=>(r&&r(`Detected ${t}, skipping search for globally-installed libvips`),e),YR=e=>{if(process.env.SHARP_IGNORE_GLOBAL_LIBVIPS)return ou(!1,"SHARP_IGNORE_GLOBAL_LIBVIPS",e);if(process.env.SHARP_FORCE_GLOBAL_LIBVIPS)return ou(!0,"SHARP_FORCE_GLOBAL_LIBVIPS",e);if(zR())return ou(!1,"Rosetta",e);let t=Em();return!!t&&RR(t,pm)};mm.exports={minimumLibvipsVersion:pm,prebuiltPlatforms:UR,buildPlatformArch:Fn,buildSharpLibvipsIncludeDir:VR,buildSharpLibvipsCPlusPlusDir:jR,buildSharpLibvipsLibDir:qR,isUnsupportedNodeRuntime:XR,runtimePlatformArch:KR,log:WR,yarnLocator:JR,spawnRebuild:QR,globalLibvipsVersion:Em,pkgConfigPath:$m,useGlobalLibvips:YR}});var Ks=ae((hK,Sm)=>{"use strict";var{familySync:e4,versionSync:t4}=Ao(),{runtimePlatformArch:r4,isUnsupportedNodeRuntime:Im,prebuiltPlatforms:a4,minimumLibvipsVersion:n4}=Hu(),Za=r4(),s4=[`../src/build/Release/sharp-${Za}.node`,"../src/build/Release/sharp-wasm32.node",`@img/sharp-${Za}/sharp.node`,"@img/sharp-wasm32/sharp.node"],_u,Zn,Ws=[];for(_u of s4)try{Zn=require(_u);break}catch(e){Ws.push(e)}if(Zn&&_u.startsWith("@img/sharp-linux-x64")&&!Zn._isUsingX64V2()){let e=new Error("Prebuilt binaries for linux-x64 require v2 microarchitecture");e.code="Unsupported CPU",Ws.push(e),Zn=null}if(Zn)Sm.exports=Zn;else{let[e,t,r]=["linux","darwin","win32"].map(s=>Za.startsWith(s)),a=[`Could not load the "sharp" module using the ${Za} runtime`];Ws.forEach(s=>{s.code!=="MODULE_NOT_FOUND"&&a.push(`${s.code}: ${s.message}`)});let n=Ws.map(s=>s.message).join(" ");if(a.push("Possible solutions:"),Im()){let{found:s,expected:i}=Im();a.push("- Please upgrade Node.js:",` Found ${s}`,` Requires ${i}`)}else if(a4.includes(Za)){let[s,i]=Za.split("-"),o=s.endsWith("musl")?" --libc=musl":"";a.push("- Ensure optional dependencies can be installed:"," npm install --include=optional sharp","- Ensure your package manager supports multi-platform installation:"," See https://sharp.pixelplumbing.com/install#cross-platform","- Add platform-specific dependencies:",` npm install --os=${s.replace("musl","")}${o} --cpu=${i} sharp`)}else a.push(`- Manually install libvips >= ${n4}`,"- Add experimental WebAssembly-based dependencies:"," npm install --cpu=wasm32 sharp"," npm install @img/sharp-wasm32");if(e&&/(symbol not found|CXXABI_)/i.test(n))try{let{config:s}=require(`@img/sharp-libvips-${Za}/package`),i=`${e4()} ${t4()}`,o=`${s.musl?"musl":"glibc"} ${s.musl||s.glibc}`;a.push("- Update your OS:",` Found ${i}`,` Requires ${o}`)}catch{}throw e&&/\/snap\/core[0-9]{2}/.test(n)&&a.push("- Remove the Node.js Snap, which does not support native modules"," snap remove node"),t&&/Incompatible library version/.test(n)&&a.push("- Update Homebrew:"," brew update && brew upgrade vips"),Ws.some(s=>s.code==="ERR_DLOPEN_DISABLED")&&a.push("- Run Node.js without using the --no-addons flag"),r&&/The specified procedure could not be found/.test(n)&&a.push("- Using the canvas package on Windows?"," See https://sharp.pixelplumbing.com/install#canvas-and-windows","- Check for outdated versions of sharp in the dependency tree:"," npm ls sharp"),a.push("- Consult the installation documentation:"," See https://sharp.pixelplumbing.com/install"),new Error(a.join(`
7
- `))}});var Am=ae((fK,Lm)=>{"use strict";var i4=require("util"),cu=require("stream"),o4=Nr();Ks();var H4=i4.debuglog("sharp"),_4=e=>{Ua.queue.emit("change",e)},Ua=function(e,t){if(arguments.length===1&&!o4.defined(e))throw new Error("Invalid input");return this instanceof Ua?(cu.Duplex.call(this),this.options={topOffsetPre:-1,leftOffsetPre:-1,widthPre:-1,heightPre:-1,topOffsetPost:-1,leftOffsetPost:-1,widthPost:-1,heightPost:-1,width:-1,height:-1,canvas:"crop",position:0,resizeBackground:[0,0,0,255],angle:0,rotationAngle:0,rotationBackground:[0,0,0,255],rotateBefore:!1,orientBefore:!1,flip:!1,flop:!1,extendTop:0,extendBottom:0,extendLeft:0,extendRight:0,extendBackground:[0,0,0,255],extendWith:"background",withoutEnlargement:!1,withoutReduction:!1,affineMatrix:[],affineBackground:[0,0,0,255],affineIdx:0,affineIdy:0,affineOdx:0,affineOdy:0,affineInterpolator:this.constructor.interpolators.bilinear,kernel:"lanczos3",fastShrinkOnLoad:!0,tint:[-1,0,0,0],flatten:!1,flattenBackground:[0,0,0],unflatten:!1,negate:!1,negateAlpha:!0,medianSize:0,blurSigma:0,precision:"integer",minAmpl:.2,sharpenSigma:0,sharpenM1:1,sharpenM2:2,sharpenX1:2,sharpenY2:10,sharpenY3:20,threshold:0,thresholdGrayscale:!0,trimBackground:[],trimThreshold:-1,trimLineArt:!1,dilateWidth:0,erodeWidth:0,gamma:0,gammaOut:0,greyscale:!1,normalise:!1,normaliseLower:1,normaliseUpper:99,claheWidth:0,claheHeight:0,claheMaxSlope:3,brightness:1,saturation:1,hue:0,lightness:0,booleanBufferIn:null,booleanFileIn:"",joinChannelIn:[],extractChannel:-1,removeAlpha:!1,ensureAlpha:-1,colourspace:"srgb",colourspacePipeline:"last",composite:[],fileOut:"",formatOut:"input",streamOut:!1,keepMetadata:0,withMetadataOrientation:-1,withMetadataDensity:0,withIccProfile:"",withExif:{},withExifMerge:!0,withXmp:"",resolveWithObject:!1,loop:-1,delay:[],jpegQuality:80,jpegProgressive:!1,jpegChromaSubsampling:"4:2:0",jpegTrellisQuantisation:!1,jpegOvershootDeringing:!1,jpegOptimiseScans:!1,jpegOptimiseCoding:!0,jpegQuantisationTable:0,pngProgressive:!1,pngCompressionLevel:6,pngAdaptiveFiltering:!1,pngPalette:!1,pngQuality:100,pngEffort:7,pngBitdepth:8,pngDither:1,jp2Quality:80,jp2TileHeight:512,jp2TileWidth:512,jp2Lossless:!1,jp2ChromaSubsampling:"4:4:4",webpQuality:80,webpAlphaQuality:100,webpLossless:!1,webpNearLossless:!1,webpSmartSubsample:!1,webpSmartDeblock:!1,webpPreset:"default",webpEffort:4,webpMinSize:!1,webpMixed:!1,gifBitdepth:8,gifEffort:7,gifDither:1,gifInterFrameMaxError:0,gifInterPaletteMaxError:3,gifKeepDuplicateFrames:!1,gifReuse:!0,gifProgressive:!1,tiffQuality:80,tiffCompression:"jpeg",tiffBigtiff:!1,tiffPredictor:"horizontal",tiffPyramid:!1,tiffMiniswhite:!1,tiffBitdepth:8,tiffTile:!1,tiffTileHeight:256,tiffTileWidth:256,tiffXres:1,tiffYres:1,tiffResolutionUnit:"inch",heifQuality:50,heifLossless:!1,heifCompression:"av1",heifEffort:4,heifChromaSubsampling:"4:4:4",heifBitdepth:8,jxlDistance:1,jxlDecodingTier:0,jxlEffort:7,jxlLossless:!1,rawDepth:"uchar",tileSize:256,tileOverlap:0,tileContainer:"fs",tileLayout:"dz",tileFormat:"last",tileDepth:"last",tileAngle:0,tileSkipBlanks:-1,tileBackground:[255,255,255,255],tileCentre:!1,tileId:"https://example.com/iiif",tileBasename:"",timeoutSeconds:0,linearA:[],linearB:[],pdfBackground:[255,255,255,255],debuglog:r=>{this.emit("warning",r),H4(r)},queueListener:_4},this.options.input=this._createInputDescriptor(e,t,{allowStream:!0}),this):new Ua(e,t)};Object.setPrototypeOf(Ua.prototype,cu.Duplex.prototype);Object.setPrototypeOf(Ua,cu.Duplex);function c4(){let e=this.constructor.call(),{debuglog:t,queueListener:r,...a}=this.options;return e.options=structuredClone(a),e.options.debuglog=t,e.options.queueListener=r,this._isStreamInput()&&this.on("finish",()=>{this._flattenBufferIn(),e.options.input.buffer=this.options.input.buffer,e.emit("finish")}),e}Object.assign(Ua.prototype,{clone:c4});Lm.exports=Ua});var Tm=ae((EK,bm)=>{"use strict";var D=Nr(),$a=Ks(),l4={left:"low",top:"low",low:"low",center:"centre",centre:"centre",right:"high",bottom:"high",high:"high"},u4=["failOn","limitInputPixels","unlimited","animated","autoOrient","density","ignoreIcc","page","pages","sequentialRead","jp2","openSlide","pdf","raw","svg","tiff","failOnError","openSlideLevel","pdfBackground","tiffSubifd"];function gm(e){let t=u4.filter(r=>D.defined(e[r])).map(r=>[r,e[r]]);return t.length?Object.fromEntries(t):void 0}function d4(e,t,r){let a={autoOrient:!1,failOn:"warning",limitInputPixels:268402689,ignoreIcc:!1,unlimited:!1,sequentialRead:!0};if(D.string(e))a.file=e;else if(D.buffer(e)){if(e.length===0)throw Error("Input Buffer is empty");a.buffer=e}else if(D.arrayBuffer(e)){if(e.byteLength===0)throw Error("Input bit Array is empty");a.buffer=Buffer.from(e,0,e.byteLength)}else if(D.typedArray(e)){if(e.length===0)throw Error("Input Bit Array is empty");a.buffer=Buffer.from(e.buffer,e.byteOffset,e.byteLength)}else if(D.plainObject(e)&&!D.defined(t))t=e,gm(t)&&(a.buffer=[]);else if(!D.defined(e)&&!D.defined(t)&&D.object(r)&&r.allowStream)a.buffer=[];else if(Array.isArray(e))if(e.length>1)if(!this.options.joining)this.options.joining=!0,this.options.join=e.map(n=>this._createInputDescriptor(n));else throw new Error("Recursive join is unsupported");else throw new Error("Expected at least two images to join");else throw new Error(`Unsupported input '${e}' of type ${typeof e}${D.defined(t)?` when also providing options of type ${typeof t}`:""}`);if(D.object(t)){if(D.defined(t.failOnError))if(D.bool(t.failOnError))a.failOn=t.failOnError?"warning":"none";else throw D.invalidParameterError("failOnError","boolean",t.failOnError);if(D.defined(t.failOn))if(D.string(t.failOn)&&D.inArray(t.failOn,["none","truncated","error","warning"]))a.failOn=t.failOn;else throw D.invalidParameterError("failOn","one of: none, truncated, error, warning",t.failOn);if(D.defined(t.autoOrient))if(D.bool(t.autoOrient))a.autoOrient=t.autoOrient;else throw D.invalidParameterError("autoOrient","boolean",t.autoOrient);if(D.defined(t.density))if(D.inRange(t.density,1,1e5))a.density=t.density;else throw D.invalidParameterError("density","number between 1 and 100000",t.density);if(D.defined(t.ignoreIcc))if(D.bool(t.ignoreIcc))a.ignoreIcc=t.ignoreIcc;else throw D.invalidParameterError("ignoreIcc","boolean",t.ignoreIcc);if(D.defined(t.limitInputPixels))if(D.bool(t.limitInputPixels))a.limitInputPixels=t.limitInputPixels?16383**2:0;else if(D.integer(t.limitInputPixels)&&D.inRange(t.limitInputPixels,0,Number.MAX_SAFE_INTEGER))a.limitInputPixels=t.limitInputPixels;else throw D.invalidParameterError("limitInputPixels","positive integer",t.limitInputPixels);if(D.defined(t.unlimited))if(D.bool(t.unlimited))a.unlimited=t.unlimited;else throw D.invalidParameterError("unlimited","boolean",t.unlimited);if(D.defined(t.sequentialRead))if(D.bool(t.sequentialRead))a.sequentialRead=t.sequentialRead;else throw D.invalidParameterError("sequentialRead","boolean",t.sequentialRead);if(D.defined(t.raw)){if(D.object(t.raw)&&D.integer(t.raw.width)&&t.raw.width>0&&D.integer(t.raw.height)&&t.raw.height>0&&D.integer(t.raw.channels)&&D.inRange(t.raw.channels,1,4))switch(a.rawWidth=t.raw.width,a.rawHeight=t.raw.height,a.rawChannels=t.raw.channels,e.constructor){case Uint8Array:case Uint8ClampedArray:a.rawDepth="uchar";break;case Int8Array:a.rawDepth="char";break;case Uint16Array:a.rawDepth="ushort";break;case Int16Array:a.rawDepth="short";break;case Uint32Array:a.rawDepth="uint";break;case Int32Array:a.rawDepth="int";break;case Float32Array:a.rawDepth="float";break;case Float64Array:a.rawDepth="double";break;default:a.rawDepth="uchar";break}else throw new Error("Expected width, height and channels for raw pixel input");if(a.rawPremultiplied=!1,D.defined(t.raw.premultiplied))if(D.bool(t.raw.premultiplied))a.rawPremultiplied=t.raw.premultiplied;else throw D.invalidParameterError("raw.premultiplied","boolean",t.raw.premultiplied);if(a.rawPageHeight=0,D.defined(t.raw.pageHeight))if(D.integer(t.raw.pageHeight)&&t.raw.pageHeight>0&&t.raw.pageHeight<=t.raw.height){if(t.raw.height%t.raw.pageHeight!==0)throw new Error(`Expected raw.height ${t.raw.height} to be a multiple of raw.pageHeight ${t.raw.pageHeight}`);a.rawPageHeight=t.raw.pageHeight}else throw D.invalidParameterError("raw.pageHeight","positive integer",t.raw.pageHeight)}if(D.defined(t.animated))if(D.bool(t.animated))a.pages=t.animated?-1:1;else throw D.invalidParameterError("animated","boolean",t.animated);if(D.defined(t.pages))if(D.integer(t.pages)&&D.inRange(t.pages,-1,1e5))a.pages=t.pages;else throw D.invalidParameterError("pages","integer between -1 and 100000",t.pages);if(D.defined(t.page))if(D.integer(t.page)&&D.inRange(t.page,0,1e5))a.page=t.page;else throw D.invalidParameterError("page","integer between 0 and 100000",t.page);if(D.object(t.openSlide)&&D.defined(t.openSlide.level))if(D.integer(t.openSlide.level)&&D.inRange(t.openSlide.level,0,256))a.openSlideLevel=t.openSlide.level;else throw D.invalidParameterError("openSlide.level","integer between 0 and 256",t.openSlide.level);else if(D.defined(t.level))if(D.integer(t.level)&&D.inRange(t.level,0,256))a.openSlideLevel=t.level;else throw D.invalidParameterError("level","integer between 0 and 256",t.level);if(D.object(t.tiff)&&D.defined(t.tiff.subifd))if(D.integer(t.tiff.subifd)&&D.inRange(t.tiff.subifd,-1,1e5))a.tiffSubifd=t.tiff.subifd;else throw D.invalidParameterError("tiff.subifd","integer between -1 and 100000",t.tiff.subifd);else if(D.defined(t.subifd))if(D.integer(t.subifd)&&D.inRange(t.subifd,-1,1e5))a.tiffSubifd=t.subifd;else throw D.invalidParameterError("subifd","integer between -1 and 100000",t.subifd);if(D.object(t.svg)){if(D.defined(t.svg.stylesheet))if(D.string(t.svg.stylesheet))a.svgStylesheet=t.svg.stylesheet;else throw D.invalidParameterError("svg.stylesheet","string",t.svg.stylesheet);if(D.defined(t.svg.highBitdepth))if(D.bool(t.svg.highBitdepth))a.svgHighBitdepth=t.svg.highBitdepth;else throw D.invalidParameterError("svg.highBitdepth","boolean",t.svg.highBitdepth)}if(D.object(t.pdf)&&D.defined(t.pdf.background)?a.pdfBackground=this._getBackgroundColourOption(t.pdf.background):D.defined(t.pdfBackground)&&(a.pdfBackground=this._getBackgroundColourOption(t.pdfBackground)),D.object(t.jp2)&&D.defined(t.jp2.oneshot))if(D.bool(t.jp2.oneshot))a.jp2Oneshot=t.jp2.oneshot;else throw D.invalidParameterError("jp2.oneshot","boolean",t.jp2.oneshot);if(D.defined(t.create))if(D.object(t.create)&&D.integer(t.create.width)&&t.create.width>0&&D.integer(t.create.height)&&t.create.height>0&&D.integer(t.create.channels)){if(a.createWidth=t.create.width,a.createHeight=t.create.height,a.createChannels=t.create.channels,a.createPageHeight=0,D.defined(t.create.pageHeight))if(D.integer(t.create.pageHeight)&&t.create.pageHeight>0&&t.create.pageHeight<=t.create.height){if(t.create.height%t.create.pageHeight!==0)throw new Error(`Expected create.height ${t.create.height} to be a multiple of create.pageHeight ${t.create.pageHeight}`);a.createPageHeight=t.create.pageHeight}else throw D.invalidParameterError("create.pageHeight","positive integer",t.create.pageHeight);if(D.defined(t.create.noise)){if(!D.object(t.create.noise))throw new Error("Expected noise to be an object");if(t.create.noise.type!=="gaussian")throw new Error("Only gaussian noise is supported at the moment");if(a.createNoiseType=t.create.noise.type,!D.inRange(t.create.channels,1,4))throw D.invalidParameterError("create.channels","number between 1 and 4",t.create.channels);if(a.createNoiseMean=128,D.defined(t.create.noise.mean))if(D.number(t.create.noise.mean)&&D.inRange(t.create.noise.mean,0,1e4))a.createNoiseMean=t.create.noise.mean;else throw D.invalidParameterError("create.noise.mean","number between 0 and 10000",t.create.noise.mean);if(a.createNoiseSigma=30,D.defined(t.create.noise.sigma))if(D.number(t.create.noise.sigma)&&D.inRange(t.create.noise.sigma,0,1e4))a.createNoiseSigma=t.create.noise.sigma;else throw D.invalidParameterError("create.noise.sigma","number between 0 and 10000",t.create.noise.sigma)}else if(D.defined(t.create.background)){if(!D.inRange(t.create.channels,3,4))throw D.invalidParameterError("create.channels","number between 3 and 4",t.create.channels);a.createBackground=this._getBackgroundColourOption(t.create.background)}else throw new Error("Expected valid noise or background to create a new input image");delete a.buffer}else throw new Error("Expected valid width, height and channels to create a new input image");if(D.defined(t.text))if(D.object(t.text)&&D.string(t.text.text)){if(a.textValue=t.text.text,D.defined(t.text.height)&&D.defined(t.text.dpi))throw new Error("Expected only one of dpi or height");if(D.defined(t.text.font))if(D.string(t.text.font))a.textFont=t.text.font;else throw D.invalidParameterError("text.font","string",t.text.font);if(D.defined(t.text.fontfile))if(D.string(t.text.fontfile))a.textFontfile=t.text.fontfile;else throw D.invalidParameterError("text.fontfile","string",t.text.fontfile);if(D.defined(t.text.width))if(D.integer(t.text.width)&&t.text.width>0)a.textWidth=t.text.width;else throw D.invalidParameterError("text.width","positive integer",t.text.width);if(D.defined(t.text.height))if(D.integer(t.text.height)&&t.text.height>0)a.textHeight=t.text.height;else throw D.invalidParameterError("text.height","positive integer",t.text.height);if(D.defined(t.text.align))if(D.string(t.text.align)&&D.string(this.constructor.align[t.text.align]))a.textAlign=this.constructor.align[t.text.align];else throw D.invalidParameterError("text.align","valid alignment",t.text.align);if(D.defined(t.text.justify))if(D.bool(t.text.justify))a.textJustify=t.text.justify;else throw D.invalidParameterError("text.justify","boolean",t.text.justify);if(D.defined(t.text.dpi))if(D.integer(t.text.dpi)&&D.inRange(t.text.dpi,1,1e6))a.textDpi=t.text.dpi;else throw D.invalidParameterError("text.dpi","integer between 1 and 1000000",t.text.dpi);if(D.defined(t.text.rgba))if(D.bool(t.text.rgba))a.textRgba=t.text.rgba;else throw D.invalidParameterError("text.rgba","bool",t.text.rgba);if(D.defined(t.text.spacing))if(D.integer(t.text.spacing)&&D.inRange(t.text.spacing,-1e6,1e6))a.textSpacing=t.text.spacing;else throw D.invalidParameterError("text.spacing","integer between -1000000 and 1000000",t.text.spacing);if(D.defined(t.text.wrap))if(D.string(t.text.wrap)&&D.inArray(t.text.wrap,["word","char","word-char","none"]))a.textWrap=t.text.wrap;else throw D.invalidParameterError("text.wrap","one of: word, char, word-char, none",t.text.wrap);delete a.buffer}else throw new Error("Expected a valid string to create an image with text.");if(D.defined(t.join))if(D.defined(this.options.join)){if(D.defined(t.join.animated))if(D.bool(t.join.animated))a.joinAnimated=t.join.animated;else throw D.invalidParameterError("join.animated","boolean",t.join.animated);if(D.defined(t.join.across))if(D.integer(t.join.across)&&D.inRange(t.join.across,1,1e6))a.joinAcross=t.join.across;else throw D.invalidParameterError("join.across","integer between 1 and 100000",t.join.across);if(D.defined(t.join.shim))if(D.integer(t.join.shim)&&D.inRange(t.join.shim,0,1e6))a.joinShim=t.join.shim;else throw D.invalidParameterError("join.shim","integer between 0 and 100000",t.join.shim);if(D.defined(t.join.background)&&(a.joinBackground=this._getBackgroundColourOption(t.join.background)),D.defined(t.join.halign))if(D.string(t.join.halign)&&D.string(this.constructor.align[t.join.halign]))a.joinHalign=this.constructor.align[t.join.halign];else throw D.invalidParameterError("join.halign","valid alignment",t.join.halign);if(D.defined(t.join.valign))if(D.string(t.join.valign)&&D.string(this.constructor.align[t.join.valign]))a.joinValign=this.constructor.align[t.join.valign];else throw D.invalidParameterError("join.valign","valid alignment",t.join.valign)}else throw new Error("Expected input to be an array of images to join")}else if(D.defined(t))throw new Error(`Invalid input options ${t}`);return a}function p4(e,t,r){Array.isArray(this.options.input.buffer)?D.buffer(e)?(this.options.input.buffer.length===0&&this.on("finish",()=>{this.streamInFinished=!0}),this.options.input.buffer.push(e),r()):r(new Error("Non-Buffer data on Writable Stream")):r(new Error("Unexpected data on Writable Stream"))}function h4(){this._isStreamInput()&&(this.options.input.buffer=Buffer.concat(this.options.input.buffer))}function f4(){return Array.isArray(this.options.input.buffer)}function E4(e){let t=Error();return D.fn(e)?(this._isStreamInput()?this.on("finish",()=>{this._flattenBufferIn(),$a.metadata(this.options,(r,a)=>{r?e(D.nativeError(r,t)):e(null,a)})}):$a.metadata(this.options,(r,a)=>{r?e(D.nativeError(r,t)):e(null,a)}),this):this._isStreamInput()?new Promise((r,a)=>{let n=()=>{this._flattenBufferIn(),$a.metadata(this.options,(s,i)=>{s?a(D.nativeError(s,t)):r(i)})};this.writableFinished?n():this.once("finish",n)}):new Promise((r,a)=>{$a.metadata(this.options,(n,s)=>{n?a(D.nativeError(n,t)):r(s)})})}function $4(e){let t=Error();return D.fn(e)?(this._isStreamInput()?this.on("finish",()=>{this._flattenBufferIn(),$a.stats(this.options,(r,a)=>{r?e(D.nativeError(r,t)):e(null,a)})}):$a.stats(this.options,(r,a)=>{r?e(D.nativeError(r,t)):e(null,a)}),this):this._isStreamInput()?new Promise((r,a)=>{this.on("finish",function(){this._flattenBufferIn(),$a.stats(this.options,(n,s)=>{n?a(D.nativeError(n,t)):r(s)})})}):new Promise((r,a)=>{$a.stats(this.options,(n,s)=>{n?a(D.nativeError(n,t)):r(s)})})}bm.exports=e=>{Object.assign(e.prototype,{_inputOptionsFromObject:gm,_createInputDescriptor:d4,_write:p4,_flattenBufferIn:h4,_isStreamInput:f4,metadata:E4,stats:$4}),e.align=l4}});var wm=ae(($K,Cm)=>{"use strict";var He=Nr(),vm={center:0,centre:0,north:1,east:2,south:3,west:4,northeast:5,southeast:6,southwest:7,northwest:8},ym={top:1,right:2,bottom:3,left:4,"right top":5,"right bottom":6,"left bottom":7,"left top":8},xm={background:"background",copy:"copy",repeat:"repeat",mirror:"mirror"},Dm={entropy:16,attention:17},lu={nearest:"nearest",linear:"linear",cubic:"cubic",mitchell:"mitchell",lanczos2:"lanczos2",lanczos3:"lanczos3",mks2013:"mks2013",mks2021:"mks2021"},m4={contain:"contain",cover:"cover",fill:"fill",inside:"inside",outside:"outside"},I4={contain:"embed",cover:"crop",fill:"ignore_aspect",inside:"max",outside:"min"};function uu(e){return e.angle%360!==0||e.rotationAngle!==0}function Bo(e){return e.width!==-1||e.height!==-1}function S4(e,t,r){if(Bo(this.options)&&this.options.debuglog("ignoring previous resize options"),this.options.widthPost!==-1&&this.options.debuglog("operation order will be: extract, resize, extract"),He.defined(e))if(He.object(e)&&!He.defined(r))r=e;else if(He.integer(e)&&e>0)this.options.width=e;else throw He.invalidParameterError("width","positive integer",e);else this.options.width=-1;if(He.defined(t))if(He.integer(t)&&t>0)this.options.height=t;else throw He.invalidParameterError("height","positive integer",t);else this.options.height=-1;if(He.object(r)){if(He.defined(r.width))if(He.integer(r.width)&&r.width>0)this.options.width=r.width;else throw He.invalidParameterError("width","positive integer",r.width);if(He.defined(r.height))if(He.integer(r.height)&&r.height>0)this.options.height=r.height;else throw He.invalidParameterError("height","positive integer",r.height);if(He.defined(r.fit)){let a=I4[r.fit];if(He.string(a))this.options.canvas=a;else throw He.invalidParameterError("fit","valid fit",r.fit)}if(He.defined(r.position)){let a=He.integer(r.position)?r.position:Dm[r.position]||ym[r.position]||vm[r.position];if(He.integer(a)&&(He.inRange(a,0,8)||He.inRange(a,16,17)))this.options.position=a;else throw He.invalidParameterError("position","valid position/gravity/strategy",r.position)}if(this._setBackgroundColourOption("resizeBackground",r.background),He.defined(r.kernel))if(He.string(lu[r.kernel]))this.options.kernel=lu[r.kernel];else throw He.invalidParameterError("kernel","valid kernel name",r.kernel);He.defined(r.withoutEnlargement)&&this._setBooleanOption("withoutEnlargement",r.withoutEnlargement),He.defined(r.withoutReduction)&&this._setBooleanOption("withoutReduction",r.withoutReduction),He.defined(r.fastShrinkOnLoad)&&this._setBooleanOption("fastShrinkOnLoad",r.fastShrinkOnLoad)}return uu(this.options)&&Bo(this.options)&&(this.options.rotateBefore=!0),this}function L4(e){if(He.integer(e)&&e>0)this.options.extendTop=e,this.options.extendBottom=e,this.options.extendLeft=e,this.options.extendRight=e;else if(He.object(e)){if(He.defined(e.top))if(He.integer(e.top)&&e.top>=0)this.options.extendTop=e.top;else throw He.invalidParameterError("top","positive integer",e.top);if(He.defined(e.bottom))if(He.integer(e.bottom)&&e.bottom>=0)this.options.extendBottom=e.bottom;else throw He.invalidParameterError("bottom","positive integer",e.bottom);if(He.defined(e.left))if(He.integer(e.left)&&e.left>=0)this.options.extendLeft=e.left;else throw He.invalidParameterError("left","positive integer",e.left);if(He.defined(e.right))if(He.integer(e.right)&&e.right>=0)this.options.extendRight=e.right;else throw He.invalidParameterError("right","positive integer",e.right);if(this._setBackgroundColourOption("extendBackground",e.background),He.defined(e.extendWith))if(He.string(xm[e.extendWith]))this.options.extendWith=xm[e.extendWith];else throw He.invalidParameterError("extendWith","one of: background, copy, repeat, mirror",e.extendWith)}else throw He.invalidParameterError("extend","integer or object",e);return this}function A4(e){let t=Bo(this.options)||this.options.widthPre!==-1?"Post":"Pre";return this.options[`width${t}`]!==-1&&this.options.debuglog("ignoring previous extract options"),["left","top","width","height"].forEach(function(r){let a=e[r];if(He.integer(a)&&a>=0)this.options[r+(r==="left"||r==="top"?"Offset":"")+t]=a;else throw He.invalidParameterError(r,"integer",a)},this),uu(this.options)&&!Bo(this.options)&&(this.options.widthPre===-1||this.options.widthPost===-1)&&(this.options.rotateBefore=!0),this.options.input.autoOrient&&(this.options.orientBefore=!0),this}function g4(e){if(this.options.trimThreshold=10,He.defined(e))if(He.object(e)){if(He.defined(e.background)&&this._setBackgroundColourOption("trimBackground",e.background),He.defined(e.threshold))if(He.number(e.threshold)&&e.threshold>=0)this.options.trimThreshold=e.threshold;else throw He.invalidParameterError("threshold","positive number",e.threshold);He.defined(e.lineArt)&&this._setBooleanOption("trimLineArt",e.lineArt)}else throw He.invalidParameterError("trim","object",e);return uu(this.options)&&(this.options.rotateBefore=!0),this}Cm.exports=e=>{Object.assign(e.prototype,{resize:S4,extend:L4,extract:A4,trim:g4}),e.gravity=vm,e.strategy=Dm,e.kernel=lu,e.fit=m4,e.position=ym}});var Bm=ae((mK,Nm)=>{"use strict";var Ge=Nr(),du={clear:"clear",source:"source",over:"over",in:"in",out:"out",atop:"atop",dest:"dest","dest-over":"dest-over","dest-in":"dest-in","dest-out":"dest-out","dest-atop":"dest-atop",xor:"xor",add:"add",saturate:"saturate",multiply:"multiply",screen:"screen",overlay:"overlay",darken:"darken",lighten:"lighten","colour-dodge":"colour-dodge","color-dodge":"colour-dodge","colour-burn":"colour-burn","color-burn":"colour-burn","hard-light":"hard-light","soft-light":"soft-light",difference:"difference",exclusion:"exclusion"};function b4(e){if(!Array.isArray(e))throw Ge.invalidParameterError("images to composite","array",e);return this.options.composite=e.map(t=>{if(!Ge.object(t))throw Ge.invalidParameterError("image to composite","object",t);let r=this._inputOptionsFromObject(t),a={input:this._createInputDescriptor(t.input,r,{allowStream:!1}),blend:"over",tile:!1,left:0,top:0,hasOffset:!1,gravity:0,premultiplied:!1};if(Ge.defined(t.blend))if(Ge.string(du[t.blend]))a.blend=du[t.blend];else throw Ge.invalidParameterError("blend","valid blend name",t.blend);if(Ge.defined(t.tile))if(Ge.bool(t.tile))a.tile=t.tile;else throw Ge.invalidParameterError("tile","boolean",t.tile);if(Ge.defined(t.left))if(Ge.integer(t.left))a.left=t.left;else throw Ge.invalidParameterError("left","integer",t.left);if(Ge.defined(t.top))if(Ge.integer(t.top))a.top=t.top;else throw Ge.invalidParameterError("top","integer",t.top);if(Ge.defined(t.top)!==Ge.defined(t.left))throw new Error("Expected both left and top to be set");if(a.hasOffset=Ge.integer(t.top)&&Ge.integer(t.left),Ge.defined(t.gravity))if(Ge.integer(t.gravity)&&Ge.inRange(t.gravity,0,8))a.gravity=t.gravity;else if(Ge.string(t.gravity)&&Ge.integer(this.constructor.gravity[t.gravity]))a.gravity=this.constructor.gravity[t.gravity];else throw Ge.invalidParameterError("gravity","valid gravity",t.gravity);if(Ge.defined(t.premultiplied))if(Ge.bool(t.premultiplied))a.premultiplied=t.premultiplied;else throw Ge.invalidParameterError("premultiplied","boolean",t.premultiplied);return a}),this}Nm.exports=e=>{e.prototype.composite=b4,e.blend=du}});var Om=ae((IK,Rm)=>{"use strict";var P=Nr(),Mm={integer:"integer",float:"float",approximate:"approximate"};function T4(e,t){if(!P.defined(e))return this.autoOrient();if((this.options.angle||this.options.rotationAngle)&&(this.options.debuglog("ignoring previous rotate options"),this.options.angle=0,this.options.rotationAngle=0),P.integer(e)&&!(e%90))this.options.angle=e;else if(P.number(e))this.options.rotationAngle=e,P.object(t)&&t.background&&this._setBackgroundColourOption("rotationBackground",t.background);else throw P.invalidParameterError("angle","numeric",e);return this}function x4(){return this.options.input.autoOrient=!0,this}function v4(e){return this.options.flip=P.bool(e)?e:!0,this}function y4(e){return this.options.flop=P.bool(e)?e:!0,this}function D4(e,t){let r=[].concat(...e);if(r.length===4&&r.every(P.number))this.options.affineMatrix=r;else throw P.invalidParameterError("matrix","1x4 or 2x2 array",e);if(P.defined(t))if(P.object(t)){if(this._setBackgroundColourOption("affineBackground",t.background),P.defined(t.idx))if(P.number(t.idx))this.options.affineIdx=t.idx;else throw P.invalidParameterError("options.idx","number",t.idx);if(P.defined(t.idy))if(P.number(t.idy))this.options.affineIdy=t.idy;else throw P.invalidParameterError("options.idy","number",t.idy);if(P.defined(t.odx))if(P.number(t.odx))this.options.affineOdx=t.odx;else throw P.invalidParameterError("options.odx","number",t.odx);if(P.defined(t.ody))if(P.number(t.ody))this.options.affineOdy=t.ody;else throw P.invalidParameterError("options.ody","number",t.ody);if(P.defined(t.interpolator))if(P.inArray(t.interpolator,Object.values(this.constructor.interpolators)))this.options.affineInterpolator=t.interpolator;else throw P.invalidParameterError("options.interpolator","valid interpolator name",t.interpolator)}else throw P.invalidParameterError("options","object",t);return this}function C4(e,t,r){if(!P.defined(e))this.options.sharpenSigma=-1;else if(P.bool(e))this.options.sharpenSigma=e?-1:0;else if(P.number(e)&&P.inRange(e,.01,1e4)){if(this.options.sharpenSigma=e,P.defined(t))if(P.number(t)&&P.inRange(t,0,1e4))this.options.sharpenM1=t;else throw P.invalidParameterError("flat","number between 0 and 10000",t);if(P.defined(r))if(P.number(r)&&P.inRange(r,0,1e4))this.options.sharpenM2=r;else throw P.invalidParameterError("jagged","number between 0 and 10000",r)}else if(P.plainObject(e)){if(P.number(e.sigma)&&P.inRange(e.sigma,1e-6,10))this.options.sharpenSigma=e.sigma;else throw P.invalidParameterError("options.sigma","number between 0.000001 and 10",e.sigma);if(P.defined(e.m1))if(P.number(e.m1)&&P.inRange(e.m1,0,1e6))this.options.sharpenM1=e.m1;else throw P.invalidParameterError("options.m1","number between 0 and 1000000",e.m1);if(P.defined(e.m2))if(P.number(e.m2)&&P.inRange(e.m2,0,1e6))this.options.sharpenM2=e.m2;else throw P.invalidParameterError("options.m2","number between 0 and 1000000",e.m2);if(P.defined(e.x1))if(P.number(e.x1)&&P.inRange(e.x1,0,1e6))this.options.sharpenX1=e.x1;else throw P.invalidParameterError("options.x1","number between 0 and 1000000",e.x1);if(P.defined(e.y2))if(P.number(e.y2)&&P.inRange(e.y2,0,1e6))this.options.sharpenY2=e.y2;else throw P.invalidParameterError("options.y2","number between 0 and 1000000",e.y2);if(P.defined(e.y3))if(P.number(e.y3)&&P.inRange(e.y3,0,1e6))this.options.sharpenY3=e.y3;else throw P.invalidParameterError("options.y3","number between 0 and 1000000",e.y3)}else throw P.invalidParameterError("sigma","number between 0.01 and 10000",e);return this}function w4(e){if(!P.defined(e))this.options.medianSize=3;else if(P.integer(e)&&P.inRange(e,1,1e3))this.options.medianSize=e;else throw P.invalidParameterError("size","integer between 1 and 1000",e);return this}function N4(e){let t;if(P.number(e))t=e;else if(P.plainObject(e)){if(!P.number(e.sigma))throw P.invalidParameterError("options.sigma","number between 0.3 and 1000",t);if(t=e.sigma,"precision"in e)if(P.string(Mm[e.precision]))this.options.precision=Mm[e.precision];else throw P.invalidParameterError("precision","one of: integer, float, approximate",e.precision);if("minAmplitude"in e)if(P.number(e.minAmplitude)&&P.inRange(e.minAmplitude,.001,1))this.options.minAmpl=e.minAmplitude;else throw P.invalidParameterError("minAmplitude","number between 0.001 and 1",e.minAmplitude)}if(!P.defined(e))this.options.blurSigma=-1;else if(P.bool(e))this.options.blurSigma=e?-1:0;else if(P.number(t)&&P.inRange(t,.3,1e3))this.options.blurSigma=t;else throw P.invalidParameterError("sigma","number between 0.3 and 1000",t);return this}function Pm(e){if(!P.defined(e))this.options.dilateWidth=1;else if(P.integer(e)&&e>0)this.options.dilateWidth=e;else throw P.invalidParameterError("dilate","positive integer",Pm);return this}function km(e){if(!P.defined(e))this.options.erodeWidth=1;else if(P.integer(e)&&e>0)this.options.erodeWidth=e;else throw P.invalidParameterError("erode","positive integer",km);return this}function B4(e){return this.options.flatten=P.bool(e)?e:!0,P.object(e)&&this._setBackgroundColourOption("flattenBackground",e.background),this}function M4(){return this.options.unflatten=!0,this}function P4(e,t){if(!P.defined(e))this.options.gamma=2.2;else if(P.number(e)&&P.inRange(e,1,3))this.options.gamma=e;else throw P.invalidParameterError("gamma","number between 1.0 and 3.0",e);if(!P.defined(t))this.options.gammaOut=this.options.gamma;else if(P.number(t)&&P.inRange(t,1,3))this.options.gammaOut=t;else throw P.invalidParameterError("gammaOut","number between 1.0 and 3.0",t);return this}function k4(e){if(this.options.negate=P.bool(e)?e:!0,P.plainObject(e)&&"alpha"in e)if(P.bool(e.alpha))this.options.negateAlpha=e.alpha;else throw P.invalidParameterError("alpha","should be boolean value",e.alpha);return this}function R4(e){if(P.plainObject(e)){if(P.defined(e.lower))if(P.number(e.lower)&&P.inRange(e.lower,0,99))this.options.normaliseLower=e.lower;else throw P.invalidParameterError("lower","number between 0 and 99",e.lower);if(P.defined(e.upper))if(P.number(e.upper)&&P.inRange(e.upper,1,100))this.options.normaliseUpper=e.upper;else throw P.invalidParameterError("upper","number between 1 and 100",e.upper)}if(this.options.normaliseLower>=this.options.normaliseUpper)throw P.invalidParameterError("range","lower to be less than upper",`${this.options.normaliseLower} >= ${this.options.normaliseUpper}`);return this.options.normalise=!0,this}function O4(e){return this.normalise(e)}function G4(e){if(P.plainObject(e)){if(P.integer(e.width)&&e.width>0)this.options.claheWidth=e.width;else throw P.invalidParameterError("width","integer greater than zero",e.width);if(P.integer(e.height)&&e.height>0)this.options.claheHeight=e.height;else throw P.invalidParameterError("height","integer greater than zero",e.height);if(P.defined(e.maxSlope))if(P.integer(e.maxSlope)&&P.inRange(e.maxSlope,0,100))this.options.claheMaxSlope=e.maxSlope;else throw P.invalidParameterError("maxSlope","integer between 0 and 100",e.maxSlope)}else throw P.invalidParameterError("options","plain object",e);return this}function F4(e){if(!P.object(e)||!Array.isArray(e.kernel)||!P.integer(e.width)||!P.integer(e.height)||!P.inRange(e.width,3,1001)||!P.inRange(e.height,3,1001)||e.height*e.width!==e.kernel.length)throw new Error("Invalid convolution kernel");return P.integer(e.scale)||(e.scale=e.kernel.reduce((t,r)=>t+r,0)),e.scale<1&&(e.scale=1),P.integer(e.offset)||(e.offset=0),this.options.convKernel=e,this}function Z4(e,t){if(!P.defined(e))this.options.threshold=128;else if(P.bool(e))this.options.threshold=e?128:0;else if(P.integer(e)&&P.inRange(e,0,255))this.options.threshold=e;else throw P.invalidParameterError("threshold","integer between 0 and 255",e);return!P.object(t)||t.greyscale===!0||t.grayscale===!0?this.options.thresholdGrayscale=!0:this.options.thresholdGrayscale=!1,this}function U4(e,t,r){if(this.options.boolean=this._createInputDescriptor(e,r),P.string(t)&&P.inArray(t,["and","or","eor"]))this.options.booleanOp=t;else throw P.invalidParameterError("operator","one of: and, or, eor",t);return this}function W4(e,t){if(!P.defined(e)&&P.number(t)?e=1:P.number(e)&&!P.defined(t)&&(t=0),!P.defined(e))this.options.linearA=[];else if(P.number(e))this.options.linearA=[e];else if(Array.isArray(e)&&e.length&&e.every(P.number))this.options.linearA=e;else throw P.invalidParameterError("a","number or array of numbers",e);if(!P.defined(t))this.options.linearB=[];else if(P.number(t))this.options.linearB=[t];else if(Array.isArray(t)&&t.length&&t.every(P.number))this.options.linearB=t;else throw P.invalidParameterError("b","number or array of numbers",t);if(this.options.linearA.length!==this.options.linearB.length)throw new Error("Expected a and b to be arrays of the same length");return this}function K4(e){if(!Array.isArray(e))throw P.invalidParameterError("inputMatrix","array",e);if(e.length!==3&&e.length!==4)throw P.invalidParameterError("inputMatrix","3x3 or 4x4 array",e.length);let t=e.flat().map(Number);if(t.length!==9&&t.length!==16)throw P.invalidParameterError("inputMatrix","cardinality of 9 or 16",t.length);return this.options.recombMatrix=t,this}function V4(e){if(!P.plainObject(e))throw P.invalidParameterError("options","plain object",e);if("brightness"in e)if(P.number(e.brightness)&&e.brightness>=0)this.options.brightness=e.brightness;else throw P.invalidParameterError("brightness","number above zero",e.brightness);if("saturation"in e)if(P.number(e.saturation)&&e.saturation>=0)this.options.saturation=e.saturation;else throw P.invalidParameterError("saturation","number above zero",e.saturation);if("hue"in e)if(P.integer(e.hue))this.options.hue=e.hue%360;else throw P.invalidParameterError("hue","number",e.hue);if("lightness"in e)if(P.number(e.lightness))this.options.lightness=e.lightness;else throw P.invalidParameterError("lightness","number",e.lightness);return this}Rm.exports=e=>{Object.assign(e.prototype,{autoOrient:x4,rotate:T4,flip:v4,flop:y4,affine:D4,sharpen:C4,erode:km,dilate:Pm,median:w4,blur:N4,flatten:B4,unflatten:M4,gamma:P4,negate:k4,normalise:R4,normalize:O4,clahe:G4,convolve:F4,threshold:Z4,boolean:U4,linear:W4,recomb:K4,modulate:V4})}});var Km=ae((SK,Wm)=>{"use strict";var $u=Object.defineProperty,j4=Object.getOwnPropertyDescriptor,q4=Object.getOwnPropertyNames,X4=Object.prototype.hasOwnProperty,z4=(e,t)=>{for(var r in t)$u(e,r,{get:t[r],enumerable:!0})},J4=(e,t,r,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of q4(t))!X4.call(e,n)&&n!==r&&$u(e,n,{get:()=>t[n],enumerable:!(a=j4(t,n))||a.enumerable});return e},Q4=e=>J4($u({},"__esModule",{value:!0}),e),Gm={};z4(Gm,{default:()=>u8});Wm.exports=Q4(Gm);var pu={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]};for(let e in pu)Object.freeze(pu[e]);var Rr=Object.freeze(pu),Fm=Object.create(null);for(let e in Rr)Object.hasOwn(Rr,e)&&(Fm[Rr[e]]=e);var qt={to:{},get:{}};qt.get=function(e){let t=e.slice(0,3).toLowerCase(),r,a;switch(t){case"hsl":{r=qt.get.hsl(e),a="hsl";break}case"hwb":{r=qt.get.hwb(e),a="hwb";break}default:{r=qt.get.rgb(e),a="rgb";break}}return r?{model:a,value:r}:null};qt.get.rgb=function(e){if(!e)return null;let t=/^#([a-f\d]{3,4})$/i,r=/^#([a-f\d]{6})([a-f\d]{2})?$/i,a=/^rgba?\(\s*([+-]?(?:\d*\.)?\d+(?:e\d+)?)(?=[\s,])\s*(?:,\s*)?([+-]?(?:\d*\.)?\d+(?:e\d+)?)(?=[\s,])\s*(?:,\s*)?([+-]?(?:\d*\.)?\d+(?:e\d+)?)\s*(?:[\s,|/]\s*([+-]?(?:\d*\.)?\d+(?:e\d+)?)(%?)\s*)?\)$/i,n=/^rgba?\(\s*([+-]?[\d.]+)%\s*,?\s*([+-]?[\d.]+)%\s*,?\s*([+-]?[\d.]+)%\s*(?:[\s,|/]\s*([+-]?[\d.]+)(%?)\s*)?\)$/i,s=/^(\w+)$/,i=[0,0,0,1],o,H,_;if(o=e.match(r)){for(_=o[2],o=o[1],H=0;H<3;H++){let c=H*2;i[H]=Number.parseInt(o.slice(c,c+2),16)}_&&(i[3]=Number.parseInt(_,16)/255)}else if(o=e.match(t)){for(o=o[1],_=o[3],H=0;H<3;H++)i[H]=Number.parseInt(o[H]+o[H],16);_&&(i[3]=Number.parseInt(_+_,16)/255)}else if(o=e.match(a)){for(H=0;H<3;H++)i[H]=Number.parseFloat(o[H+1]);o[4]&&(i[3]=o[5]?Number.parseFloat(o[4])*.01:Number.parseFloat(o[4]))}else if(o=e.match(n)){for(H=0;H<3;H++)i[H]=Math.round(Number.parseFloat(o[H+1])*2.55);o[4]&&(i[3]=o[5]?Number.parseFloat(o[4])*.01:Number.parseFloat(o[4]))}else return(o=e.toLowerCase().match(s))?o[1]==="transparent"?[0,0,0,0]:Object.hasOwn(Rr,o[1])?(i=Rr[o[1]].slice(),i[3]=1,i):null:null;for(H=0;H<3;H++)i[H]=ma(i[H],0,255);return i[3]=ma(i[3],0,1),i};qt.get.hsl=function(e){if(!e)return null;let t=/^hsla?\(\s*([+-]?(?:\d{0,3}\.)?\d+)(?:deg)?\s*,?\s*([+-]?[\d.]+)%\s*,?\s*([+-]?[\d.]+)%\s*(?:[,|/]\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:e[+-]?\d+)?)\s*)?\)$/i,r=e.match(t);if(r){let a=Number.parseFloat(r[4]),n=(Number.parseFloat(r[1])%360+360)%360,s=ma(Number.parseFloat(r[2]),0,100),i=ma(Number.parseFloat(r[3]),0,100),o=ma(Number.isNaN(a)?1:a,0,1);return[n,s,i,o]}return null};qt.get.hwb=function(e){if(!e)return null;let t=/^hwb\(\s*([+-]?\d{0,3}(?:\.\d+)?)(?:deg)?\s*[\s,]\s*([+-]?[\d.]+)%\s*[\s,]\s*([+-]?[\d.]+)%\s*(?:[\s,]\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:e[+-]?\d+)?)\s*)?\)$/i,r=e.match(t);if(r){let a=Number.parseFloat(r[4]),n=(Number.parseFloat(r[1])%360+360)%360,s=ma(Number.parseFloat(r[2]),0,100),i=ma(Number.parseFloat(r[3]),0,100),o=ma(Number.isNaN(a)?1:a,0,1);return[n,s,i,o]}return null};qt.to.hex=function(...e){return"#"+Mo(e[0])+Mo(e[1])+Mo(e[2])+(e[3]<1?Mo(Math.round(e[3]*255)):"")};qt.to.rgb=function(...e){return e.length<4||e[3]===1?"rgb("+Math.round(e[0])+", "+Math.round(e[1])+", "+Math.round(e[2])+")":"rgba("+Math.round(e[0])+", "+Math.round(e[1])+", "+Math.round(e[2])+", "+e[3]+")"};qt.to.rgb.percent=function(...e){let t=Math.round(e[0]/255*100),r=Math.round(e[1]/255*100),a=Math.round(e[2]/255*100);return e.length<4||e[3]===1?"rgb("+t+"%, "+r+"%, "+a+"%)":"rgba("+t+"%, "+r+"%, "+a+"%, "+e[3]+")"};qt.to.hsl=function(...e){return e.length<4||e[3]===1?"hsl("+e[0]+", "+e[1]+"%, "+e[2]+"%)":"hsla("+e[0]+", "+e[1]+"%, "+e[2]+"%, "+e[3]+")"};qt.to.hwb=function(...e){let t="";return e.length>=4&&e[3]!==1&&(t=", "+e[3]),"hwb("+e[0]+", "+e[1]+"%, "+e[2]+"%"+t+")"};qt.to.keyword=function(...e){return Fm[e.slice(0,3)]};function ma(e,t,r){return Math.min(Math.max(t,e),r)}function Mo(e){let t=Math.round(e).toString(16).toUpperCase();return t.length<2?"0"+t:t}var Un=qt,Zm={};for(let e of Object.keys(Rr))Zm[Rr[e]]=e;var re={rgb:{channels:3,labels:"rgb"},hsl:{channels:3,labels:"hsl"},hsv:{channels:3,labels:"hsv"},hwb:{channels:3,labels:"hwb"},cmyk:{channels:4,labels:"cmyk"},xyz:{channels:3,labels:"xyz"},lab:{channels:3,labels:"lab"},oklab:{channels:3,labels:["okl","oka","okb"]},lch:{channels:3,labels:"lch"},oklch:{channels:3,labels:["okl","okc","okh"]},hex:{channels:1,labels:["hex"]},keyword:{channels:1,labels:["keyword"]},ansi16:{channels:1,labels:["ansi16"]},ansi256:{channels:1,labels:["ansi256"]},hcg:{channels:3,labels:["h","c","g"]},apple:{channels:3,labels:["r16","g16","b16"]},gray:{channels:1,labels:["gray"]}},Wa=re,na=(6/29)**3;function Kn(e){let t=e>.0031308?1.055*e**.4166666666666667-.055:e*12.92;return Math.min(Math.max(0,t),1)}function Vn(e){return e>.04045?((e+.055)/1.055)**2.4:e/12.92}for(let e of Object.keys(re)){if(!("channels"in re[e]))throw new Error("missing channels property: "+e);if(!("labels"in re[e]))throw new Error("missing channel labels property: "+e);if(re[e].labels.length!==re[e].channels)throw new Error("channel and label counts mismatch: "+e);let{channels:t,labels:r}=re[e];delete re[e].channels,delete re[e].labels,Object.defineProperty(re[e],"channels",{value:t}),Object.defineProperty(re[e],"labels",{value:r})}re.rgb.hsl=function(e){let t=e[0]/255,r=e[1]/255,a=e[2]/255,n=Math.min(t,r,a),s=Math.max(t,r,a),i=s-n,o,H;switch(s){case n:{o=0;break}case t:{o=(r-a)/i;break}case r:{o=2+(a-t)/i;break}case a:{o=4+(t-r)/i;break}}o=Math.min(o*60,360),o<0&&(o+=360);let _=(n+s)/2;return s===n?H=0:_<=.5?H=i/(s+n):H=i/(2-s-n),[o,H*100,_*100]};re.rgb.hsv=function(e){let t,r,a,n,s,i=e[0]/255,o=e[1]/255,H=e[2]/255,_=Math.max(i,o,H),c=_-Math.min(i,o,H),l=function(d){return(_-d)/6/c+1/2};if(c===0)n=0,s=0;else{switch(s=c/_,t=l(i),r=l(o),a=l(H),_){case i:{n=a-r;break}case o:{n=1/3+t-a;break}case H:{n=2/3+r-t;break}}n<0?n+=1:n>1&&(n-=1)}return[n*360,s*100,_*100]};re.rgb.hwb=function(e){let t=e[0],r=e[1],a=e[2],n=re.rgb.hsl(e)[0],s=1/255*Math.min(t,Math.min(r,a));return a=1-1/255*Math.max(t,Math.max(r,a)),[n,s*100,a*100]};re.rgb.oklab=function(e){let t=Vn(e[0]/255),r=Vn(e[1]/255),a=Vn(e[2]/255),n=Math.cbrt(.4122214708*t+.5363325363*r+.0514459929*a),s=Math.cbrt(.2119034982*t+.6806995451*r+.1073969566*a),i=Math.cbrt(.0883024619*t+.2817188376*r+.6299787005*a),o=.2104542553*n+.793617785*s-.0040720468*i,H=1.9779984951*n-2.428592205*s+.4505937099*i,_=.0259040371*n+.7827717662*s-.808675766*i;return[o*100,H*100,_*100]};re.rgb.cmyk=function(e){let t=e[0]/255,r=e[1]/255,a=e[2]/255,n=Math.min(1-t,1-r,1-a),s=(1-t-n)/(1-n)||0,i=(1-r-n)/(1-n)||0,o=(1-a-n)/(1-n)||0;return[s*100,i*100,o*100,n*100]};function Y4(e,t){return(e[0]-t[0])**2+(e[1]-t[1])**2+(e[2]-t[2])**2}re.rgb.keyword=function(e){let t=Zm[e];if(t)return t;let r=Number.POSITIVE_INFINITY,a;for(let n of Object.keys(Rr)){let s=Rr[n],i=Y4(e,s);i<r&&(r=i,a=n)}return a};re.keyword.rgb=function(e){return[...Rr[e]]};re.rgb.xyz=function(e){let t=Vn(e[0]/255),r=Vn(e[1]/255),a=Vn(e[2]/255),n=t*.4124564+r*.3575761+a*.1804375,s=t*.2126729+r*.7151522+a*.072175,i=t*.0193339+r*.119192+a*.9503041;return[n*100,s*100,i*100]};re.rgb.lab=function(e){let t=re.rgb.xyz(e),r=t[0],a=t[1],n=t[2];r/=95.047,a/=100,n/=108.883,r=r>na?r**(1/3):7.787*r+16/116,a=a>na?a**(1/3):7.787*a+16/116,n=n>na?n**(1/3):7.787*n+16/116;let s=116*a-16,i=500*(r-a),o=200*(a-n);return[s,i,o]};re.hsl.rgb=function(e){let t=e[0]/360,r=e[1]/100,a=e[2]/100,n,s;if(r===0)return s=a*255,[s,s,s];let i=a<.5?a*(1+r):a+r-a*r,o=2*a-i,H=[0,0,0];for(let _=0;_<3;_++)n=t+1/3*-(_-1),n<0&&n++,n>1&&n--,6*n<1?s=o+(i-o)*6*n:2*n<1?s=i:3*n<2?s=o+(i-o)*(2/3-n)*6:s=o,H[_]=s*255;return H};re.hsl.hsv=function(e){let t=e[0],r=e[1]/100,a=e[2]/100,n=r,s=Math.max(a,.01);a*=2,r*=a<=1?a:2-a,n*=s<=1?s:2-s;let i=(a+r)/2,o=a===0?2*n/(s+n):2*r/(a+r);return[t,o*100,i*100]};re.hsv.rgb=function(e){let t=e[0]/60,r=e[1]/100,a=e[2]/100,n=Math.floor(t)%6,s=t-Math.floor(t),i=255*a*(1-r),o=255*a*(1-r*s),H=255*a*(1-r*(1-s));switch(a*=255,n){case 0:return[a,H,i];case 1:return[o,a,i];case 2:return[i,a,H];case 3:return[i,o,a];case 4:return[H,i,a];case 5:return[a,i,o]}};re.hsv.hsl=function(e){let t=e[0],r=e[1]/100,a=e[2]/100,n=Math.max(a,.01),s,i;i=(2-r)*a;let o=(2-r)*n;return s=r*n,s/=o<=1?o:2-o,s=s||0,i/=2,[t,s*100,i*100]};re.hwb.rgb=function(e){let t=e[0]/360,r=e[1]/100,a=e[2]/100,n=r+a,s;n>1&&(r/=n,a/=n);let i=Math.floor(6*t),o=1-a;s=6*t-i,(i&1)!==0&&(s=1-s);let H=r+s*(o-r),_,c,l;switch(i){default:case 6:case 0:{_=o,c=H,l=r;break}case 1:{_=H,c=o,l=r;break}case 2:{_=r,c=o,l=H;break}case 3:{_=r,c=H,l=o;break}case 4:{_=H,c=r,l=o;break}case 5:{_=o,c=r,l=H;break}}return[_*255,c*255,l*255]};re.cmyk.rgb=function(e){let t=e[0]/100,r=e[1]/100,a=e[2]/100,n=e[3]/100,s=1-Math.min(1,t*(1-n)+n),i=1-Math.min(1,r*(1-n)+n),o=1-Math.min(1,a*(1-n)+n);return[s*255,i*255,o*255]};re.xyz.rgb=function(e){let t=e[0]/100,r=e[1]/100,a=e[2]/100,n,s,i;return n=t*3.2404542+r*-1.5371385+a*-.4985314,s=t*-.969266+r*1.8760108+a*.041556,i=t*.0556434+r*-.2040259+a*1.0572252,n=Kn(n),s=Kn(s),i=Kn(i),[n*255,s*255,i*255]};re.xyz.lab=function(e){let t=e[0],r=e[1],a=e[2];t/=95.047,r/=100,a/=108.883,t=t>na?t**(1/3):7.787*t+16/116,r=r>na?r**(1/3):7.787*r+16/116,a=a>na?a**(1/3):7.787*a+16/116;let n=116*r-16,s=500*(t-r),i=200*(r-a);return[n,s,i]};re.xyz.oklab=function(e){let t=e[0]/100,r=e[1]/100,a=e[2]/100,n=Math.cbrt(.8189330101*t+.3618667424*r-.1288597137*a),s=Math.cbrt(.0329845436*t+.9293118715*r+.0361456387*a),i=Math.cbrt(.0482003018*t+.2643662691*r+.633851707*a),o=.2104542553*n+.793617785*s-.0040720468*i,H=1.9779984951*n-2.428592205*s+.4505937099*i,_=.0259040371*n+.7827717662*s-.808675766*i;return[o*100,H*100,_*100]};re.oklab.oklch=function(e){return re.lab.lch(e)};re.oklab.xyz=function(e){let t=e[0]/100,r=e[1]/100,a=e[2]/100,n=(.999999998*t+.396337792*r+.215803758*a)**3,s=(1.000000008*t-.105561342*r-.063854175*a)**3,i=(1.000000055*t-.089484182*r-1.291485538*a)**3,o=1.227013851*n-.55779998*s+.281256149*i,H=-.040580178*n+1.11225687*s-.071676679*i,_=-.076381285*n-.421481978*s+1.58616322*i;return[o*100,H*100,_*100]};re.oklab.rgb=function(e){let t=e[0]/100,r=e[1]/100,a=e[2]/100,n=(t+.3963377774*r+.2158037573*a)**3,s=(t-.1055613458*r-.0638541728*a)**3,i=(t-.0894841775*r-1.291485548*a)**3,o=Kn(4.0767416621*n-3.3077115913*s+.2309699292*i),H=Kn(-1.2684380046*n+2.6097574011*s-.3413193965*i),_=Kn(-.0041960863*n-.7034186147*s+1.707614701*i);return[o*255,H*255,_*255]};re.oklch.oklab=function(e){return re.lch.lab(e)};re.lab.xyz=function(e){let t=e[0],r=e[1],a=e[2],n,s,i;s=(t+16)/116,n=r/500+s,i=s-a/200;let o=s**3,H=n**3,_=i**3;return s=o>na?o:(s-16/116)/7.787,n=H>na?H:(n-16/116)/7.787,i=_>na?_:(i-16/116)/7.787,n*=95.047,s*=100,i*=108.883,[n,s,i]};re.lab.lch=function(e){let t=e[0],r=e[1],a=e[2],n;n=Math.atan2(a,r)*360/2/Math.PI,n<0&&(n+=360);let i=Math.sqrt(r*r+a*a);return[t,i,n]};re.lch.lab=function(e){let t=e[0],r=e[1],n=e[2]/360*2*Math.PI,s=r*Math.cos(n),i=r*Math.sin(n);return[t,s,i]};re.rgb.ansi16=function(e,t=null){let[r,a,n]=e,s=t===null?re.rgb.hsv(e)[2]:t;if(s=Math.round(s/50),s===0)return 30;let i=30+(Math.round(n/255)<<2|Math.round(a/255)<<1|Math.round(r/255));return s===2&&(i+=60),i};re.hsv.ansi16=function(e){return re.rgb.ansi16(re.hsv.rgb(e),e[2])};re.rgb.ansi256=function(e){let t=e[0],r=e[1],a=e[2];return t>>4===r>>4&&r>>4===a>>4?t<8?16:t>248?231:Math.round((t-8)/247*24)+232:16+36*Math.round(t/255*5)+6*Math.round(r/255*5)+Math.round(a/255*5)};re.ansi16.rgb=function(e){e=e[0];let t=e%10;if(t===0||t===7)return e>50&&(t+=3.5),t=t/10.5*255,[t,t,t];let r=(Math.trunc(e>50)+1)*.5,a=(t&1)*r*255,n=(t>>1&1)*r*255,s=(t>>2&1)*r*255;return[a,n,s]};re.ansi256.rgb=function(e){if(e=e[0],e>=232){let s=(e-232)*10+8;return[s,s,s]}e-=16;let t,r=Math.floor(e/36)/5*255,a=Math.floor((t=e%36)/6)/5*255,n=t%6/5*255;return[r,a,n]};re.rgb.hex=function(e){let r=(((Math.round(e[0])&255)<<16)+((Math.round(e[1])&255)<<8)+(Math.round(e[2])&255)).toString(16).toUpperCase();return"000000".slice(r.length)+r};re.hex.rgb=function(e){let t=e.toString(16).match(/[a-f\d]{6}|[a-f\d]{3}/i);if(!t)return[0,0,0];let r=t[0];t[0].length===3&&(r=[...r].map(o=>o+o).join(""));let a=Number.parseInt(r,16),n=a>>16&255,s=a>>8&255,i=a&255;return[n,s,i]};re.rgb.hcg=function(e){let t=e[0]/255,r=e[1]/255,a=e[2]/255,n=Math.max(Math.max(t,r),a),s=Math.min(Math.min(t,r),a),i=n-s,o,H=i<1?s/(1-i):0;return i<=0?o=0:n===t?o=(r-a)/i%6:n===r?o=2+(a-t)/i:o=4+(t-r)/i,o/=6,o%=1,[o*360,i*100,H*100]};re.hsl.hcg=function(e){let t=e[1]/100,r=e[2]/100,a=r<.5?2*t*r:2*t*(1-r),n=0;return a<1&&(n=(r-.5*a)/(1-a)),[e[0],a*100,n*100]};re.hsv.hcg=function(e){let t=e[1]/100,r=e[2]/100,a=t*r,n=0;return a<1&&(n=(r-a)/(1-a)),[e[0],a*100,n*100]};re.hcg.rgb=function(e){let t=e[0]/360,r=e[1]/100,a=e[2]/100;if(r===0)return[a*255,a*255,a*255];let n=[0,0,0],s=t%1*6,i=s%1,o=1-i,H=0;switch(Math.floor(s)){case 0:{n[0]=1,n[1]=i,n[2]=0;break}case 1:{n[0]=o,n[1]=1,n[2]=0;break}case 2:{n[0]=0,n[1]=1,n[2]=i;break}case 3:{n[0]=0,n[1]=o,n[2]=1;break}case 4:{n[0]=i,n[1]=0,n[2]=1;break}default:n[0]=1,n[1]=0,n[2]=o}return H=(1-r)*a,[(r*n[0]+H)*255,(r*n[1]+H)*255,(r*n[2]+H)*255]};re.hcg.hsv=function(e){let t=e[1]/100,r=e[2]/100,a=t+r*(1-t),n=0;return a>0&&(n=t/a),[e[0],n*100,a*100]};re.hcg.hsl=function(e){let t=e[1]/100,a=e[2]/100*(1-t)+.5*t,n=0;return a>0&&a<.5?n=t/(2*a):a>=.5&&a<1&&(n=t/(2*(1-a))),[e[0],n*100,a*100]};re.hcg.hwb=function(e){let t=e[1]/100,r=e[2]/100,a=t+r*(1-t);return[e[0],(a-t)*100,(1-a)*100]};re.hwb.hcg=function(e){let t=e[1]/100,a=1-e[2]/100,n=a-t,s=0;return n<1&&(s=(a-n)/(1-n)),[e[0],n*100,s*100]};re.apple.rgb=function(e){return[e[0]/65535*255,e[1]/65535*255,e[2]/65535*255]};re.rgb.apple=function(e){return[e[0]/255*65535,e[1]/255*65535,e[2]/255*65535]};re.gray.rgb=function(e){return[e[0]/100*255,e[0]/100*255,e[0]/100*255]};re.gray.hsl=function(e){return[0,0,e[0]]};re.gray.hsv=re.gray.hsl;re.gray.hwb=function(e){return[0,100,e[0]]};re.gray.cmyk=function(e){return[0,0,0,e[0]]};re.gray.lab=function(e){return[e[0],0,0]};re.gray.hex=function(e){let t=Math.round(e[0]/100*255)&255,a=((t<<16)+(t<<8)+t).toString(16).toUpperCase();return"000000".slice(a.length)+a};re.rgb.gray=function(e){return[(e[0]+e[1]+e[2])/3/255*100]};function e8(){let e={},t=Object.keys(Wa);for(let{length:r}=t,a=0;a<r;a++)e[t[a]]={distance:-1,parent:null};return e}function t8(e){let t=e8(),r=[e];for(t[e].distance=0;r.length>0;){let a=r.pop(),n=Object.keys(Wa[a]);for(let{length:s}=n,i=0;i<s;i++){let o=n[i],H=t[o];H.distance===-1&&(H.distance=t[a].distance+1,H.parent=a,r.unshift(o))}}return t}function r8(e,t){return function(r){return t(e(r))}}function a8(e,t){let r=[t[e].parent,e],a=Wa[t[e].parent][e],n=t[e].parent;for(;t[n].parent;)r.unshift(t[n].parent),a=r8(Wa[t[n].parent][n],a),n=t[n].parent;return a.conversion=r,a}function n8(e){let t=t8(e),r={},a=Object.keys(t);for(let{length:n}=a,s=0;s<n;s++){let i=a[s];t[i].parent!==null&&(r[i]=a8(i,t))}return r}var s8=n8,Wn={},i8=Object.keys(Wa);function o8(e){let t=function(...r){let a=r[0];return a==null?a:(a.length>1&&(r=a),e(r))};return"conversion"in e&&(t.conversion=e.conversion),t}function H8(e){let t=function(...r){let a=r[0];if(a==null)return a;a.length>1&&(r=a);let n=e(r);if(typeof n=="object")for(let{length:s}=n,i=0;i<s;i++)n[i]=Math.round(n[i]);return n};return"conversion"in e&&(t.conversion=e.conversion),t}for(let e of i8){Wn[e]={},Object.defineProperty(Wn[e],"channels",{value:Wa[e].channels}),Object.defineProperty(Wn[e],"labels",{value:Wa[e].labels});let t=s8(e),r=Object.keys(t);for(let a of r){let n=t[a];Wn[e][a]=H8(n),Wn[e][a].raw=o8(n)}}var Yt=Wn,Um=["keyword","gray","hex"],hu={};for(let e of Object.keys(Yt))hu[[...Yt[e].labels].sort().join("")]=e;var fu={};function Et(e,t){if(!(this instanceof Et))return new Et(e,t);if(t&&t in Um&&(t=null),t&&!(t in Yt))throw new Error("Unknown model: "+t);let r,a;if(e==null)this.model="rgb",this.color=[0,0,0],this.valpha=1;else if(e instanceof Et)this.model=e.model,this.color=[...e.color],this.valpha=e.valpha;else if(typeof e=="string"){let n=Un.get(e);if(n===null)throw new Error("Unable to parse color from string: "+e);this.model=n.model,a=Yt[this.model].channels,this.color=n.value.slice(0,a),this.valpha=typeof n.value[a]=="number"?n.value[a]:1}else if(e.length>0){this.model=t||"rgb",a=Yt[this.model].channels;let n=Array.prototype.slice.call(e,0,a);this.color=Eu(n,a),this.valpha=typeof e[a]=="number"?e[a]:1}else if(typeof e=="number")this.model="rgb",this.color=[e>>16&255,e>>8&255,e&255],this.valpha=1;else{this.valpha=1;let n=Object.keys(e);"alpha"in e&&(n.splice(n.indexOf("alpha"),1),this.valpha=typeof e.alpha=="number"?e.alpha:0);let s=n.sort().join("");if(!(s in hu))throw new Error("Unable to parse color from object: "+JSON.stringify(e));this.model=hu[s];let{labels:i}=Yt[this.model],o=[];for(r=0;r<i.length;r++)o.push(e[i[r]]);this.color=Eu(o)}if(fu[this.model])for(a=Yt[this.model].channels,r=0;r<a;r++){let n=fu[this.model][r];n&&(this.color[r]=n(this.color[r]))}this.valpha=Math.max(0,Math.min(1,this.valpha)),Object.freeze&&Object.freeze(this)}Et.prototype={toString(){return this.string()},toJSON(){return this[this.model]()},string(e){let t=this.model in Un.to?this:this.rgb();t=t.round(typeof e=="number"?e:1);let r=t.valpha===1?t.color:[...t.color,this.valpha];return Un.to[t.model](...r)},percentString(e){let t=this.rgb().round(typeof e=="number"?e:1),r=t.valpha===1?t.color:[...t.color,this.valpha];return Un.to.rgb.percent(...r)},array(){return this.valpha===1?[...this.color]:[...this.color,this.valpha]},object(){let e={},{channels:t}=Yt[this.model],{labels:r}=Yt[this.model];for(let a=0;a<t;a++)e[r[a]]=this.color[a];return this.valpha!==1&&(e.alpha=this.valpha),e},unitArray(){let e=this.rgb().color;return e[0]/=255,e[1]/=255,e[2]/=255,this.valpha!==1&&e.push(this.valpha),e},unitObject(){let e=this.rgb().object();return e.r/=255,e.g/=255,e.b/=255,this.valpha!==1&&(e.alpha=this.valpha),e},round(e){return e=Math.max(e||0,0),new Et([...this.color.map(c8(e)),this.valpha],this.model)},alpha(e){return e!==void 0?new Et([...this.color,Math.max(0,Math.min(1,e))],this.model):this.valpha},red:Ye("rgb",0,ct(255)),green:Ye("rgb",1,ct(255)),blue:Ye("rgb",2,ct(255)),hue:Ye(["hsl","hsv","hsl","hwb","hcg"],0,e=>(e%360+360)%360),saturationl:Ye("hsl",1,ct(100)),lightness:Ye("hsl",2,ct(100)),saturationv:Ye("hsv",1,ct(100)),value:Ye("hsv",2,ct(100)),chroma:Ye("hcg",1,ct(100)),gray:Ye("hcg",2,ct(100)),white:Ye("hwb",1,ct(100)),wblack:Ye("hwb",2,ct(100)),cyan:Ye("cmyk",0,ct(100)),magenta:Ye("cmyk",1,ct(100)),yellow:Ye("cmyk",2,ct(100)),black:Ye("cmyk",3,ct(100)),x:Ye("xyz",0,ct(95.047)),y:Ye("xyz",1,ct(100)),z:Ye("xyz",2,ct(108.833)),l:Ye("lab",0,ct(100)),a:Ye("lab",1),b:Ye("lab",2),keyword(e){return e!==void 0?new Et(e):Yt[this.model].keyword(this.color)},hex(e){return e!==void 0?new Et(e):Un.to.hex(...this.rgb().round().color)},hexa(e){if(e!==void 0)return new Et(e);let t=this.rgb().round().color,r=Math.round(this.valpha*255).toString(16).toUpperCase();return r.length===1&&(r="0"+r),Un.to.hex(...t)+r},rgbNumber(){let e=this.rgb().color;return(e[0]&255)<<16|(e[1]&255)<<8|e[2]&255},luminosity(){let e=this.rgb().color,t=[];for(let[r,a]of e.entries()){let n=a/255;t[r]=n<=.04045?n/12.92:((n+.055)/1.055)**2.4}return .2126*t[0]+.7152*t[1]+.0722*t[2]},contrast(e){let t=this.luminosity(),r=e.luminosity();return t>r?(t+.05)/(r+.05):(r+.05)/(t+.05)},level(e){let t=this.contrast(e);return t>=7?"AAA":t>=4.5?"AA":""},isDark(){let e=this.rgb().color;return(e[0]*2126+e[1]*7152+e[2]*722)/1e4<128},isLight(){return!this.isDark()},negate(){let e=this.rgb();for(let t=0;t<3;t++)e.color[t]=255-e.color[t];return e},lighten(e){let t=this.hsl();return t.color[2]+=t.color[2]*e,t},darken(e){let t=this.hsl();return t.color[2]-=t.color[2]*e,t},saturate(e){let t=this.hsl();return t.color[1]+=t.color[1]*e,t},desaturate(e){let t=this.hsl();return t.color[1]-=t.color[1]*e,t},whiten(e){let t=this.hwb();return t.color[1]+=t.color[1]*e,t},blacken(e){let t=this.hwb();return t.color[2]+=t.color[2]*e,t},grayscale(){let e=this.rgb().color,t=e[0]*.3+e[1]*.59+e[2]*.11;return Et.rgb(t,t,t)},fade(e){return this.alpha(this.valpha-this.valpha*e)},opaquer(e){return this.alpha(this.valpha+this.valpha*e)},rotate(e){let t=this.hsl(),r=t.color[0];return r=(r+e)%360,r=r<0?360+r:r,t.color[0]=r,t},mix(e,t){if(!e||!e.rgb)throw new Error('Argument to "mix" was not a Color instance, but rather an instance of '+typeof e);let r=e.rgb(),a=this.rgb(),n=t===void 0?.5:t,s=2*n-1,i=r.alpha()-a.alpha(),o=((s*i===-1?s:(s+i)/(1+s*i))+1)/2,H=1-o;return Et.rgb(o*r.red()+H*a.red(),o*r.green()+H*a.green(),o*r.blue()+H*a.blue(),r.alpha()*n+a.alpha()*(1-n))}};for(let e of Object.keys(Yt)){if(Um.includes(e))continue;let{channels:t}=Yt[e];Et.prototype[e]=function(...r){return this.model===e?new Et(this):r.length>0?new Et(r,e):new Et([...l8(Yt[this.model][e].raw(this.color)),this.valpha],e)},Et[e]=function(...r){let a=r[0];return typeof a=="number"&&(a=Eu(r,t)),new Et(a,e)}}function _8(e,t){return Number(e.toFixed(t))}function c8(e){return function(t){return _8(t,e)}}function Ye(e,t,r){e=Array.isArray(e)?e:[e];for(let a of e)(fu[a]||=[])[t]=r;return e=e[0],function(a){let n;return a!==void 0?(r&&(a=r(a)),n=this[e](),n.color[t]=a,n):(n=this[e]().color[t],r&&(n=r(n)),n)}}function ct(e){return function(t){return Math.max(0,Math.min(e,t))}}function l8(e){return Array.isArray(e)?e:[e]}function Eu(e,t){for(let r=0;r<t;r++)typeof e[r]!="number"&&(e[r]=0);return e}var u8=Et});var jm=ae((LK,Vm)=>{"use strict";Vm.exports=Km().default});var Jm=ae((AK,zm)=>{"use strict";var d8=jm(),sa=Nr(),qm={multiband:"multiband","b-w":"b-w",bw:"b-w",cmyk:"cmyk",srgb:"srgb"};function p8(e){return this._setBackgroundColourOption("tint",e),this}function h8(e){return this.options.greyscale=sa.bool(e)?e:!0,this}function f8(e){return this.greyscale(e)}function E8(e){if(!sa.string(e))throw sa.invalidParameterError("colourspace","string",e);return this.options.colourspacePipeline=e,this}function $8(e){return this.pipelineColourspace(e)}function m8(e){if(!sa.string(e))throw sa.invalidParameterError("colourspace","string",e);return this.options.colourspace=e,this}function I8(e){return this.toColourspace(e)}function Xm(e){if(sa.object(e)||sa.string(e)&&e.length>=3&&e.length<=200){let t=d8(e);return[t.red(),t.green(),t.blue(),Math.round(t.alpha()*255)]}else throw sa.invalidParameterError("background","object or string",e)}function S8(e,t){sa.defined(t)&&(this.options[e]=Xm(t))}zm.exports=e=>{Object.assign(e.prototype,{tint:p8,greyscale:h8,grayscale:f8,pipelineColourspace:E8,pipelineColorspace:$8,toColourspace:m8,toColorspace:I8,_getBackgroundColourOption:Xm,_setBackgroundColourOption:S8}),e.colourspace=qm,e.colorspace=qm}});var Ym=ae((gK,Qm)=>{"use strict";var Or=Nr(),L8={and:"and",or:"or",eor:"eor"};function A8(){return this.options.removeAlpha=!0,this}function g8(e){if(Or.defined(e))if(Or.number(e)&&Or.inRange(e,0,1))this.options.ensureAlpha=e;else throw Or.invalidParameterError("alpha","number between 0 and 1",e);else this.options.ensureAlpha=1;return this}function b8(e){let t={red:0,green:1,blue:2,alpha:3};if(Object.keys(t).includes(e)&&(e=t[e]),Or.integer(e)&&Or.inRange(e,0,4))this.options.extractChannel=e;else throw Or.invalidParameterError("channel","integer or one of: red, green, blue, alpha",e);return this}function T8(e,t){return Array.isArray(e)?e.forEach(function(r){this.options.joinChannelIn.push(this._createInputDescriptor(r,t))},this):this.options.joinChannelIn.push(this._createInputDescriptor(e,t)),this}function x8(e){if(Or.string(e)&&Or.inArray(e,["and","or","eor"]))this.options.bandBoolOp=e;else throw Or.invalidParameterError("boolOp","one of: and, or, eor",e);return this}Qm.exports=e=>{Object.assign(e.prototype,{removeAlpha:A8,ensureAlpha:g8,extractChannel:b8,joinChannel:T8,bandbool:x8}),e.bool=L8}});var nI=ae((bK,aI)=>{"use strict";var mu=require("path"),b=Nr(),jn=Ks(),eI=new Map([["heic","heif"],["heif","heif"],["avif","avif"],["jpeg","jpeg"],["jpg","jpeg"],["jpe","jpeg"],["tile","tile"],["dz","tile"],["png","png"],["raw","raw"],["tiff","tiff"],["tif","tiff"],["webp","webp"],["gif","gif"],["jp2","jp2"],["jpx","jp2"],["j2k","jp2"],["j2c","jp2"],["jxl","jxl"]]),v8=/\.(jp[2x]|j2[kc])$/i,tI=()=>new Error("JP2 output requires libvips with support for OpenJPEG"),rI=e=>1<<31-Math.clz32(Math.ceil(Math.log2(e)));function y8(e,t){let r;if(b.string(e)?b.string(this.options.input.file)&&mu.resolve(this.options.input.file)===mu.resolve(e)?r=new Error("Cannot use same file for input and output"):v8.test(mu.extname(e))&&!this.constructor.format.jp2k.output.file&&(r=tI()):r=new Error("Missing output file path"),r)if(b.fn(t))t(r);else return Promise.reject(r);else{this.options.fileOut=e;let a=Error();return this._pipeline(t,a)}return this}function D8(e,t){b.object(e)?this._setBooleanOption("resolveWithObject",e.resolveWithObject):this.options.resolveWithObject&&(this.options.resolveWithObject=!1),this.options.fileOut="";let r=Error();return this._pipeline(b.fn(e)?e:t,r)}function C8(){return this.options.keepMetadata|=1,this}function w8(e){if(b.object(e))for(let[t,r]of Object.entries(e))if(b.object(r))for(let[a,n]of Object.entries(r))if(b.string(n))this.options.withExif[`exif-${t.toLowerCase()}-${a}`]=n;else throw b.invalidParameterError(`${t}.${a}`,"string",n);else throw b.invalidParameterError(t,"object",r);else throw b.invalidParameterError("exif","object",e);return this.options.withExifMerge=!1,this.keepExif()}function N8(e){return this.withExif(e),this.options.withExifMerge=!0,this}function B8(){return this.options.keepMetadata|=8,this}function M8(e,t){if(b.string(e))this.options.withIccProfile=e;else throw b.invalidParameterError("icc","string",e);if(this.keepIccProfile(),b.object(t)&&b.defined(t.attach))if(b.bool(t.attach))t.attach||(this.options.keepMetadata&=-9);else throw b.invalidParameterError("attach","boolean",t.attach);return this}function P8(){return this.options.keepMetadata|=2,this}function k8(e){if(b.string(e)&&e.length>0)this.options.withXmp=e,this.options.keepMetadata|=2;else throw b.invalidParameterError("xmp","non-empty string",e);return this}function R8(){return this.options.keepMetadata=31,this}function O8(e){if(this.keepMetadata(),this.withIccProfile("srgb"),b.object(e)){if(b.defined(e.orientation))if(b.integer(e.orientation)&&b.inRange(e.orientation,1,8))this.options.withMetadataOrientation=e.orientation;else throw b.invalidParameterError("orientation","integer between 1 and 8",e.orientation);if(b.defined(e.density))if(b.number(e.density)&&e.density>0)this.options.withMetadataDensity=e.density;else throw b.invalidParameterError("density","positive number",e.density);b.defined(e.icc)&&this.withIccProfile(e.icc),b.defined(e.exif)&&this.withExifMerge(e.exif)}return this}function G8(e,t){let r=eI.get((b.object(e)&&b.string(e.id)?e.id:e).toLowerCase());if(!r)throw b.invalidParameterError("format",`one of: ${[...eI.keys()].join(", ")}`,e);return this[r](t)}function F8(e){if(b.object(e)){if(b.defined(e.quality))if(b.integer(e.quality)&&b.inRange(e.quality,1,100))this.options.jpegQuality=e.quality;else throw b.invalidParameterError("quality","integer between 1 and 100",e.quality);if(b.defined(e.progressive)&&this._setBooleanOption("jpegProgressive",e.progressive),b.defined(e.chromaSubsampling))if(b.string(e.chromaSubsampling)&&b.inArray(e.chromaSubsampling,["4:2:0","4:4:4"]))this.options.jpegChromaSubsampling=e.chromaSubsampling;else throw b.invalidParameterError("chromaSubsampling","one of: 4:2:0, 4:4:4",e.chromaSubsampling);let t=b.bool(e.optimizeCoding)?e.optimizeCoding:e.optimiseCoding;if(b.defined(t)&&this._setBooleanOption("jpegOptimiseCoding",t),b.defined(e.mozjpeg))if(b.bool(e.mozjpeg))e.mozjpeg&&(this.options.jpegTrellisQuantisation=!0,this.options.jpegOvershootDeringing=!0,this.options.jpegOptimiseScans=!0,this.options.jpegProgressive=!0,this.options.jpegQuantisationTable=3);else throw b.invalidParameterError("mozjpeg","boolean",e.mozjpeg);let r=b.bool(e.trellisQuantization)?e.trellisQuantization:e.trellisQuantisation;b.defined(r)&&this._setBooleanOption("jpegTrellisQuantisation",r),b.defined(e.overshootDeringing)&&this._setBooleanOption("jpegOvershootDeringing",e.overshootDeringing);let a=b.bool(e.optimizeScans)?e.optimizeScans:e.optimiseScans;b.defined(a)&&(this._setBooleanOption("jpegOptimiseScans",a),a&&(this.options.jpegProgressive=!0));let n=b.number(e.quantizationTable)?e.quantizationTable:e.quantisationTable;if(b.defined(n))if(b.integer(n)&&b.inRange(n,0,8))this.options.jpegQuantisationTable=n;else throw b.invalidParameterError("quantisationTable","integer between 0 and 8",n)}return this._updateFormatOut("jpeg",e)}function Z8(e){if(b.object(e)){if(b.defined(e.progressive)&&this._setBooleanOption("pngProgressive",e.progressive),b.defined(e.compressionLevel))if(b.integer(e.compressionLevel)&&b.inRange(e.compressionLevel,0,9))this.options.pngCompressionLevel=e.compressionLevel;else throw b.invalidParameterError("compressionLevel","integer between 0 and 9",e.compressionLevel);b.defined(e.adaptiveFiltering)&&this._setBooleanOption("pngAdaptiveFiltering",e.adaptiveFiltering);let t=e.colours||e.colors;if(b.defined(t))if(b.integer(t)&&b.inRange(t,2,256))this.options.pngBitdepth=rI(t);else throw b.invalidParameterError("colours","integer between 2 and 256",t);if(b.defined(e.palette)?this._setBooleanOption("pngPalette",e.palette):[e.quality,e.effort,e.colours,e.colors,e.dither].some(b.defined)&&this._setBooleanOption("pngPalette",!0),this.options.pngPalette){if(b.defined(e.quality))if(b.integer(e.quality)&&b.inRange(e.quality,0,100))this.options.pngQuality=e.quality;else throw b.invalidParameterError("quality","integer between 0 and 100",e.quality);if(b.defined(e.effort))if(b.integer(e.effort)&&b.inRange(e.effort,1,10))this.options.pngEffort=e.effort;else throw b.invalidParameterError("effort","integer between 1 and 10",e.effort);if(b.defined(e.dither))if(b.number(e.dither)&&b.inRange(e.dither,0,1))this.options.pngDither=e.dither;else throw b.invalidParameterError("dither","number between 0.0 and 1.0",e.dither)}}return this._updateFormatOut("png",e)}function U8(e){if(b.object(e)){if(b.defined(e.quality))if(b.integer(e.quality)&&b.inRange(e.quality,1,100))this.options.webpQuality=e.quality;else throw b.invalidParameterError("quality","integer between 1 and 100",e.quality);if(b.defined(e.alphaQuality))if(b.integer(e.alphaQuality)&&b.inRange(e.alphaQuality,0,100))this.options.webpAlphaQuality=e.alphaQuality;else throw b.invalidParameterError("alphaQuality","integer between 0 and 100",e.alphaQuality);if(b.defined(e.lossless)&&this._setBooleanOption("webpLossless",e.lossless),b.defined(e.nearLossless)&&this._setBooleanOption("webpNearLossless",e.nearLossless),b.defined(e.smartSubsample)&&this._setBooleanOption("webpSmartSubsample",e.smartSubsample),b.defined(e.smartDeblock)&&this._setBooleanOption("webpSmartDeblock",e.smartDeblock),b.defined(e.preset))if(b.string(e.preset)&&b.inArray(e.preset,["default","photo","picture","drawing","icon","text"]))this.options.webpPreset=e.preset;else throw b.invalidParameterError("preset","one of: default, photo, picture, drawing, icon, text",e.preset);if(b.defined(e.effort))if(b.integer(e.effort)&&b.inRange(e.effort,0,6))this.options.webpEffort=e.effort;else throw b.invalidParameterError("effort","integer between 0 and 6",e.effort);b.defined(e.minSize)&&this._setBooleanOption("webpMinSize",e.minSize),b.defined(e.mixed)&&this._setBooleanOption("webpMixed",e.mixed)}return Iu(e,this.options),this._updateFormatOut("webp",e)}function W8(e){if(b.object(e)){b.defined(e.reuse)&&this._setBooleanOption("gifReuse",e.reuse),b.defined(e.progressive)&&this._setBooleanOption("gifProgressive",e.progressive);let t=e.colours||e.colors;if(b.defined(t))if(b.integer(t)&&b.inRange(t,2,256))this.options.gifBitdepth=rI(t);else throw b.invalidParameterError("colours","integer between 2 and 256",t);if(b.defined(e.effort))if(b.number(e.effort)&&b.inRange(e.effort,1,10))this.options.gifEffort=e.effort;else throw b.invalidParameterError("effort","integer between 1 and 10",e.effort);if(b.defined(e.dither))if(b.number(e.dither)&&b.inRange(e.dither,0,1))this.options.gifDither=e.dither;else throw b.invalidParameterError("dither","number between 0.0 and 1.0",e.dither);if(b.defined(e.interFrameMaxError))if(b.number(e.interFrameMaxError)&&b.inRange(e.interFrameMaxError,0,32))this.options.gifInterFrameMaxError=e.interFrameMaxError;else throw b.invalidParameterError("interFrameMaxError","number between 0.0 and 32.0",e.interFrameMaxError);if(b.defined(e.interPaletteMaxError))if(b.number(e.interPaletteMaxError)&&b.inRange(e.interPaletteMaxError,0,256))this.options.gifInterPaletteMaxError=e.interPaletteMaxError;else throw b.invalidParameterError("interPaletteMaxError","number between 0.0 and 256.0",e.interPaletteMaxError);if(b.defined(e.keepDuplicateFrames))if(b.bool(e.keepDuplicateFrames))this._setBooleanOption("gifKeepDuplicateFrames",e.keepDuplicateFrames);else throw b.invalidParameterError("keepDuplicateFrames","boolean",e.keepDuplicateFrames)}return Iu(e,this.options),this._updateFormatOut("gif",e)}function K8(e){if(!this.constructor.format.jp2k.output.buffer)throw tI();if(b.object(e)){if(b.defined(e.quality))if(b.integer(e.quality)&&b.inRange(e.quality,1,100))this.options.jp2Quality=e.quality;else throw b.invalidParameterError("quality","integer between 1 and 100",e.quality);if(b.defined(e.lossless))if(b.bool(e.lossless))this.options.jp2Lossless=e.lossless;else throw b.invalidParameterError("lossless","boolean",e.lossless);if(b.defined(e.tileWidth))if(b.integer(e.tileWidth)&&b.inRange(e.tileWidth,1,32768))this.options.jp2TileWidth=e.tileWidth;else throw b.invalidParameterError("tileWidth","integer between 1 and 32768",e.tileWidth);if(b.defined(e.tileHeight))if(b.integer(e.tileHeight)&&b.inRange(e.tileHeight,1,32768))this.options.jp2TileHeight=e.tileHeight;else throw b.invalidParameterError("tileHeight","integer between 1 and 32768",e.tileHeight);if(b.defined(e.chromaSubsampling))if(b.string(e.chromaSubsampling)&&b.inArray(e.chromaSubsampling,["4:2:0","4:4:4"]))this.options.jp2ChromaSubsampling=e.chromaSubsampling;else throw b.invalidParameterError("chromaSubsampling","one of: 4:2:0, 4:4:4",e.chromaSubsampling)}return this._updateFormatOut("jp2",e)}function Iu(e,t){if(b.object(e)&&b.defined(e.loop))if(b.integer(e.loop)&&b.inRange(e.loop,0,65535))t.loop=e.loop;else throw b.invalidParameterError("loop","integer between 0 and 65535",e.loop);if(b.object(e)&&b.defined(e.delay))if(b.integer(e.delay)&&b.inRange(e.delay,0,65535))t.delay=[e.delay];else if(Array.isArray(e.delay)&&e.delay.every(b.integer)&&e.delay.every(r=>b.inRange(r,0,65535)))t.delay=e.delay;else throw b.invalidParameterError("delay","integer or an array of integers between 0 and 65535",e.delay)}function V8(e){if(b.object(e)){if(b.defined(e.quality))if(b.integer(e.quality)&&b.inRange(e.quality,1,100))this.options.tiffQuality=e.quality;else throw b.invalidParameterError("quality","integer between 1 and 100",e.quality);if(b.defined(e.bitdepth))if(b.integer(e.bitdepth)&&b.inArray(e.bitdepth,[1,2,4,8]))this.options.tiffBitdepth=e.bitdepth;else throw b.invalidParameterError("bitdepth","1, 2, 4 or 8",e.bitdepth);if(b.defined(e.tile)&&this._setBooleanOption("tiffTile",e.tile),b.defined(e.tileWidth))if(b.integer(e.tileWidth)&&e.tileWidth>0)this.options.tiffTileWidth=e.tileWidth;else throw b.invalidParameterError("tileWidth","integer greater than zero",e.tileWidth);if(b.defined(e.tileHeight))if(b.integer(e.tileHeight)&&e.tileHeight>0)this.options.tiffTileHeight=e.tileHeight;else throw b.invalidParameterError("tileHeight","integer greater than zero",e.tileHeight);if(b.defined(e.miniswhite)&&this._setBooleanOption("tiffMiniswhite",e.miniswhite),b.defined(e.pyramid)&&this._setBooleanOption("tiffPyramid",e.pyramid),b.defined(e.xres))if(b.number(e.xres)&&e.xres>0)this.options.tiffXres=e.xres;else throw b.invalidParameterError("xres","number greater than zero",e.xres);if(b.defined(e.yres))if(b.number(e.yres)&&e.yres>0)this.options.tiffYres=e.yres;else throw b.invalidParameterError("yres","number greater than zero",e.yres);if(b.defined(e.compression))if(b.string(e.compression)&&b.inArray(e.compression,["none","jpeg","deflate","packbits","ccittfax4","lzw","webp","zstd","jp2k"]))this.options.tiffCompression=e.compression;else throw b.invalidParameterError("compression","one of: none, jpeg, deflate, packbits, ccittfax4, lzw, webp, zstd, jp2k",e.compression);if(b.defined(e.bigtiff)&&this._setBooleanOption("tiffBigtiff",e.bigtiff),b.defined(e.predictor))if(b.string(e.predictor)&&b.inArray(e.predictor,["none","horizontal","float"]))this.options.tiffPredictor=e.predictor;else throw b.invalidParameterError("predictor","one of: none, horizontal, float",e.predictor);if(b.defined(e.resolutionUnit))if(b.string(e.resolutionUnit)&&b.inArray(e.resolutionUnit,["inch","cm"]))this.options.tiffResolutionUnit=e.resolutionUnit;else throw b.invalidParameterError("resolutionUnit","one of: inch, cm",e.resolutionUnit)}return this._updateFormatOut("tiff",e)}function j8(e){return this.heif({...e,compression:"av1"})}function q8(e){if(b.object(e)){if(b.string(e.compression)&&b.inArray(e.compression,["av1","hevc"]))this.options.heifCompression=e.compression;else throw b.invalidParameterError("compression","one of: av1, hevc",e.compression);if(b.defined(e.quality))if(b.integer(e.quality)&&b.inRange(e.quality,1,100))this.options.heifQuality=e.quality;else throw b.invalidParameterError("quality","integer between 1 and 100",e.quality);if(b.defined(e.lossless))if(b.bool(e.lossless))this.options.heifLossless=e.lossless;else throw b.invalidParameterError("lossless","boolean",e.lossless);if(b.defined(e.effort))if(b.integer(e.effort)&&b.inRange(e.effort,0,9))this.options.heifEffort=e.effort;else throw b.invalidParameterError("effort","integer between 0 and 9",e.effort);if(b.defined(e.chromaSubsampling))if(b.string(e.chromaSubsampling)&&b.inArray(e.chromaSubsampling,["4:2:0","4:4:4"]))this.options.heifChromaSubsampling=e.chromaSubsampling;else throw b.invalidParameterError("chromaSubsampling","one of: 4:2:0, 4:4:4",e.chromaSubsampling);if(b.defined(e.bitdepth))if(b.integer(e.bitdepth)&&b.inArray(e.bitdepth,[8,10,12])){if(e.bitdepth!==8&&this.constructor.versions.heif)throw b.invalidParameterError("bitdepth when using prebuilt binaries",8,e.bitdepth);this.options.heifBitdepth=e.bitdepth}else throw b.invalidParameterError("bitdepth","8, 10 or 12",e.bitdepth)}else throw b.invalidParameterError("options","Object",e);return this._updateFormatOut("heif",e)}function X8(e){if(b.object(e)){if(b.defined(e.quality))if(b.integer(e.quality)&&b.inRange(e.quality,1,100))this.options.jxlDistance=e.quality>=30?.1+(100-e.quality)*.09:53/3e3*e.quality*e.quality-23/20*e.quality+25;else throw b.invalidParameterError("quality","integer between 1 and 100",e.quality);else if(b.defined(e.distance))if(b.number(e.distance)&&b.inRange(e.distance,0,15))this.options.jxlDistance=e.distance;else throw b.invalidParameterError("distance","number between 0.0 and 15.0",e.distance);if(b.defined(e.decodingTier))if(b.integer(e.decodingTier)&&b.inRange(e.decodingTier,0,4))this.options.jxlDecodingTier=e.decodingTier;else throw b.invalidParameterError("decodingTier","integer between 0 and 4",e.decodingTier);if(b.defined(e.lossless))if(b.bool(e.lossless))this.options.jxlLossless=e.lossless;else throw b.invalidParameterError("lossless","boolean",e.lossless);if(b.defined(e.effort))if(b.integer(e.effort)&&b.inRange(e.effort,1,9))this.options.jxlEffort=e.effort;else throw b.invalidParameterError("effort","integer between 1 and 9",e.effort)}return Iu(e,this.options),this._updateFormatOut("jxl",e)}function z8(e){if(b.object(e)&&b.defined(e.depth))if(b.string(e.depth)&&b.inArray(e.depth,["char","uchar","short","ushort","int","uint","float","complex","double","dpcomplex"]))this.options.rawDepth=e.depth;else throw b.invalidParameterError("depth","one of: char, uchar, short, ushort, int, uint, float, complex, double, dpcomplex",e.depth);return this._updateFormatOut("raw")}function J8(e){if(b.object(e)){if(b.defined(e.size))if(b.integer(e.size)&&b.inRange(e.size,1,8192))this.options.tileSize=e.size;else throw b.invalidParameterError("size","integer between 1 and 8192",e.size);if(b.defined(e.overlap))if(b.integer(e.overlap)&&b.inRange(e.overlap,0,8192)){if(e.overlap>this.options.tileSize)throw b.invalidParameterError("overlap",`<= size (${this.options.tileSize})`,e.overlap);this.options.tileOverlap=e.overlap}else throw b.invalidParameterError("overlap","integer between 0 and 8192",e.overlap);if(b.defined(e.container))if(b.string(e.container)&&b.inArray(e.container,["fs","zip"]))this.options.tileContainer=e.container;else throw b.invalidParameterError("container","one of: fs, zip",e.container);if(b.defined(e.layout))if(b.string(e.layout)&&b.inArray(e.layout,["dz","google","iiif","iiif3","zoomify"]))this.options.tileLayout=e.layout;else throw b.invalidParameterError("layout","one of: dz, google, iiif, iiif3, zoomify",e.layout);if(b.defined(e.angle))if(b.integer(e.angle)&&!(e.angle%90))this.options.tileAngle=e.angle;else throw b.invalidParameterError("angle","positive/negative multiple of 90",e.angle);if(this._setBackgroundColourOption("tileBackground",e.background),b.defined(e.depth))if(b.string(e.depth)&&b.inArray(e.depth,["onepixel","onetile","one"]))this.options.tileDepth=e.depth;else throw b.invalidParameterError("depth","one of: onepixel, onetile, one",e.depth);if(b.defined(e.skipBlanks))if(b.integer(e.skipBlanks)&&b.inRange(e.skipBlanks,-1,65535))this.options.tileSkipBlanks=e.skipBlanks;else throw b.invalidParameterError("skipBlanks","integer between -1 and 255/65535",e.skipBlanks);else b.defined(e.layout)&&e.layout==="google"&&(this.options.tileSkipBlanks=5);let t=b.bool(e.center)?e.center:e.centre;if(b.defined(t)&&this._setBooleanOption("tileCentre",t),b.defined(e.id))if(b.string(e.id))this.options.tileId=e.id;else throw b.invalidParameterError("id","string",e.id);if(b.defined(e.basename))if(b.string(e.basename))this.options.tileBasename=e.basename;else throw b.invalidParameterError("basename","string",e.basename)}if(b.inArray(this.options.formatOut,["jpeg","png","webp"]))this.options.tileFormat=this.options.formatOut;else if(this.options.formatOut!=="input")throw b.invalidParameterError("format","one of: jpeg, png, webp",this.options.formatOut);return this._updateFormatOut("dz")}function Q8(e){if(!b.plainObject(e))throw b.invalidParameterError("options","object",e);if(b.integer(e.seconds)&&b.inRange(e.seconds,0,3600))this.options.timeoutSeconds=e.seconds;else throw b.invalidParameterError("seconds","integer between 0 and 3600",e.seconds);return this}function Y8(e,t){return b.object(t)&&t.force===!1||(this.options.formatOut=e),this}function eO(e,t){if(b.bool(t))this.options[e]=t;else throw b.invalidParameterError(e,"boolean",t)}function tO(){if(!this.options.streamOut){this.options.streamOut=!0;let e=Error();this._pipeline(void 0,e)}}function rO(e,t){return typeof e=="function"?(this._isStreamInput()?this.on("finish",()=>{this._flattenBufferIn(),jn.pipeline(this.options,(r,a,n)=>{r?e(b.nativeError(r,t)):e(null,a,n)})}):jn.pipeline(this.options,(r,a,n)=>{r?e(b.nativeError(r,t)):e(null,a,n)}),this):this.options.streamOut?(this._isStreamInput()?(this.once("finish",()=>{this._flattenBufferIn(),jn.pipeline(this.options,(r,a,n)=>{r?this.emit("error",b.nativeError(r,t)):(this.emit("info",n),this.push(a)),this.push(null),this.on("end",()=>this.emit("close"))})}),this.streamInFinished&&this.emit("finish")):jn.pipeline(this.options,(r,a,n)=>{r?this.emit("error",b.nativeError(r,t)):(this.emit("info",n),this.push(a)),this.push(null),this.on("end",()=>this.emit("close"))}),this):this._isStreamInput()?new Promise((r,a)=>{this.once("finish",()=>{this._flattenBufferIn(),jn.pipeline(this.options,(n,s,i)=>{n?a(b.nativeError(n,t)):this.options.resolveWithObject?r({data:s,info:i}):r(s)})})}):new Promise((r,a)=>{jn.pipeline(this.options,(n,s,i)=>{n?a(b.nativeError(n,t)):this.options.resolveWithObject?r({data:s,info:i}):r(s)})})}aI.exports=e=>{Object.assign(e.prototype,{toFile:y8,toBuffer:D8,keepExif:C8,withExif:w8,withExifMerge:N8,keepIccProfile:B8,withIccProfile:M8,keepXmp:P8,withXmp:k8,keepMetadata:R8,withMetadata:O8,toFormat:G8,jpeg:F8,jp2:K8,png:Z8,webp:U8,tiff:V8,avif:j8,heif:q8,jxl:X8,gif:W8,raw:z8,tile:J8,timeout:Q8,_updateFormatOut:Y8,_setBooleanOption:eO,_read:tO,_pipeline:rO})}});var HI=ae((TK,oI)=>{"use strict";var aO=require("events"),Po=Ao(),Hr=Nr(),{runtimePlatformArch:nO}=Hu(),Ut=Ks(),sI=nO(),Su=Ut.libvipsVersion(),Ia=Ut.format();Ia.heif.output.alias=["avif","heic"];Ia.jpeg.output.alias=["jpe","jpg"];Ia.tiff.output.alias=["tif"];Ia.jp2k.output.alias=["j2c","j2k","jp2","jpx"];var sO={nearest:"nearest",bilinear:"bilinear",bicubic:"bicubic",locallyBoundedBicubic:"lbb",nohalo:"nohalo",vertexSplitQuadraticBasisSpline:"vsqbs"},qn={vips:Su.semver};if(!Su.isGlobal)if(Su.isWasm)try{qn=require("@img/sharp-wasm32/versions")}catch{}else try{qn=require(`@img/sharp-${sI}/versions`)}catch{try{qn=require(`@img/sharp-libvips-${sI}/versions`)}catch{}}qn.sharp=iu().version;qn.heif&&Ia.heif&&(Ia.heif.input.fileSuffix=[".avif"],Ia.heif.output.alias=["avif"]);function iI(e){return Hr.bool(e)?e?Ut.cache(50,20,100):Ut.cache(0,0,0):Hr.object(e)?Ut.cache(e.memory,e.files,e.items):Ut.cache()}iI(!0);function iO(e){return Ut.concurrency(Hr.integer(e)?e:null)}Po.familySync()===Po.GLIBC&&!Ut._isUsingJemalloc()?Ut.concurrency(1):Po.familySync()===Po.MUSL&&Ut.concurrency()===1024&&Ut.concurrency(require("os").availableParallelism());var oO=new aO.EventEmitter;function HO(){return Ut.counters()}function _O(e){return Ut.simd(Hr.bool(e)?e:null)}function cO(e){if(Hr.object(e))if(Array.isArray(e.operation)&&e.operation.every(Hr.string))Ut.block(e.operation,!0);else throw Hr.invalidParameterError("operation","Array<string>",e.operation);else throw Hr.invalidParameterError("options","object",e)}function lO(e){if(Hr.object(e))if(Array.isArray(e.operation)&&e.operation.every(Hr.string))Ut.block(e.operation,!1);else throw Hr.invalidParameterError("operation","Array<string>",e.operation);else throw Hr.invalidParameterError("options","object",e)}oI.exports=e=>{e.cache=iI,e.concurrency=iO,e.counters=HO,e.simd=_O,e.format=Ia,e.interpolators=sO,e.versions=qn,e.queue=oO,e.block=cO,e.unblock=lO}});var cI=ae((xK,_I)=>{"use strict";var ia=Am();Tm()(ia);wm()(ia);Bm()(ia);Om()(ia);Jm()(ia);Ym()(ia);nI()(ia);HI()(ia);_I.exports=ia});var IB={};hl(IB,{ASTFeatureExtractor:()=>hg,ASTForAudioClassification:()=>NT,ASTModel:()=>wT,ASTPreTrainedModel:()=>OH,AfmoeForCausalLM:()=>yT,AfmoeModel:()=>vT,AfmoePreTrainedModel:()=>kH,AlbertForMaskedLM:()=>bT,AlbertForQuestionAnswering:()=>gT,AlbertForSequenceClassification:()=>AT,AlbertModel:()=>LT,AlbertPreTrainedModel:()=>$s,AlbertTokenizer:()=>dA,ApertusForCausalLM:()=>xT,ApertusModel:()=>TT,ApertusPreTrainedModel:()=>PH,ArceeForCausalLM:()=>CT,ArceeModel:()=>DT,ArceePreTrainedModel:()=>RH,AudioClassificationPipeline:()=>Q2,AutoConfig:()=>ls,AutoFeatureExtractor:()=>sr,AutoImageProcessor:()=>Dt,AutoModel:()=>is,AutoModelForAudioClassification:()=>O2,AutoModelForAudioFrameClassification:()=>x7,AutoModelForAudioTextToText:()=>w7,AutoModelForCTC:()=>R2,AutoModelForCausalLM:()=>C2,AutoModelForDepthEstimation:()=>Z2,AutoModelForDocumentQuestionAnswering:()=>G2,AutoModelForImageClassification:()=>M2,AutoModelForImageFeatureExtraction:()=>U2,AutoModelForImageMatting:()=>v7,AutoModelForImageSegmentation:()=>pd,AutoModelForImageTextToText:()=>C7,AutoModelForImageToImage:()=>F2,AutoModelForMaskGeneration:()=>b7,AutoModelForMaskedLM:()=>w2,AutoModelForNormalEstimation:()=>y7,AutoModelForObjectDetection:()=>P2,AutoModelForPoseEstimation:()=>D7,AutoModelForQuestionAnswering:()=>N2,AutoModelForSemanticSegmentation:()=>hd,AutoModelForSeq2SeqLM:()=>tH,AutoModelForSequenceClassification:()=>dd,AutoModelForSpeechSeq2Seq:()=>v2,AutoModelForTextToSpectrogram:()=>y2,AutoModelForTextToWaveform:()=>D2,AutoModelForTokenClassification:()=>x2,AutoModelForUniversalSegmentation:()=>fd,AutoModelForVision2Seq:()=>B2,AutoModelForXVector:()=>T7,AutoModelForZeroShotObjectDetection:()=>k2,AutoProcessor:()=>zb,AutoTokenizer:()=>we,AutomaticSpeechRecognitionPipeline:()=>eB,BackgroundRemovalPipeline:()=>nB,BartForConditionalGeneration:()=>MT,BartForSequenceClassification:()=>PT,BartModel:()=>BT,BartPretrainedModel:()=>fi,BartTokenizer:()=>pA,BaseStreamer:()=>hB,BeitFeatureExtractor:()=>Mg,BeitForImageClassification:()=>RT,BeitModel:()=>kT,BeitPreTrainedModel:()=>GH,BertForMaskedLM:()=>GT,BertForQuestionAnswering:()=>UT,BertForSequenceClassification:()=>FT,BertForTokenClassification:()=>ZT,BertModel:()=>OT,BertPreTrainedModel:()=>ln,BertTokenizer:()=>hA,BitImageProcessor:()=>Pg,BlenderbotForConditionalGeneration:()=>KT,BlenderbotModel:()=>WT,BlenderbotPreTrainedModel:()=>FH,BlenderbotSmallForConditionalGeneration:()=>jT,BlenderbotSmallModel:()=>VT,BlenderbotSmallPreTrainedModel:()=>ZH,BlenderbotSmallTokenizer:()=>fA,BlenderbotTokenizer:()=>EA,BloomForCausalLM:()=>XT,BloomModel:()=>qT,BloomPreTrainedModel:()=>UH,BloomTokenizer:()=>$A,CHMv2ForDepthEstimation:()=>rx,CHMv2ImageProcessor:()=>Rg,CHMv2PreTrainedModel:()=>Gp,CLIPFeatureExtractor:()=>Og,CLIPImageProcessor:()=>_p,CLIPModel:()=>nx,CLIPPreTrainedModel:()=>Ca,CLIPSegForImageSegmentation:()=>_x,CLIPSegModel:()=>Hx,CLIPSegPreTrainedModel:()=>WH,CLIPTextModel:()=>sx,CLIPTextModelWithProjection:()=>Up,CLIPTokenizer:()=>IA,CLIPVisionModel:()=>ix,CLIPVisionModelWithProjection:()=>ox,CamembertForMaskedLM:()=>JT,CamembertForQuestionAnswering:()=>ex,CamembertForSequenceClassification:()=>QT,CamembertForTokenClassification:()=>YT,CamembertModel:()=>zT,CamembertPreTrainedModel:()=>un,CamembertTokenizer:()=>mA,ChatterboxFeatureExtractor:()=>fg,ChatterboxModel:()=>Rp,ChatterboxPreTrainedModel:()=>kp,ChatterboxProcessor:()=>vg,ChineseCLIPFeatureExtractor:()=>kg,ChineseCLIPModel:()=>tx,ChineseCLIPPreTrainedModel:()=>Op,ClapAudioModelWithProjection:()=>Zp,ClapFeatureExtractor:()=>Eg,ClapModel:()=>ax,ClapPreTrainedModel:()=>Ei,ClapTextModelWithProjection:()=>Fp,ClassifierFreeGuidanceLogitsProcessor:()=>_T,CodeGenForCausalLM:()=>lx,CodeGenModel:()=>cx,CodeGenPreTrainedModel:()=>KH,CodeGenTokenizer:()=>LA,CodeLlamaTokenizer:()=>SA,Cohere2ForCausalLM:()=>hx,Cohere2Model:()=>px,Cohere2PreTrainedModel:()=>jH,CohereAsrFeatureExtractor:()=>$g,CohereAsrForConditionalGeneration:()=>Ex,CohereAsrModel:()=>fx,CohereAsrPreTrainedModel:()=>qH,CohereAsrProcessor:()=>yg,CohereAsrTokenizer:()=>gA,CohereForCausalLM:()=>dx,CohereModel:()=>ux,CoherePreTrainedModel:()=>VH,CohereTokenizer:()=>AA,ConvBertForMaskedLM:()=>mx,ConvBertForQuestionAnswering:()=>Lx,ConvBertForSequenceClassification:()=>Ix,ConvBertForTokenClassification:()=>Sx,ConvBertModel:()=>$x,ConvBertPreTrainedModel:()=>dn,ConvBertTokenizer:()=>bA,ConvNextFeatureExtractor:()=>Gg,ConvNextForImageClassification:()=>gx,ConvNextImageProcessor:()=>cp,ConvNextModel:()=>Ax,ConvNextPreTrainedModel:()=>XH,ConvNextV2ForImageClassification:()=>Tx,ConvNextV2Model:()=>bx,ConvNextV2PreTrainedModel:()=>zH,DFineForObjectDetection:()=>Dx,DFineModel:()=>yx,DFinePreTrainedModel:()=>QH,DINOv3ConvNextModel:()=>rv,DINOv3ConvNextPreTrainedModel:()=>Qp,DINOv3ViTImageProcessor:()=>Ug,DINOv3ViTModel:()=>av,DINOv3ViTPreTrainedModel:()=>Yp,DPTFeatureExtractor:()=>Kg,DPTForDepthEstimation:()=>lv,DPTImageProcessor:()=>dp,DPTModel:()=>cv,DPTPreTrainedModel:()=>n_,DacDecoderModel:()=>jp,DacDecoderOutput:()=>Kp,DacEncoderModel:()=>Vp,DacEncoderOutput:()=>Wp,DacFeatureExtractor:()=>np,DacModel:()=>Cx,DacPreTrainedModel:()=>$i,DebertaForMaskedLM:()=>Nx,DebertaForQuestionAnswering:()=>Px,DebertaForSequenceClassification:()=>Bx,DebertaForTokenClassification:()=>Mx,DebertaModel:()=>wx,DebertaPreTrainedModel:()=>pn,DebertaTokenizer:()=>xA,DebertaV2ForMaskedLM:()=>Gx,DebertaV2ForQuestionAnswering:()=>Ux,DebertaV2ForSequenceClassification:()=>Fx,DebertaV2ForTokenClassification:()=>Zx,DebertaV2Model:()=>Ox,DebertaV2PreTrainedModel:()=>hn,DebertaV2Tokenizer:()=>TA,DecisionTransformerModel:()=>Wx,DecisionTransformerPreTrainedModel:()=>qp,DeepseekV3ForCausalLM:()=>Rx,DeepseekV3Model:()=>kx,DeepseekV3PreTrainedModel:()=>YH,DeiTFeatureExtractor:()=>Fg,DeiTForImageClassification:()=>Vx,DeiTImageProcessor:()=>lp,DeiTModel:()=>Kx,DeiTPreTrainedModel:()=>e_,DepthAnythingForDepthEstimation:()=>jx,DepthAnythingPreTrainedModel:()=>Xp,DepthEstimationPipeline:()=>cB,DepthProForDepthEstimation:()=>qx,DepthProPreTrainedModel:()=>zp,DetrFeatureExtractor:()=>Zg,DetrForObjectDetection:()=>zx,DetrForSegmentation:()=>Jx,DetrImageProcessor:()=>up,DetrModel:()=>Xx,DetrObjectDetectionOutput:()=>t_,DetrPreTrainedModel:()=>mi,DetrSegmentationOutput:()=>Jp,Dinov2ForImageClassification:()=>Yx,Dinov2Model:()=>Qx,Dinov2PreTrainedModel:()=>r_,Dinov2WithRegistersForImageClassification:()=>tv,Dinov2WithRegistersModel:()=>ev,Dinov2WithRegistersPreTrainedModel:()=>a_,DistilBertForMaskedLM:()=>Hv,DistilBertForQuestionAnswering:()=>ov,DistilBertForSequenceClassification:()=>sv,DistilBertForTokenClassification:()=>iv,DistilBertModel:()=>nv,DistilBertPreTrainedModel:()=>fn,DistilBertTokenizer:()=>vA,DocumentQuestionAnsweringPipeline:()=>HB,DonutFeatureExtractor:()=>Wg,DonutImageProcessor:()=>vH,DonutSwinModel:()=>_v,DonutSwinPreTrainedModel:()=>eh,DynamicCache:()=>MH,EdgeTamModel:()=>Lw,EfficientNetForImageClassification:()=>dv,EfficientNetImageProcessor:()=>Vg,EfficientNetModel:()=>uv,EfficientNetPreTrainedModel:()=>s_,ElectraForMaskedLM:()=>hv,ElectraForQuestionAnswering:()=>$v,ElectraForSequenceClassification:()=>fv,ElectraForTokenClassification:()=>Ev,ElectraModel:()=>pv,ElectraPreTrainedModel:()=>En,ElectraTokenizer:()=>yA,EncodecFeatureExtractor:()=>rp,EosTokenCriteria:()=>pT,Ernie4_5ForCausalLM:()=>Iv,Ernie4_5Model:()=>mv,Ernie4_5PretrainedModel:()=>i_,EsmForMaskedLM:()=>Lv,EsmForSequenceClassification:()=>Av,EsmForTokenClassification:()=>gv,EsmModel:()=>Sv,EsmPreTrainedModel:()=>Is,EsmTokenizer:()=>DA,EuroBertForMaskedLM:()=>Tv,EuroBertForSequenceClassification:()=>xv,EuroBertForTokenClassification:()=>vv,EuroBertModel:()=>bv,EuroBertPreTrainedModel:()=>Ss,ExaoneForCausalLM:()=>Dv,ExaoneModel:()=>yv,ExaonePreTrainedModel:()=>o_,FalconForCausalLM:()=>wv,FalconH1ForCausalLM:()=>Bv,FalconH1Model:()=>Nv,FalconH1PreTrainedModel:()=>__,FalconModel:()=>Cv,FalconPreTrainedModel:()=>H_,FalconTokenizer:()=>CA,FastViTForImageClassification:()=>Pv,FastViTModel:()=>Mv,FastViTPreTrainedModel:()=>c_,FeatureExtractionPipeline:()=>lB,FeatureExtractor:()=>vt,FillMaskPipeline:()=>j2,Florence2ForConditionalGeneration:()=>kv,Florence2PreTrainedModel:()=>th,Florence2Processor:()=>Ab,ForcedBOSTokenLogitsProcessor:()=>eT,ForcedEOSTokenLogitsProcessor:()=>tT,GLPNFeatureExtractor:()=>Xg,GLPNForDepthEstimation:()=>ey,GLPNModel:()=>Yv,GLPNPreTrainedModel:()=>$_,GPT2LMHeadModel:()=>cy,GPT2Model:()=>_y,GPT2PreTrainedModel:()=>A_,GPT2Tokenizer:()=>BA,GPTBigCodeForCausalLM:()=>ry,GPTBigCodeModel:()=>ty,GPTBigCodePreTrainedModel:()=>m_,GPTJForCausalLM:()=>uy,GPTJModel:()=>ly,GPTJPreTrainedModel:()=>g_,GPTNeoForCausalLM:()=>ny,GPTNeoModel:()=>ay,GPTNeoPreTrainedModel:()=>I_,GPTNeoXForCausalLM:()=>iy,GPTNeoXModel:()=>sy,GPTNeoXPreTrainedModel:()=>S_,GPTNeoXTokenizer:()=>NA,Gemma2ForCausalLM:()=>Fv,Gemma2Model:()=>Gv,Gemma2PreTrainedModel:()=>u_,Gemma3ForCausalLM:()=>Kv,Gemma3ForConditionalGeneration:()=>nh,Gemma3ImageProcessor:()=>jg,Gemma3Model:()=>Wv,Gemma3PreTrainedModel:()=>ah,Gemma3Processor:()=>gb,Gemma3nAudioFeatureExtractor:()=>sp,Gemma3nForCausalLM:()=>Vv,Gemma3nForConditionalGeneration:()=>Ii,Gemma3nPreTrainedModel:()=>sh,Gemma3nProcessor:()=>bb,Gemma4AudioFeatureExtractor:()=>ip,Gemma4ForCausalLM:()=>jv,Gemma4ForConditionalGeneration:()=>d_,Gemma4ImageProcessor:()=>pp,Gemma4Processor:()=>Tb,GemmaForCausalLM:()=>Ov,GemmaModel:()=>Rv,GemmaPreTrainedModel:()=>l_,GemmaTokenizer:()=>wA,Glm46VImageProcessor:()=>qg,Glm46VProcessor:()=>xb,GlmForCausalLM:()=>Xv,GlmModel:()=>qv,GlmMoeDsaForCausalLM:()=>Jv,GlmMoeDsaModel:()=>zv,GlmMoeDsaPreTrainedModel:()=>h_,GlmOcrForConditionalGeneration:()=>Qv,GlmPreTrainedModel:()=>p_,GptOssForCausalLM:()=>Hy,GptOssModel:()=>oy,GptOssPreTrainedModel:()=>L_,GraniteForCausalLM:()=>py,GraniteModel:()=>dy,GraniteMoeHybridForCausalLM:()=>fy,GraniteMoeHybridModel:()=>hy,GraniteMoeHybridPreTrainedModel:()=>T_,GranitePreTrainedModel:()=>b_,GraniteSpeechFeatureExtractor:()=>mg,GraniteSpeechForConditionalGeneration:()=>Ey,GraniteSpeechProcessor:()=>vb,GroundingDinoForObjectDetection:()=>$y,GroundingDinoImageProcessor:()=>zg,GroundingDinoPreTrainedModel:()=>ch,GroundingDinoProcessor:()=>yb,GroupViTModel:()=>my,GroupViTPreTrainedModel:()=>lh,HeliumForCausalLM:()=>Sy,HeliumModel:()=>Iy,HeliumPreTrainedModel:()=>v_,HerbertTokenizer:()=>MA,HieraForImageClassification:()=>Ay,HieraModel:()=>Ly,HieraPreTrainedModel:()=>y_,HubertForCTC:()=>Dy,HubertForSequenceClassification:()=>Cy,HubertModel:()=>yy,HubertPreTrainedModel:()=>vy,HunYuanDenseV1ForCausalLM:()=>Ny,HunYuanDenseV1Model:()=>wy,HunYuanDenseV1PreTrainedModel:()=>D_,IJepaForImageClassification:()=>My,IJepaModel:()=>By,IJepaPreTrainedModel:()=>C_,Idefics3ForConditionalGeneration:()=>uh,Idefics3ImageProcessor:()=>Hd,Idefics3Processor:()=>_d,ImageClassificationPipeline:()=>aB,ImageFeatureExtractionPipeline:()=>uB,ImageFeatureExtractor:()=>Ee,ImageProcessor:()=>Ee,ImageSegmentationPipeline:()=>rf,ImageToImagePipeline:()=>_B,ImageToTextPipeline:()=>rB,InterruptableStoppingCriteria:()=>XZ,JAISLMHeadModel:()=>ky,JAISModel:()=>Py,JAISPreTrainedModel:()=>w_,JinaCLIPImageProcessor:()=>Qg,JinaCLIPModel:()=>Ry,JinaCLIPPreTrainedModel:()=>Si,JinaCLIPProcessor:()=>Cb,JinaCLIPTextModel:()=>dh,JinaCLIPVisionModel:()=>Oy,Lfm2ForCausalLM:()=>Fy,Lfm2Model:()=>Gy,Lfm2MoeForCausalLM:()=>Wy,Lfm2MoeModel:()=>Uy,Lfm2MoePreTrainedModel:()=>B_,Lfm2PreTrainedModel:()=>N_,Lfm2VlForConditionalGeneration:()=>Ky,Lfm2VlImageProcessor:()=>Yg,Lfm2VlProcessor:()=>wb,LightOnOcrForConditionalGeneration:()=>Zy,LiteWhisperForConditionalGeneration:()=>PN,Llama4ForCausalLM:()=>qy,Llama4PreTrainedModel:()=>ph,LlamaForCausalLM:()=>jy,LlamaModel:()=>Vy,LlamaPreTrainedModel:()=>M_,LlamaTokenizer:()=>PA,LlavaForConditionalGeneration:()=>Kr,LlavaOnevisionForConditionalGeneration:()=>Kr,LlavaOnevisionImageProcessor:()=>eb,LlavaPreTrainedModel:()=>rh,LlavaProcessor:()=>Nb,LlavaQwen2ForCausalLM:()=>Uv,LogLevel:()=>ur,LogitsProcessor:()=>pr,LogitsProcessorList:()=>EH,LogitsWarper:()=>NH,LongT5ForConditionalGeneration:()=>zy,LongT5Model:()=>Xy,LongT5PreTrainedModel:()=>P_,M2M100ForConditionalGeneration:()=>Qy,M2M100Model:()=>Jy,M2M100PreTrainedModel:()=>k_,M2M100Tokenizer:()=>kA,MBart50Tokenizer:()=>OA,MBartForCausalLM:()=>iD,MBartForConditionalGeneration:()=>nD,MBartForSequenceClassification:()=>sD,MBartModel:()=>aD,MBartPreTrainedModel:()=>Ls,MBartTokenizer:()=>Yd,MPNetForMaskedLM:()=>VD,MPNetForQuestionAnswering:()=>XD,MPNetForSequenceClassification:()=>jD,MPNetForTokenClassification:()=>qD,MPNetModel:()=>KD,MPNetPreTrainedModel:()=>$n,MPNetTokenizer:()=>ZA,MT5ForConditionalGeneration:()=>YD,MT5Model:()=>QD,MT5PreTrainedModel:()=>q_,MarianMTModel:()=>eD,MarianModel:()=>Yy,MarianPreTrainedModel:()=>R_,MarianTokenizer:()=>RA,Mask2FormerImageProcessor:()=>rb,MaskFormerFeatureExtractor:()=>tb,MaskFormerForInstanceSegmentation:()=>rD,MaskFormerImageProcessor:()=>yH,MaskFormerModel:()=>tD,MaskFormerPreTrainedModel:()=>O_,MaxLengthCriteria:()=>dT,Metric3DForDepthEstimation:()=>oD,Metric3DPreTrainedModel:()=>hh,Metric3Dv2ForDepthEstimation:()=>HD,Metric3Dv2PreTrainedModel:()=>fh,MgpstrForSceneTextRecognition:()=>_D,MgpstrModelOutput:()=>Eh,MgpstrPreTrainedModel:()=>$h,MgpstrProcessor:()=>Bb,MgpstrTokenizer:()=>GA,MimiDecoderModel:()=>Lh,MimiDecoderOutput:()=>Ih,MimiEncoderModel:()=>Sh,MimiEncoderOutput:()=>mh,MimiModel:()=>cD,MimiPreTrainedModel:()=>Li,MinLengthLogitsProcessor:()=>iT,MinNewTokensLengthLogitsProcessor:()=>oT,Mistral4ForCausalLM:()=>pD,Mistral4Model:()=>dD,Mistral4PreTrainedModel:()=>F_,MistralForCausalLM:()=>uD,MistralModel:()=>lD,MistralPreTrainedModel:()=>G_,MobileBertForMaskedLM:()=>fD,MobileBertForQuestionAnswering:()=>$D,MobileBertForSequenceClassification:()=>ED,MobileBertModel:()=>hD,MobileBertPreTrainedModel:()=>As,MobileBertTokenizer:()=>FA,MobileLLMForCausalLM:()=>ID,MobileLLMModel:()=>mD,MobileLLMPreTrainedModel:()=>Z_,MobileNetV1FeatureExtractor:()=>ab,MobileNetV1ForImageClassification:()=>LD,MobileNetV1ForSemanticSegmentation:()=>AD,MobileNetV1ImageProcessor:()=>fp,MobileNetV1Model:()=>SD,MobileNetV1PreTrainedModel:()=>Ai,MobileNetV2FeatureExtractor:()=>nb,MobileNetV2ForImageClassification:()=>bD,MobileNetV2ForSemanticSegmentation:()=>TD,MobileNetV2ImageProcessor:()=>Ep,MobileNetV2Model:()=>gD,MobileNetV2PreTrainedModel:()=>gi,MobileNetV3FeatureExtractor:()=>sb,MobileNetV3ForImageClassification:()=>vD,MobileNetV3ForSemanticSegmentation:()=>yD,MobileNetV3ImageProcessor:()=>$p,MobileNetV3Model:()=>xD,MobileNetV3PreTrainedModel:()=>bi,MobileNetV4FeatureExtractor:()=>ib,MobileNetV4ForImageClassification:()=>CD,MobileNetV4ForSemanticSegmentation:()=>wD,MobileNetV4ImageProcessor:()=>mp,MobileNetV4Model:()=>DD,MobileNetV4PreTrainedModel:()=>Ti,MobileViTFeatureExtractor:()=>ob,MobileViTForImageClassification:()=>BD,MobileViTImageProcessor:()=>Ip,MobileViTModel:()=>ND,MobileViTPreTrainedModel:()=>U_,MobileViTV2ForImageClassification:()=>PD,MobileViTV2Model:()=>MD,MobileViTV2PreTrainedModel:()=>W_,ModelRegistry:()=>j7,ModernBertDecoderForCausalLM:()=>ZD,ModernBertDecoderModel:()=>FD,ModernBertDecoderPreTrainedModel:()=>K_,ModernBertForMaskedLM:()=>RD,ModernBertForSequenceClassification:()=>OD,ModernBertForTokenClassification:()=>GD,ModernBertModel:()=>kD,ModernBertPreTrainedModel:()=>gs,Moondream1ForConditionalGeneration:()=>Zv,MoonshineFeatureExtractor:()=>Ig,MoonshineForConditionalGeneration:()=>WD,MoonshineModel:()=>UD,MoonshinePreTrainedModel:()=>V_,MoonshineProcessor:()=>Mb,MptForCausalLM:()=>JD,MptModel:()=>zD,MptPreTrainedModel:()=>j_,MultiModalityCausalLM:()=>eC,MultiModalityPreTrainedModel:()=>Ah,MusicgenForCausalLM:()=>rC,MusicgenForConditionalGeneration:()=>gh,MusicgenModel:()=>tC,MusicgenPreTrainedModel:()=>X_,NanoChatForCausalLM:()=>nC,NanoChatModel:()=>aC,NanoChatPreTrainedModel:()=>z_,NemotronHForCausalLM:()=>iC,NemotronHModel:()=>sC,NemotronHPreTrainedModel:()=>J_,NeoBertForMaskedLM:()=>HC,NeoBertForQuestionAnswering:()=>lC,NeoBertForSequenceClassification:()=>_C,NeoBertForTokenClassification:()=>cC,NeoBertModel:()=>oC,NeoBertPreTrainedModel:()=>mn,NllbTokenizer:()=>UA,NoBadWordsLogitsProcessor:()=>HT,NoRepeatNGramLogitsProcessor:()=>nT,NomicBertModel:()=>uC,NomicBertPreTrainedModel:()=>bh,NougatImageProcessor:()=>Hb,NougatTokenizer:()=>WA,OPTForCausalLM:()=>TC,OPTModel:()=>bC,OPTPreTrainedModel:()=>nc,ObjectDetectionPipeline:()=>iB,Olmo2ForCausalLM:()=>fC,Olmo2Model:()=>hC,Olmo2PreTrainedModel:()=>Y_,Olmo3ForCausalLM:()=>$C,Olmo3Model:()=>EC,Olmo3PreTrainedModel:()=>ec,OlmoForCausalLM:()=>pC,OlmoHybridForCausalLM:()=>IC,OlmoHybridModel:()=>mC,OlmoHybridPreTrainedModel:()=>tc,OlmoModel:()=>dC,OlmoPreTrainedModel:()=>Q_,OpenAIPrivacyFilterForTokenClassification:()=>LC,OpenAIPrivacyFilterModel:()=>SC,OpenAIPrivacyFilterPreTrainedModel:()=>rc,OpenELMForCausalLM:()=>gC,OpenELMModel:()=>AC,OpenELMPreTrainedModel:()=>ac,OwlViTFeatureExtractor:()=>_b,OwlViTForObjectDetection:()=>DC,OwlViTImageProcessor:()=>DH,OwlViTModel:()=>yC,OwlViTPreTrainedModel:()=>ic,OwlViTProcessor:()=>Pb,Owlv2ForObjectDetection:()=>vC,Owlv2ImageProcessor:()=>cb,Owlv2Model:()=>xC,Owlv2PreTrainedModel:()=>sc,PaliGemmaForConditionalGeneration:()=>CC,PaliGemmaProcessor:()=>kb,ParakeetFeatureExtractor:()=>ap,ParakeetForCTC:()=>wC,ParakeetPreTrainedModel:()=>Th,PatchTSMixerForPrediction:()=>BC,PatchTSMixerModel:()=>NC,PatchTSMixerPreTrainedModel:()=>oc,PatchTSTForPrediction:()=>PC,PatchTSTModel:()=>MC,PatchTSTPreTrainedModel:()=>Hc,Phi3ForCausalLM:()=>GC,Phi3Model:()=>OC,Phi3PreTrainedModel:()=>cc,Phi3VForCausalLM:()=>vh,Phi3VImageProcessor:()=>lb,Phi3VPreTrainedModel:()=>xh,Phi3VProcessor:()=>Rb,PhiForCausalLM:()=>RC,PhiModel:()=>kC,PhiPreTrainedModel:()=>_c,PixtralImageProcessor:()=>ub,PixtralProcessor:()=>Ob,PreTrainedModel:()=>C,PreTrainedTokenizer:()=>he,PretrainedConfig:()=>fH,Processor:()=>Ne,PvtForImageClassification:()=>ZC,PvtImageProcessor:()=>db,PvtModel:()=>FC,PvtPreTrainedModel:()=>lc,PyAnnoteFeatureExtractor:()=>op,PyAnnoteForAudioFrameClassification:()=>WC,PyAnnoteModel:()=>UC,PyAnnotePreTrainedModel:()=>uc,PyAnnoteProcessor:()=>Gb,QuestionAnsweringPipeline:()=>V2,Qwen2ForCausalLM:()=>VC,Qwen2Model:()=>KC,Qwen2MoeForCausalLM:()=>qC,Qwen2MoeModel:()=>jC,Qwen2MoePreTrainedModel:()=>pc,Qwen2PreTrainedModel:()=>dc,Qwen2Tokenizer:()=>KA,Qwen2VLForCausalLM:()=>oh,Qwen2VLForConditionalGeneration:()=>f_,Qwen2VLImageProcessor:()=>hp,Qwen2VLPreTrainedModel:()=>ih,Qwen2VLProcessor:()=>CH,Qwen2_5_VLForCausalLM:()=>Hh,Qwen2_5_VLForConditionalGeneration:()=>E_,Qwen2_5_VLProcessor:()=>bp,Qwen3ForCausalLM:()=>zC,Qwen3Model:()=>XC,Qwen3MoeForCausalLM:()=>QC,Qwen3MoeModel:()=>JC,Qwen3MoePreTrainedModel:()=>fc,Qwen3NextForCausalLM:()=>ew,Qwen3NextModel:()=>YC,Qwen3NextPreTrainedModel:()=>Ec,Qwen3PreTrainedModel:()=>hc,Qwen3VLForCausalLM:()=>yh,Qwen3VLForConditionalGeneration:()=>$c,Qwen3VLMoeForCausalLM:()=>rw,Qwen3VLMoeForConditionalGeneration:()=>tw,Qwen3VLProcessor:()=>Fb,Qwen3_5ForCausalLM:()=>Dh,Qwen3_5ForConditionalGeneration:()=>mc,Qwen3_5MoeForCausalLM:()=>nw,Qwen3_5MoeForConditionalGeneration:()=>aw,RFDetrForObjectDetection:()=>Hw,RFDetrModel:()=>ow,RFDetrObjectDetectionOutput:()=>Ch,RFDetrPreTrainedModel:()=>Sc,RTDetrForObjectDetection:()=>vx,RTDetrImageProcessor:()=>pb,RTDetrModel:()=>xx,RTDetrObjectDetectionOutput:()=>ms,RTDetrPreTrainedModel:()=>JH,RTDetrV2ForObjectDetection:()=>Iw,RTDetrV2Model:()=>mw,RTDetrV2ObjectDetectionOutput:()=>wh,RTDetrV2PreTrainedModel:()=>Lc,RawAudio:()=>pg,RawImage:()=>Xt,RawVideo:()=>EB,RawVideoFrame:()=>af,RepetitionPenaltyLogitsProcessor:()=>sT,ResNetForImageClassification:()=>iw,ResNetModel:()=>sw,ResNetPreTrainedModel:()=>Ic,RoFormerForMaskedLM:()=>hw,RoFormerForQuestionAnswering:()=>$w,RoFormerForSequenceClassification:()=>fw,RoFormerForTokenClassification:()=>Ew,RoFormerModel:()=>pw,RoFormerPreTrainedModel:()=>Sn,RoFormerTokenizer:()=>jA,RobertaForMaskedLM:()=>cw,RobertaForQuestionAnswering:()=>dw,RobertaForSequenceClassification:()=>lw,RobertaForTokenClassification:()=>uw,RobertaModel:()=>_w,RobertaPreTrainedModel:()=>In,RobertaTokenizer:()=>VA,Sam2ImageProcessor:()=>eH,Sam2ImageSegmentationOutput:()=>Mh,Sam2Model:()=>Ac,Sam2PreTrainedModel:()=>Ph,Sam2Processor:()=>xp,Sam2VideoProcessor:()=>Zb,Sam3ImageProcessor:()=>eH,Sam3TrackerModel:()=>Aw,SamImageProcessor:()=>eH,SamImageSegmentationOutput:()=>Nh,SamModel:()=>Sw,SamPreTrainedModel:()=>Bh,SamProcessor:()=>Tp,SapiensFeatureExtractor:()=>hb,SapiensForDepthEstimation:()=>bw,SapiensForNormalEstimation:()=>Tw,SapiensForSemanticSegmentation:()=>gw,SapiensImageProcessor:()=>Sp,SapiensPreTrainedModel:()=>xi,SeamlessM4TFeatureExtractor:()=>Sg,SegformerFeatureExtractor:()=>fb,SegformerForImageClassification:()=>vw,SegformerForSemanticSegmentation:()=>yw,SegformerImageProcessor:()=>Lp,SegformerModel:()=>xw,SegformerPreTrainedModel:()=>vi,SiglipImageProcessor:()=>Eb,SiglipModel:()=>Dw,SiglipPreTrainedModel:()=>gc,SiglipTextModel:()=>kh,SiglipTokenizer:()=>qA,SiglipVisionModel:()=>Cw,SmolLM3ForCausalLM:()=>Nw,SmolLM3Model:()=>ww,SmolLM3PreTrainedModel:()=>bc,SmolVLMForConditionalGeneration:()=>Bw,SmolVLMImageProcessor:()=>Hd,SmolVLMProcessor:()=>_d,SnacDecoderModel:()=>Oh,SnacEncoderModel:()=>Rh,SnacFeatureExtractor:()=>Lg,SnacModel:()=>Mw,SnacPreTrainedModel:()=>yi,SolarOpenForCausalLM:()=>kw,SolarOpenModel:()=>Pw,SolarOpenPreTrainedModel:()=>Tc,SpeechT5FeatureExtractor:()=>Ag,SpeechT5ForSpeechToText:()=>Ow,SpeechT5ForTextToSpeech:()=>Gw,SpeechT5HifiGan:()=>Fw,SpeechT5Model:()=>Rw,SpeechT5PreTrainedModel:()=>Di,SpeechT5Processor:()=>Ub,SpeechT5Tokenizer:()=>XA,SqueezeBertForMaskedLM:()=>Uw,SqueezeBertForQuestionAnswering:()=>Kw,SqueezeBertForSequenceClassification:()=>Ww,SqueezeBertModel:()=>Zw,SqueezeBertPreTrainedModel:()=>bs,SqueezeBertTokenizer:()=>zA,StableLmForCausalLM:()=>jw,StableLmModel:()=>Vw,StableLmPreTrainedModel:()=>xc,Starcoder2ForCausalLM:()=>Xw,Starcoder2Model:()=>qw,Starcoder2PreTrainedModel:()=>vc,StoppingCriteria:()=>Es,StoppingCriteriaList:()=>yp,StyleTextToSpeech2Model:()=>zw,StyleTextToSpeech2PreTrainedModel:()=>Gh,SummarizationPipeline:()=>q2,SupertonicForConditionalGeneration:()=>Zh,SupertonicPreTrainedModel:()=>Fh,SuppressTokensAtBeginLogitsProcessor:()=>vp,SuppressTokensLogitsProcessor:()=>rT,Swin2SRForImageSuperResolution:()=>tN,Swin2SRImageProcessor:()=>$b,Swin2SRModel:()=>eN,Swin2SRPreTrainedModel:()=>yc,SwinForImageClassification:()=>Qw,SwinForSemanticSegmentation:()=>Yw,SwinModel:()=>Jw,SwinPreTrainedModel:()=>Ci,T5ForConditionalGeneration:()=>aN,T5Model:()=>rN,T5PreTrainedModel:()=>Dc,T5Tokenizer:()=>JA,TableTransformerForObjectDetection:()=>sN,TableTransformerModel:()=>nN,TableTransformerObjectDetectionOutput:()=>Uh,TableTransformerPreTrainedModel:()=>Cc,TemperatureLogitsWarper:()=>cT,Tensor:()=>j,Text2TextGenerationPipeline:()=>Rc,TextClassificationPipeline:()=>W2,TextGenerationPipeline:()=>z2,TextStreamer:()=>fB,TextToAudioPipeline:()=>tB,TokenClassificationPipeline:()=>K2,TokenizersBackend:()=>he,TopKLogitsWarper:()=>qZ,TopPLogitsWarper:()=>jZ,TrOCRForCausalLM:()=>iN,TrOCRPreTrainedModel:()=>Wh,TranslationPipeline:()=>X2,UltravoxModel:()=>x_,UltravoxPreTrainedModel:()=>_h,UltravoxProcessor:()=>Wb,UniSpeechForCTC:()=>HN,UniSpeechForSequenceClassification:()=>_N,UniSpeechModel:()=>oN,UniSpeechPreTrainedModel:()=>wi,UniSpeechSatForAudioFrameClassification:()=>dN,UniSpeechSatForCTC:()=>lN,UniSpeechSatForSequenceClassification:()=>uN,UniSpeechSatModel:()=>cN,UniSpeechSatPreTrainedModel:()=>Ts,VLChatProcessor:()=>Db,VLMImageProcessor:()=>Jg,VaultGemmaForCausalLM:()=>hN,VaultGemmaModel:()=>pN,VaultGemmaPreTrainedModel:()=>wc,ViTFeatureExtractor:()=>mb,ViTForImageClassification:()=>$N,ViTImageProcessor:()=>Ap,ViTMAEModel:()=>mN,ViTMAEPreTrainedModel:()=>Kh,ViTMSNForImageClassification:()=>SN,ViTMSNModel:()=>IN,ViTMSNPreTrainedModel:()=>Bc,ViTModel:()=>EN,ViTPreTrainedModel:()=>Nc,VisionEncoderDecoderModel:()=>fN,VitMatteForImageMatting:()=>LN,VitMatteImageProcessor:()=>Ib,VitMattePreTrainedModel:()=>Vh,VitPoseForPoseEstimation:()=>AN,VitPoseImageProcessor:()=>Sb,VitPosePreTrainedModel:()=>jh,VitsModel:()=>gN,VitsModelOutput:()=>qh,VitsPreTrainedModel:()=>Xh,VitsTokenizer:()=>QA,VoxtralForConditionalGeneration:()=>bN,VoxtralProcessor:()=>Kb,VoxtralRealtimeFeatureExtractor:()=>Tg,VoxtralRealtimeForConditionalGeneration:()=>Jh,VoxtralRealtimePreTrainedModel:()=>zh,VoxtralRealtimeProcessor:()=>Vb,Wav2Vec2BertForCTC:()=>xN,Wav2Vec2BertForSequenceClassification:()=>vN,Wav2Vec2BertModel:()=>TN,Wav2Vec2BertPreTrainedModel:()=>Ni,Wav2Vec2CTCTokenizer:()=>YA,Wav2Vec2FeatureExtractor:()=>gg,Wav2Vec2ForAudioFrameClassification:()=>xy,Wav2Vec2ForCTC:()=>by,Wav2Vec2ForSequenceClassification:()=>Ty,Wav2Vec2Model:()=>gy,Wav2Vec2PreTrainedModel:()=>ua,Wav2Vec2Processor:()=>jb,Wav2Vec2ProcessorWithLM:()=>qb,WavLMForAudioFrameClassification:()=>NN,WavLMForCTC:()=>DN,WavLMForSequenceClassification:()=>CN,WavLMForXVector:()=>wN,WavLMModel:()=>yN,WavLMPreTrainedModel:()=>Ln,WeSpeakerFeatureExtractor:()=>bg,WeSpeakerResNetModel:()=>BN,WeSpeakerResNetPreTrainedModel:()=>Yh,WhisperFeatureExtractor:()=>xg,WhisperForConditionalGeneration:()=>ef,WhisperModel:()=>MN,WhisperPreTrainedModel:()=>Mc,WhisperProcessor:()=>Xb,WhisperTextStreamer:()=>k7,WhisperTimeStampLogitsProcessor:()=>aT,WhisperTokenizer:()=>tg,XLMForQuestionAnswering:()=>FN,XLMForSequenceClassification:()=>ON,XLMForTokenClassification:()=>GN,XLMModel:()=>kN,XLMPreTrainedModel:()=>An,XLMRobertaForMaskedLM:()=>UN,XLMRobertaForQuestionAnswering:()=>VN,XLMRobertaForSequenceClassification:()=>WN,XLMRobertaForTokenClassification:()=>KN,XLMRobertaModel:()=>ZN,XLMRobertaPreTrainedModel:()=>gn,XLMRobertaTokenizer:()=>rg,XLMTokenizer:()=>ag,XLMWithLMHeadModel:()=>RN,XVectorOutput:()=>Qh,YolosFeatureExtractor:()=>Lb,YolosForObjectDetection:()=>qN,YolosImageProcessor:()=>gp,YolosModel:()=>jN,YolosObjectDetectionOutput:()=>tf,YolosPreTrainedModel:()=>Pc,YoutuForCausalLM:()=>zN,YoutuModel:()=>XN,YoutuPreTrainedModel:()=>kc,ZeroShotAudioClassificationPipeline:()=>Y2,ZeroShotClassificationPipeline:()=>J2,ZeroShotImageClassificationPipeline:()=>sB,ZeroShotObjectDetectionPipeline:()=>oB,cat:()=>Ue,cos_sim:()=>Y6,dot:()=>rL,env:()=>ge,full:()=>xt,full_like:()=>dH,interpolate:()=>Ud,interpolate_4d:()=>dr,layer_norm:()=>jF,load_audio:()=>cg,load_image:()=>EZ,load_video:()=>R7,log_softmax:()=>tL,matmul:()=>oA,mean:()=>bH,mean_pooling:()=>HA,ones:()=>Kt,ones_like:()=>jd,permute:()=>iA,pipeline:()=>M7,quantize_embeddings:()=>cA,rand:()=>qF,randn:()=>_A,random:()=>ui,read_audio:()=>lg,rfft:()=>VF,slice:()=>Wd,softmax:()=>St,stack:()=>Ur,std_mean:()=>Kd,topk:()=>_n,zeros:()=>qd,zeros_like:()=>Xd});function GS(e){return Object.keys(e).length===0}function xa(e,t){e&&e(t)}function TO(e){return Number.isInteger(e)||typeof e=="bigint"}function dI(e){return e==null||e===-1}function pI(e){let t=[],r=e;for(;Array.isArray(r);)t.push(r.length),r=r[0];return t}function $r(...e){return Array.prototype.concat.apply([],e)}function xO(...e){return e.reduce((t,r)=>t.flatMap(a=>r.map(n=>[a,n])))}function nH(e,t){return Math.abs((e+t)%(2*t)-t)}function It(e,t){return Object.assign({},...t.map(r=>{if(e[r]!==void 0)return{[r]:e[r]}}))}function vO(e,t){let r=0;for(let a of e)a===t&&++r;return r}function f9(e){if(e===null)return null;switch(e.type){case"BertNormalizer":return new VO(e);case"Precompiled":return new qO(e);case"Sequence":return new zO(e);case"Replace":return new QO(e);case"NFC":return new t9(e);case"NFD":return new a9(e);case"NFKC":return new s9(e);case"NFKD":return new o9(e);case"Strip":return new _9(e);case"StripAccents":return new l9(e);case"Lowercase":return new d9(e);case"Prepend":return new h9(e);default:throw new Error(`Unknown Normalizer type: ${e.type}`)}}function G9(e){if(e===null)return null;switch(e.type){case"BertPreTokenizer":return new C9;case"Sequence":return new M9(e);case"Whitespace":return new S9;case"WhitespaceSplit":return new k9;case"Metaspace":return new A9(e);case"ByteLevel":return new m9(e);case"Split":return new b9(e);case"Punctuation":return new x9(e);case"Digits":return new y9(e);case"Replace":return new N9(e);case"FixedLength":return new O9(e);default:throw new Error(`Unknown PreTokenizer type: ${e.type}`)}}function j9(e){if(e.length===0)throw new Error("Array must not be empty");let t=e[0],r=0;for(let a=1;a<e.length;++a)e[a]<t&&(t=e[a],r=a);return[t,r]}function rG(e,t){switch(e.type){case"WordPiece":return new $I(e);case"Unigram":return new II(e,t.eos_token);case"BPE":return new SI(e);default:if(e.vocab)return Array.isArray(e.vocab)?new II(e,t.eos_token):Object.hasOwn(e,"continuing_subword_prefix")&&Object.hasOwn(e,"unk_token")?Object.hasOwn(e,"merges")?new SI(e):new $I(e):new tG(e,{target_lang:t.target_lang,bos_token:t.bos_token,eos_token:t.eos_token,pad_token:t.pad_token,unk_token:t.unk_token});throw new Error(`Unknown TokenizerModel type: ${e?.type}`)}}function hG(e){if(e===null)return null;switch(e.type){case"TemplateProcessing":return new iG(e);case"ByteLevel":return new HG(e);case"BertProcessing":return new cG(e);case"RobertaProcessing":return new uG(e);case"Sequence":return new pG(e);default:throw new Error(`Unknown PostProcessor type: ${e.type}`)}}function kG(e){if(e===null)return null;switch(e.type){case"ByteLevel":return new $G(e);case"WordPiece":return new IG(e);case"Metaspace":return new LG(e);case"BPEDecoder":return new gG(e);case"CTC":return new TG(e);case"Sequence":return new vG(e);case"Replace":return new DG(e);case"Fuse":return new wG(e);case"Strip":return new BG(e);case"ByteFallback":return new PG(e);default:throw new Error(`Unknown Decoder type: ${e.type}`)}}function LI(e){return/\w/.test(e)}function Vs(e){return/[0-9]/.test(e)}function AI(e){return/\s/.test(e)}function ZG(e,t={}){return e.endsWith(`
8
- `)&&(e=e.slice(0,-1)),t.lstrip_blocks&&(e=e.replace(/^[ \t]*({[#%-])/gm,"$1")),t.trim_blocks&&(e=e.replace(/([#%-]})\n/g,"$1")),e.replace(/{%\s*(end)?generation\s*%}/gs,"")}function UG(e,t={}){let r=[],a=ZG(e,t),n=0,s=0,i=_=>{let c="";for(;_(a[n]);){if(a[n]==="\\"){if(++n,n>=a.length)throw new SyntaxError("Unexpected end of input");let l=a[n++],d=FG.get(l);if(d===void 0)throw new SyntaxError(`Unexpected escaped character: ${l}`);c+=d;continue}if(c+=a[n++],n>=a.length)throw new SyntaxError("Unexpected end of input")}return c},o=()=>{let _=r.at(-1);_&&_.type===Z.Text&&(_.value=_.value.trimEnd(),_.value===""&&r.pop())},H=()=>{for(;n<a.length&&AI(a[n]);)++n};e:for(;n<a.length;){let _=r.at(-1)?.type;if(_===void 0||_===Z.CloseStatement||_===Z.CloseExpression||_===Z.Comment){let l="";for(;n<a.length&&!(a[n]==="{"&&(a[n+1]==="%"||a[n+1]==="{"||a[n+1]==="#"));)l+=a[n++];if(l.length>0){r.push(new cr(l,Z.Text));continue}}if(a[n]==="{"&&a[n+1]==="#"){n+=2;let l=a[n]==="-";l&&++n;let d="";for(;a[n]!=="#"||a[n+1]!=="}";){if(n+2>=a.length)throw new SyntaxError("Missing end of comment tag");d+=a[n++]}let h=d.endsWith("-");h&&(d=d.slice(0,-1)),l&&o(),r.push(new cr(d,Z.Comment)),n+=2,h&&H();continue}if(a.slice(n,n+3)==="{%-"){o(),r.push(new cr("{%",Z.OpenStatement)),n+=3;continue}if(a.slice(n,n+3)==="{{-"){o(),r.push(new cr("{{",Z.OpenExpression)),s=0,n+=3;continue}if(i(AI),a.slice(n,n+3)==="-%}"){r.push(new cr("%}",Z.CloseStatement)),n+=3,H();continue}if(a.slice(n,n+3)==="-}}"){r.push(new cr("}}",Z.CloseExpression)),n+=3,H();continue}let c=a[n];if(c==="-"||c==="+"){let l=r.at(-1)?.type;if(l===Z.Text||l===void 0)throw new SyntaxError(`Unexpected character: ${c}`);switch(l){case Z.Identifier:case Z.NumericLiteral:case Z.StringLiteral:case Z.CloseParen:case Z.CloseSquareBracket:break;default:{++n;let d=i(Vs);r.push(new cr(`${c}${d}`,d.length>0?Z.NumericLiteral:Z.UnaryOperator));continue}}}for(let[l,d]of GG){if(l==="}}"&&s>0)continue;if(a.slice(n,n+l.length)===l){r.push(new cr(l,d)),d===Z.OpenExpression?s=0:d===Z.OpenCurlyBracket?++s:d===Z.CloseCurlyBracket&&--s,n+=l.length;continue e}}if(c==="'"||c==='"'){++n;let l=i(d=>d!==c);r.push(new cr(l,Z.StringLiteral)),++n;continue}if(Vs(c)){let l=i(Vs);if(a[n]==="."&&Vs(a[n+1])){++n;let d=i(Vs);l=`${l}.${d}`}r.push(new cr(l,Z.NumericLiteral));continue}if(LI(c)){let l=i(LI);r.push(new cr(l,Z.Identifier));continue}throw new SyntaxError(`Unexpected character: ${c}`)}return r}function d6(e){let t=new WG([]),r=0;function a(B,O){let U=e[r++];if(!U||U.type!==B)throw new Error(`Parser Error: ${O}. ${U.type} !== ${B}.`);return U}function n(B){if(!H(B))throw new SyntaxError(`Expected ${B}`);++r}function s(){switch(e[r].type){case Z.Comment:return new JG(e[r++].value);case Z.Text:return _();case Z.OpenStatement:return c();case Z.OpenExpression:return l();default:throw new SyntaxError(`Unexpected token type: ${e[r].type}`)}}function i(...B){return r+B.length<=e.length&&B.every((O,U)=>O===e[r+U].type)}function o(...B){return e[r]?.type===Z.OpenStatement&&e[r+1]?.type===Z.Identifier&&B.includes(e[r+1]?.value)}function H(...B){return r+B.length<=e.length&&B.every((O,U)=>e[r+U].type==="Identifier"&&O===e[r+U].value)}function _(){return new bI(a(Z.Text,"Expected text token").value)}function c(){if(a(Z.OpenStatement,"Expected opening statement token"),e[r].type!==Z.Identifier)throw new SyntaxError(`Unknown statement, got ${e[r].type}`);let B=e[r].value,O;switch(B){case"set":++r,O=d();break;case"if":++r,O=h(),a(Z.OpenStatement,"Expected {% token"),n("endif"),a(Z.CloseStatement,"Expected %} token");break;case"macro":++r,O=$(),a(Z.OpenStatement,"Expected {% token"),n("endmacro"),a(Z.CloseStatement,"Expected %} token");break;case"for":++r,O=S(),a(Z.OpenStatement,"Expected {% token"),n("endfor"),a(Z.CloseStatement,"Expected %} token");break;case"call":{++r;let U=null;i(Z.OpenParen)&&(U=X());let Y=te();if(Y.type!=="Identifier")throw new SyntaxError("Expected identifier following call statement");let Se=X();a(Z.CloseStatement,"Expected closing statement token");let We=[];for(;!o("endcall");)We.push(s());a(Z.OpenStatement,"Expected '{%'"),n("endcall"),a(Z.CloseStatement,"Expected closing statement token");let ce=new gI(Y,Se);O=new l6(ce,U,We);break}case"break":++r,a(Z.CloseStatement,"Expected closing statement token"),O=new jG;break;case"continue":++r,a(Z.CloseStatement,"Expected closing statement token"),O=new qG;break;case"filter":{++r;let U=te();U instanceof zn&&i(Z.OpenParen)&&(U=K(U)),a(Z.CloseStatement,"Expected closing statement token");let Y=[];for(;!o("endfilter");)Y.push(s());a(Z.OpenStatement,"Expected '{%'"),n("endfilter"),a(Z.CloseStatement,"Expected '%}'"),O=new n6(U,Y);break}default:throw new SyntaxError(`Unknown statement type: ${B}`)}return O}function l(){a(Z.OpenExpression,"Expected opening expression token");let B=I();return a(Z.CloseExpression,"Expected closing expression token"),B}function d(){let B=m(),O=null,U=[];if(i(Z.Equals))++r,O=m();else{for(a(Z.CloseStatement,"Expected %} token");!o("endset");)U.push(s());a(Z.OpenStatement,"Expected {% token"),n("endset")}return a(Z.CloseStatement,"Expected closing statement token"),new XG(B,O,U)}function h(){let B=I();a(Z.CloseStatement,"Expected closing statement token");let O=[],U=[];for(;!o("elif","else","endif");)O.push(s());if(o("elif")){++r,++r;let Y=h();U.push(Y)}else if(o("else"))for(++r,++r,a(Z.CloseStatement,"Expected closing statement token");!o("endif");)U.push(s());return new KG(B,O,U)}function $(){let B=te();if(B.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");let O=X();a(Z.CloseStatement,"Expected closing statement token");let U=[];for(;!o("endmacro");)U.push(s());return new zG(B,O,U)}function m(B=!1){let O=B?te:I,U=[O()],Y=i(Z.Comma);for(;Y&&(++r,U.push(O()),!!i(Z.Comma)););return Y?new TI(U):U[0]}function S(){let B=m(!0);if(!(B instanceof zn||B instanceof TI))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${B.type} instead`);if(!H("in"))throw new SyntaxError("Expected `in` keyword following loop variable");++r;let O=I();a(Z.CloseStatement,"Expected closing statement token");let U=[];for(;!o("endfor","else");)U.push(s());let Y=[];if(o("else"))for(++r,++r,a(Z.CloseStatement,"Expected closing statement token");!o("endfor");)Y.push(s());return new VG(B,O,U,Y)}function I(){return g()}function g(){let B=T();if(H("if")){++r;let O=T();if(H("else")){++r;let U=g();return new u6(O,B,U)}else return new s6(B,O)}return B}function T(){let B=x();for(;H("or");){let O=e[r];++r;let U=x();B=new js(O,B,U)}return B}function x(){let B=v();for(;H("and");){let O=e[r];++r;let U=v();B=new js(O,B,U)}return B}function v(){let B;for(;H("not");){let O=e[r];++r;let U=v();B=new o6(O,U)}return B??k()}function k(){let B=L();for(;;){let O;if(H("not","in"))O=new cr("not in",Z.Identifier),r+=2;else if(H("in"))O=e[r++];else if(i(Z.ComparisonBinaryOperator))O=e[r++];else break;let U=L();B=new js(O,B,U)}return B}function L(){let B=F();for(;i(Z.AdditiveBinaryOperator);){let O=e[r];++r;let U=F();B=new js(O,B,U)}return B}function V(){let B=M(te());return i(Z.OpenParen)?K(B):B}function K(B){let O=new gI(B,X());return O=M(O),i(Z.OpenParen)&&(O=K(O)),O}function X(){a(Z.OpenParen,"Expected opening parenthesis for arguments list");let B=Q();return a(Z.CloseParen,"Expected closing parenthesis for arguments list"),B}function Q(){let B=[];for(;!i(Z.CloseParen);){let O;if(e[r].type===Z.MultiplicativeBinaryOperator&&e[r].value==="*"){++r;let U=I();O=new c6(U)}else if(O=I(),i(Z.Equals)){if(++r,!(O instanceof zn))throw new SyntaxError("Expected identifier for keyword argument");let U=I();O=new _6(O,U)}B.push(O),i(Z.Comma)&&++r}return B}function z(){let B=[],O=!1;for(;!i(Z.CloseSquareBracket);)i(Z.Colon)?(B.push(void 0),++r,O=!0):(B.push(I()),i(Z.Colon)&&(++r,O=!0));if(B.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(O){if(B.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new H6(...B)}return B[0]}function M(B){for(;i(Z.Dot)||i(Z.OpenSquareBracket);){let O=e[r];++r;let U,Y=O.type===Z.OpenSquareBracket;if(Y)U=z(),a(Z.CloseSquareBracket,"Expected closing square bracket");else if(U=te(),U.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");B=new QG(B,U,Y)}return B}function F(){let B=N();for(;i(Z.MultiplicativeBinaryOperator);){let O=e[r++],U=N();B=new js(O,B,U)}return B}function N(){let B=G();for(;H("is");){++r;let O=H("not");O&&++r;let U=te();if(!(U instanceof zn))throw new SyntaxError("Expected identifier for the test");B=new i6(B,O,U)}return B}function G(){let B=V();for(;i(Z.Pipe);){++r;let O=te();if(!(O instanceof zn))throw new SyntaxError("Expected identifier for the filter");i(Z.OpenParen)&&(O=K(O)),B=new a6(B,O)}return B}function te(){let B=e[r++];switch(B.type){case Z.NumericLiteral:{let O=B.value;return O.includes(".")?new e6(Number(O)):new YG(Number(O))}case Z.StringLiteral:{let O=B.value;for(;i(Z.StringLiteral);)O+=e[r++].value;return new bI(O)}case Z.Identifier:return new zn(B.value);case Z.OpenParen:{let O=m();return a(Z.CloseParen,"Expected closing parenthesis, got ${tokens[current].type} instead."),O}case Z.OpenSquareBracket:{let O=[];for(;!i(Z.CloseSquareBracket);)O.push(I()),i(Z.Comma)&&++r;return++r,new t6(O)}case Z.OpenCurlyBracket:{let O=new Map;for(;!i(Z.CloseCurlyBracket);){let U=I();a(Z.Colon,"Expected colon between key and value in object literal");let Y=I();O.set(U,Y),i(Z.Comma)&&++r}return++r,new r6(O)}default:throw new SyntaxError(`Unexpected token: ${B.type}`)}}for(;r<e.length;)t.body.push(s());return t}function p6(e,t,r=1){if(t===void 0&&(t=e,e=0),r===0)throw new Error("range() step must not be zero");let a=[];if(r>0)for(let n=e;n<t;n+=r)a.push(n);else for(let n=e;n>t;n+=r)a.push(n);return a}function xI(e,t,r,a=1){let n=Math.sign(a);n>=0?(t=(t??=0)<0?Math.max(e.length+t,0):Math.min(t,e.length),r=(r??=e.length)<0?Math.max(e.length+r,0):Math.min(r,e.length)):(t=(t??=e.length-1)<0?Math.max(e.length+t,-1):Math.min(t,e.length-1),r=(r??=-1)<-1?Math.max(e.length+r,-1):Math.min(r,e.length-1));let s=[];for(let i=t;n*i<n*r;i+=a)s.push(e[i]);return s}function h6(e){return e.replace(/\b\w/g,t=>t.toUpperCase())}function f6(e){return E6(new Date,e)}function E6(e,t){let r=new Intl.DateTimeFormat(void 0,{month:"long"}),a=new Intl.DateTimeFormat(void 0,{month:"short"}),n=s=>s<10?"0"+s:s.toString();return t.replace(/%[YmdbBHM%]/g,s=>{switch(s){case"%Y":return e.getFullYear().toString();case"%m":return n(e.getMonth()+1);case"%d":return n(e.getDate());case"%b":return a.format(e);case"%B":return r.format(e);case"%H":return n(e.getHours());case"%M":return n(e.getMinutes());case"%%":return"%";default:return s}})}function $6(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function m6(e,t,r,a){if(a===0)return e;let n=a==null||a<0?1/0:a,s=t.length===0?new RegExp("(?=)","gu"):new RegExp($6(t),"gu");return e.replaceAll(s,i=>n>0?(--n,r):i)}function DI(e){return e.replace(I6,t=>"\\u"+t.charCodeAt(0).toString(16).padStart(4,"0"))}function tn(e,t={},r=0,a=!0){let{indent:n=null,ensureAscii:s=!1,separators:i=null,sortKeys:o=!1}=t,H,_;switch(i?[H,_]=i:n?(H=",",_=": "):(H=", ",_=": "),e.type){case"NullValue":return"null";case"UndefinedValue":return a?"null":"undefined";case"IntegerValue":case"FloatValue":case"BooleanValue":return JSON.stringify(e.value);case"StringValue":{let c=JSON.stringify(e.value);return s&&(c=DI(c)),c}case"ArrayValue":case"ObjectValue":{let c=n?" ".repeat(n):"",l=`
9
- `+c.repeat(r),d=l+c;if(e.type==="ArrayValue"){let h=e.value.map($=>tn($,t,r+1,a));return n?`[${d}${h.join(`${H}${d}`)}${l}]`:`[${h.join(H)}]`}else{let h=Array.from(e.value.entries());o&&(h=h.sort(([m],[S])=>m.localeCompare(S)));let $=h.map(([m,S])=>{let I=JSON.stringify(m);s&&(I=DI(I));let g=`${I}${_}${tn(S,t,r+1,a)}`;return n?`${d}${g}`:g});return n?`{${$.join(H)}${l}}`:`{${$.join(H)}}`}}default:throw new Error(`Cannot convert to JSON: ${e.type}`)}}function S6(e){e.set("false",!1),e.set("true",!0),e.set("none",null),e.set("raise_exception",t=>{throw new Error(t)}),e.set("range",p6),e.set("strftime_now",f6),e.set("True",!0),e.set("False",!1),e.set("None",null)}function wI(e,t){let r=t.split("."),a=e;for(let n of r)if(a instanceof mt)a=a.value.get(n)??new je;else if(a instanceof Ae){let s=parseInt(n,10);if(!isNaN(s)&&s>=0&&s<a.value.length)a=a.value[s];else return new je}else return new je;return a}function Yu(e,t,r=!1){if(e instanceof ze&&t instanceof ze)return 0;if(e instanceof ze||t instanceof ze)throw new Error(`Cannot compare ${e.type} with ${t.type}`);if(e instanceof je&&t instanceof je)return 0;if(e instanceof je||t instanceof je)throw new Error(`Cannot compare ${e.type} with ${t.type}`);let a=s=>s instanceof me||s instanceof tt||s instanceof pe,n=s=>s instanceof pe?s.value?1:0:s.value;if(a(e)&&a(t)){let s=n(e),i=n(t);return s<i?-1:s>i?1:0}if(e.type!==t.type)throw new Error(`Cannot compare different types: ${e.type} and ${t.type}`);if(e.type==="StringValue"){let s=e.value,i=t.value;return r||(s=s.toLowerCase(),i=i.toLowerCase()),s<i?-1:s>i?1:0}else throw new Error(`Cannot compare type: ${e.type}`)}function Jo(e){switch(typeof e){case"number":return Number.isInteger(e)?new me(e):new tt(e);case"string":return new ie(e);case"boolean":return new pe(e);case"undefined":return new je;case"object":return e===null?new ze:Array.isArray(e)?new Ae(e.map(Jo)):new mt(new Map(Object.entries(e).map(([t,r])=>[t,Jo(r)])));case"function":return new qe((t,r)=>{let a=e(...t.map(n=>n.value))??null;return Jo(a)});default:throw new Error(`Cannot convert to runtime value: ${e}`)}}function b6(e){switch(e.operator.type){case"MultiplicativeBinaryOperator":return 4;case"AdditiveBinaryOperator":return 3;case"ComparisonBinaryOperator":return 2;case"Identifier":return e.operator.value==="and"?1:e.operator.value==="in"||e.operator.value==="not in"?2:0}return 0}function T6(e,t=" "){let r=typeof t=="number"?" ".repeat(t):t;return Ir(e.body,0,r).replace(/\n$/,"")}function Tt(...e){return A6+e.join(" ")+g6}function Ir(e,t,r){return e.map(a=>x6(a,t,r)).join(ut)}function x6(e,t,r){let a=r.repeat(t);switch(e.type){case"Program":return Ir(e.body,t,r);case"If":return v6(e,t,r);case"For":return y6(e,t,r);case"Set":return D6(e,t,r);case"Macro":return C6(e,t,r);case"Break":return a+Tt("break");case"Continue":return a+Tt("continue");case"CallStatement":return w6(e,t,r);case"FilterStatement":return N6(e,t,r);case"Comment":return a+"{# "+e.value+" #}";default:return a+"{{- "+Te(e)+" -}}"}}function v6(e,t,r){let a=r.repeat(t),n=[],s=e;for(;s&&(n.push({test:s.test,body:s.body}),s.alternate.length===1&&s.alternate[0].type==="If");)s=s.alternate[0];let i=a+Tt("if",Te(n[0].test))+ut+Ir(n[0].body,t+1,r);for(let o=1;o<n.length;++o)i+=ut+a+Tt("elif",Te(n[o].test))+ut+Ir(n[o].body,t+1,r);return s&&s.alternate.length>0&&(i+=ut+a+Tt("else")+ut+Ir(s.alternate,t+1,r)),i+=ut+a+Tt("endif"),i}function y6(e,t,r){let a=r.repeat(t),n="";if(e.iterable.type==="SelectExpression"){let i=e.iterable;n=`${Te(i.lhs)} if ${Te(i.test)}`}else n=Te(e.iterable);let s=a+Tt("for",Te(e.loopvar),"in",n)+ut+Ir(e.body,t+1,r);return e.defaultBlock.length>0&&(s+=ut+a+Tt("else")+ut+Ir(e.defaultBlock,t+1,r)),s+=ut+a+Tt("endfor"),s}function D6(e,t,r){let a=r.repeat(t),n=Te(e.assignee),s=e.value?Te(e.value):"",i=a+Tt("set",`${n}${e.value?" = "+s:""}`);return e.body.length===0?i:i+ut+Ir(e.body,t+1,r)+ut+a+Tt("endset")}function C6(e,t,r){let a=r.repeat(t),n=e.args.map(Te).join(", ");return a+Tt("macro",`${e.name.value}(${n})`)+ut+Ir(e.body,t+1,r)+ut+a+Tt("endmacro")}function w6(e,t,r){let a=r.repeat(t),n=e.callerArgs&&e.callerArgs.length>0?`(${e.callerArgs.map(Te).join(", ")})`:"",s=Te(e.call),i=a+Tt(`call${n}`,s)+ut;return i+=Ir(e.body,t+1,r)+ut,i+=a+Tt("endcall"),i}function N6(e,t,r){let a=r.repeat(t),n=e.filter.type==="Identifier"?e.filter.value:Te(e.filter),s=a+Tt("filter",n)+ut;return s+=Ir(e.body,t+1,r)+ut,s+=a+Tt("endfilter"),s}function Te(e,t=-1){switch(e.type){case"SpreadExpression":return`*${Te(e.argument)}`;case"Identifier":return e.value;case"IntegerLiteral":return`${e.value}`;case"FloatLiteral":return`${e.value}`;case"StringLiteral":return JSON.stringify(e.value);case"BinaryExpression":{let r=e,a=b6(r),n=Te(r.left,a),s=Te(r.right,a+1),i=`${n} ${r.operator.value} ${s}`;return a<t?`(${i})`:i}case"UnaryExpression":{let r=e;return r.operator.value+(r.operator.value==="not"?" ":"")+Te(r.argument,1/0)}case"CallExpression":{let r=e,a=r.args.map(Te).join(", ");return`${Te(r.callee)}(${a})`}case"MemberExpression":{let r=e,a=Te(r.object);["Identifier","MemberExpression","CallExpression","StringLiteral","IntegerLiteral","FloatLiteral","ArrayLiteral","TupleLiteral","ObjectLiteral"].includes(r.object.type)||(a=`(${a})`);let n=Te(r.property);return!r.computed&&r.property.type!=="Identifier"&&(n=`(${n})`),r.computed?`${a}[${n}]`:`${a}.${n}`}case"FilterExpression":{let r=e,a=Te(r.operand,1/0);return r.filter.type==="CallExpression"?`${a} | ${Te(r.filter)}`:`${a} | ${r.filter.value}`}case"SelectExpression":{let r=e;return`${Te(r.lhs)} if ${Te(r.test)}`}case"TestExpression":{let r=e;return`${Te(r.operand)} is${r.negate?" not":""} ${r.test.value}`}case"ArrayLiteral":case"TupleLiteral":{let r=e.value.map(Te),a=e.type==="ArrayLiteral"?"[]":"()";return`${a[0]}${r.join(", ")}${a[1]}`}case"ObjectLiteral":return`{${Array.from(e.value.entries()).map(([a,n])=>`${Te(a)}: ${Te(n)}`).join(", ")}}`;case"SliceExpression":{let r=e,a=r.start?Te(r.start):"",n=r.stop?Te(r.stop):"",s=r.step?`:${Te(r.step)}`:"";return`${a}:${n}${s}`}case"KeywordArgumentExpression":{let r=e;return`${r.key.value}=${Te(r.value)}`}case"Ternary":{let r=e,a=`${Te(r.trueExpr)} if ${Te(r.condition,0)} else ${Te(r.falseExpr)}`;return t>-1?`(${a})`:a}default:throw new Error(`Unknown expression type: ${e.type}`)}}function zS(e,t){let r=0;for(let n=0;n<t.length;++n)r+=t[n];let a=e()*r;for(let n=0;n<t.length;++n)if(a-=t[n],a<0)return n;return t.length-1}function ko(...e){return e=e.map((t,r)=>(r&&(t=t.replace(new RegExp("^/"),"")),r!==e.length-1&&(t=t.replace(new RegExp("/$"),"")),t)),e.join("/")}function ps(e,t=null,r=null){let a;try{a=new URL(e)}catch{return!1}return!(t&&!t.includes(a.protocol)||r&&!r.includes(a.hostname))}function G6(e){return!(!O6.test(e)||e.includes("..")||e.includes("--")||e.endsWith(".git")||e.endsWith(".ipynb"))}function F6(e,t,r){if(!r)return null;let a=R6[e]??`Error (${e}) occurred while trying to load file`;throw Error(`${a}: "${t}".`)}async function Z6(e,t,r){let a=e.headers.get("Content-Length"),n=a?parseInt(a,10):r??0;a===null&&!r&&fe.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let s=new Uint8Array(n),i=0,o=e.body.getReader();async function H(){let{done:_,value:c}=await o.read();if(_)return;let l=i+c.length;if(l>n){n=l;let h=new Uint8Array(n);h.set(s),s=h}s.set(c,i),i=l;let d=i/n*100;return t({progress:d,loaded:i,total:n}),H()}return await H(),s}function BI(e){return ps(e,["blob:"])}function MI(e){let t;if(typeof location<"u"&&location.href)t=location.href;else if(typeof Wt<"u"&&Wt.url)t=Wt.url;else return e;return new URL(e,t).href}async function hs(e=null){let t=null;if(ge.useCustomCache){if(!ge.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!ge.customCache.match||!ge.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");t=ge.customCache}if(!t&&ge.experimental_useCrossOriginStorage&&kI.isAvailable()&&(t=new kI),!t&&ge.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{t=await caches.open(ge.cacheKey)}catch(r){fe.warn("An error occurred while opening the browser cache:",r)}}if(!t&&ge.useFSCache){if(!Ie.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");t=new JS(e??ge.cacheDir)}return t}async function W6(e,...t){for(let r of t)try{let a=await e.match(r);if(a)return a}catch{continue}}function YS(e,t){let r=Au.get(e);if(r!==void 0)return r;let a=t().then(n=>n,n=>(Au.delete(e),Promise.reject(n)));return Au.put(e,a),a}async function j6(e){if(!ps(e,["http:","https:"]))return null;let t=eL(e);return t.set("Range","bytes=0-0"),ge.fetch(e,{method:"GET",headers:t,cache:"no-store"})}function sn(e,t,r={}){let a=JSON.stringify([e,t,r?.revision,r?.cache_dir,r?.local_files_only]);return YS(a,()=>q6(e,t,r))}async function q6(e,t,r){let a=await hs(r?.cache_dir),{localPath:n,remoteURL:s,proposedCacheKey:i,validModelId:o}=di(e,t,r,a),H=await pi(a,n,i);if(H!==void 0&&typeof H!="string"){let _=H.headers.get("content-length"),c=H.headers.get("content-type");return{exists:!0,size:_?parseInt(_,10):void 0,contentType:c||void 0,fromCache:!0}}if(ge.allowLocalModels&&!ps(n,["http:","https:"]))try{let c=await si(n);if(typeof c!="string"&&c.status!==404){let l=c.headers.get("content-length"),d=c.headers.get("content-type");return{exists:!0,size:l?parseInt(l,10):void 0,contentType:d||void 0,fromCache:!1}}}catch{}if(ge.allowRemoteModels&&!r.local_files_only&&o)try{let _=await j6(s);if(_&&_.status>=200&&_.status<300){let c,l=_.headers.get("content-type");if(_.status===206){let d=_.headers.get("content-range");if(d){let h=d.match(/bytes \d+-\d+\/(\d+)/);h&&(c=parseInt(h[1],10))}}else if(_.status===200)try{await _.body?.cancel()}catch{}if(c===void 0){let d=_.headers.get("content-length");c=d?parseInt(d,10):void 0}return{exists:!0,size:c,contentType:l||void 0,fromCache:!1}}}catch(_){fe.warn(`Unable to fetch file metadata for "${s}": ${_}`)}return{exists:!1,fromCache:!1}}async function si(e){return ge.useFS&&!ps(e,["http:","https:","blob:"])?new iH(e instanceof URL?e.protocol==="file:"?e.pathname:e.toString():e):ge.fetch(e,{headers:eL(e)})}function eL(e){let t=typeof process<"u"&&process?.release?.name==="node",r=new Headers;if(t){let a=!!process.env?.TESTING_REMOTELY,n=ge.version;if(r.set("User-Agent",`transformers.js/${n}; is_ci/${a};`),ps(e,["http:","https:"],["huggingface.co","hf.co"])){let i=process.env?.HF_TOKEN??process.env?.HF_ACCESS_TOKEN;i&&r.set("Authorization",`Bearer ${i}`)}}return r}function di(e,t,r={},a=null){let n=r.revision??"main",s=ko(e,t),i=G6(e),o=i?ko(ge.localModelPath,s):s,H=ko(ge.remoteHost,ge.remotePathTemplate.replaceAll("{model}",e).replaceAll("{revision}",encodeURIComponent(n)),t),_=a instanceof JS?n==="main"?s:ko(e,n,t):H;return{requestURL:s,localPath:o,remoteURL:H,proposedCacheKey:_,validModelId:i}}async function pi(e,t,r){if(e)return await W6(e,t,r)}async function X6(e,t,r,a,n,s,i={}){if(await r.match(a)===void 0)if(s){if(typeof n!="string"){let o=new Headers(n.headers);o.set("content-length",s.byteLength.toString()),await r.put(a,new Response(s,{headers:o})).catch(H=>{fe.warn(`Unable to add response to browser cache: ${H}.`)})}}else{let o=i.progress_callback?H=>xa(i.progress_callback,{status:"progress",name:e,file:t,...H}):void 0;await r.put(a,n,o)}}async function z6(e,t,r=!0,a={},n=!1,s=null){let{requestURL:i,localPath:o,remoteURL:H,proposedCacheKey:_,validModelId:c}=di(e,t,a,s),l,d=!1,h;h=await pi(s,o,_);let $=h!==void 0;if($)l=_;else{if(ge.allowLocalModels)if(ps(i,["http:","https:"])){if(a.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${i}.`);if(!ge.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${i}.`)}else try{h=await si(o),l=o}catch(g){fe.warn(`Unable to load from local path "${o}": "${g}"`)}if(h===void 0||typeof h!="string"&&h.status===404){if(a.local_files_only||!ge.allowRemoteModels){if(r)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${o}".`);return null}if(!c)throw Error(`Local file missing at "${o}" and download aborted due to invalid model ID "${e}".`);if(h=await si(H),h.status!==200)return F6(h.status,H,r);l=_}d=s&&typeof Response<"u"&&h instanceof Response&&h.status===200}xa(a.progress_callback,{status:"download",name:e,file:t});let m;if(!(Ie.IS_NODE_ENV&&n)){let I;if(typeof h!="string")if(!a.progress_callback)I=new Uint8Array(await h.arrayBuffer());else if($&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent))I=new Uint8Array(await h.arrayBuffer()),xa(a.progress_callback,{status:"progress",name:e,file:t,progress:100,loaded:I.length,total:I.length});else{let g,T=h.headers.get("content-length");if(T)g=parseInt(T,10);else try{let x=await sn(e,t,a);x.size&&(g=x.size)}catch{}I=await Z6(h,x=>{xa(a.progress_callback,{status:"progress",name:e,file:t,...x})},g)}m=I}if(d&&l&&typeof h!="string"&&await X6(e,t,s,l,h,m,a),Ie.IS_NODE_ENV&&n&&a.progress_callback&&typeof h!="string"){let I=parseInt(h.headers.get("content-length"),10)||0;xa(a.progress_callback,{status:"progress",name:e,file:t,progress:100,loaded:I,total:I})}if(xa(a.progress_callback,{status:"done",name:e,file:t}),m){if(!Ie.IS_NODE_ENV&&n)throw new Error("Cannot return path in a browser environment.");return m}if(h instanceof iH)return h.filePath;let S=await s?.match(l);if(S instanceof iH)return S.filePath;if(S instanceof Response)return new Uint8Array(await S.arrayBuffer());if(typeof S=="string")return S;throw new Error("Unable to get model file path or buffer.")}async function oH(e,t,r=!0,a={},n=!1){if(!ge.allowLocalModels){if(a.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(!ge.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}xa(a.progress_callback,{status:"initiate",name:e,file:t});let s=`${e}::${t}`,i=Ro.get(s);if(!i){let o=await hs(a?.cache_dir);i=z6(e,t,r,a,n,o).then(H=>(Ro.delete(s),H),H=>{throw Ro.delete(s),H}),Ro.set(s,i)}return await i}async function gd(e,t,r=!0,a={}){let n=await oH(e,t,r,a,!1);return n===null?null:new TextDecoder("utf-8").decode(n)}async function jr(e,t,r=!0,a={}){let n=await gd(e,t,r,a);return n===null?{}:JSON.parse(n)}function J6(e,[t,r,a],[n,s],i="bilinear",o=!1){let H=s/a,_=n/r,c=new e.constructor(n*s*t),l=r*a,d=n*s;for(let h=0;h<n;++h)for(let $=0;$<s;++$){let m=h*s+$,S=($+.5)/H-.5,I=(h+.5)/_-.5,g=Math.floor(S),T=Math.floor(I),x=Math.min(g+1,a-1),v=Math.min(T+1,r-1);g=Math.max(g,0),T=Math.max(T,0);let k=S-g,L=I-T,V=(1-k)*(1-L),K=k*(1-L),X=(1-k)*L,Q=k*L,z=T*a,M=v*a,F=z+g,N=z+x,G=M+g,te=M+x;for(let B=0;B<t;++B){let O=B*l;c[B*d+m]=V*e[O+F]+K*e[O+N]+X*e[O+G]+Q*e[O+te]}}return c}function Q6(e,t,r){let a=new Array(r.length),n=new Array(r.length);for(let o=r.length-1,H=1;o>=0;--o)n[o]=H,a[o]=t[r[o]],H*=a[o];let s=r.map((o,H)=>n[r.indexOf(H)]),i=new e.constructor(e.length);for(let o=0;o<e.length;++o){let H=0;for(let _=t.length-1,c=o;_>=0;--_)H+=c%t[_]*s[_],c=Math.floor(c/t[_]);i[H]=e[o]}return[i,a]}function St(e){let t=nt(e)[0],r=e.map(s=>Math.exp(s-t)),a=r.reduce((s,i)=>s+i,0);return r.map(s=>s/a)}function tL(e){let t=nt(e)[0],r=0;for(let s=0;s<e.length;++s)r+=Math.exp(e[s]-t);let a=Math.log(r);return e.map(s=>s-t-a)}function rL(e,t){let r=0;for(let a=0;a<e.length;++a)r+=e[a]*t[a];return r}function Y6(e,t){let r=rL(e,t),a=RI(e),n=RI(t);return r/(a*n)}function RI(e){return Math.sqrt(e.reduce((t,r)=>t+r*r,0))}function ed(e){if(e.length===0)throw Error("Array must not be empty");let t=e[0],r=0;for(let a=1;a<e.length;++a)e[a]<t&&(t=e[a],r=a);return[t,r]}function nt(e){if(e.length===0)throw Error("Array must not be empty");let t=e[0],r=0;for(let a=1;a<e.length;++a)e[a]>t&&(t=e[a],r=a);return[t,r]}function aL(e){return e>0&&(e&e-1)===0}function rF(e,t){if(t%2===0||t<=0)throw new Error("Window size must be a positive odd number");let r=new e.constructor(e.length),a=new e.constructor(t),n=Math.floor(t/2);for(let s=0;s<e.length;++s){let i=0;for(let o=-n;o<=n;++o){let H=s+o;H<0?H=Math.abs(H):H>=e.length&&(H=2*(e.length-1)-H),a[i++]=e[H]}a.sort(),r[s]=a[n]}return r}function ti(e,t){let r=Math.pow(10,t);return Math.round(e*r)/r}function aF(e){let t=Math.round(e);return Math.abs(e)%1===.5?t%2===0?t:t-1:t}function nF(e){let t=e.length,r=e[0].length,a=[t+1,r+1],n=Array.from({length:a[0]},()=>Array(a[1]).fill(1/0));n[0][0]=0;let s=Array.from({length:a[0]},()=>Array(a[1]).fill(-1));for(let c=1;c<a[1];++c)for(let l=1;l<a[0];++l){let d=n[l-1][c-1],h=n[l-1][c],$=n[l][c-1],m,S;d<h&&d<$?(m=d,S=0):h<d&&h<$?(m=h,S=1):(m=$,S=2),n[l][c]=e[l-1][c-1]+m,s[l][c]=S}for(let c=0;c<a[1];++c)s[0][c]=2;for(let c=0;c<a[0];++c)s[c][0]=1;let i=t,o=r,H=[],_=[];for(;i>0||o>0;)switch(H.push(i-1),_.push(o-1),s[i][o]){case 0:--i,--o;break;case 1:--i;break;case 2:--o;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${i}, ${o}]. Please file a bug report.`)}return H.reverse(),_.reverse(),[H,_]}async function GI(e={}){var t=e,r=!!globalThis.window,a=!!globalThis.WorkerGlobalScope,n=a&&self.name?.startsWith("em-pthread");t.mountExternalData=(u,p)=>{u.startsWith("./")&&(u=u.substring(2)),(t.Uc||(t.Uc=new Map)).set(u,p)},t.unmountExternalData=()=>{delete t.Uc},globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let s=()=>{let u=p=>(...f)=>{let E=vr;return f=p(...f),vr!=E?new Promise((A,y)=>{Jc={resolve:A,reject:y}}):f};(()=>{for(let p of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])t[p]=u(t[p])})(),typeof jsepRunAsync<"u"&&(t._OrtRun=jsepRunAsync(t._OrtRun),t._OrtRunWithBinding=jsepRunAsync(t._OrtRunWithBinding)),s=void 0};t.asyncInit=()=>{s?.()};var i,o,H=(u,p)=>{throw p},_=Wt.url,c="";if(r||a){try{c=new URL(".",_).href}catch{}a&&(o=u=>{var p=new XMLHttpRequest;return p.open("GET",u,!1),p.responseType="arraybuffer",p.send(null),new Uint8Array(p.response)}),i=async u=>{if(k(u))return new Promise((f,E)=>{var A=new XMLHttpRequest;A.open("GET",u,!0),A.responseType="arraybuffer",A.onload=()=>{A.status==200||A.status==0&&A.response?f(A.response):E(A.status)},A.onerror=E,A.send(null)});var p=await fetch(u,{credentials:"same-origin"});if(p.ok)return p.arrayBuffer();throw Error(p.status+" : "+p.url)}}var l,d,h,$,m,S,I=console.log.bind(console),g=console.error.bind(console),T=I,x=g,v=!1,k=u=>u.startsWith("file://");function L(){pa.buffer!=X.buffer&&Se()}if(n){let u=function(p){try{var f=p.data,E=f.Oc;if(E==="load"){let A=[];self.onmessage=y=>A.push(y),S=()=>{postMessage({Oc:"loaded"});for(let y of A)u(y);self.onmessage=u};for(let y of f.ce)t[y]&&!t[y].proxy||(t[y]=(...w)=>{postMessage({Oc:"callHandler",be:y,args:w})},y=="print"&&(T=t[y]),y=="printErr"&&(x=t[y]));pa=f.ie,Se(),d=f.je,Ke(),Xi()}else if(E==="run"){(function(A){var y=(L(),N)[A+52>>>2>>>0];A=(L(),N)[A+56>>>2>>>0],AE(y,y-A),le(y)})(f.Nc),_l(f.Nc,0,0,1,0,0),cf(),qc(f.Nc),K||(sE(),K=!0);try{yB(f.ge,f.Wc)}catch(A){if(A!="unwind")throw A}}else f.target!=="setimmediate"&&(E==="checkMailbox"?K&&Fi():E&&(x(`worker: received unknown command ${E}`),x(f)))}catch(A){throw $E(),A}};var V=u,K=!1;self.onunhandledrejection=p=>{throw p.reason||p},self.onmessage=u}var X,Q,z,M,F,N,G,te,B,O,U,Y=!1;function Se(){var u=pa.buffer;t.HEAP8=X=new Int8Array(u),z=new Int16Array(u),t.HEAPU8=Q=new Uint8Array(u),M=new Uint16Array(u),t.HEAP32=F=new Int32Array(u),t.HEAPU32=N=new Uint32Array(u),G=new Float32Array(u),te=new Float64Array(u),B=new BigInt64Array(u),O=new BigUint64Array(u)}function We(){Y=!0,n?S():ea._b()}function ce(u){throw x(u="Aborted("+u+")"),v=!0,u=new WebAssembly.RuntimeError(u+". Build with -sASSERTIONS for more info."),m?.(u),u}function Bt(){return{a:{f:DB,J:CB,k:wB,p:NB,l:BB,sa:MB,b:PB,ca:kB,Ja:ff,q:RB,da:If,Za:Sf,Fa:Lf,Ha:Af,_a:gf,Xa:bf,Qa:Tf,Wa:xf,oa:vf,Ga:yf,Xb:Df,Ya:Cf,Yb:wf,db:OB,Da:FB,Sb:ZB,Qb:WB,Ca:VB,M:jB,I:qB,Rb:XB,ja:rM,Tb:aM,Ta:nM,Vb:iM,Ka:oM,Ob:HM,ka:_M,Sa:qc,ab:cM,U:pM,n:mM,c:Vc,rb:IM,w:SM,L:LM,z:AM,j:gM,o:Gf,sb:bM,G:TM,T:xM,h:vM,u:yM,m:DM,i:CM,Na:wM,Oa:NM,Pa:BM,La:Wf,Ma:Kf,Pb:Vf,eb:PM,cb:OM,Y:GM,qb:FM,la:ZM,bb:kM,fb:UM,$a:WM,Wb:KM,N:MM,gb:VM,X:jM,Ub:qM,nb:aP,C:nP,ra:sP,qa:iP,pb:oP,W:HP,v:_P,mb:cP,lb:lP,kb:uP,ob:dP,jb:pP,ib:hP,hb:fP,Ua:Qf,Va:Yf,Ia:Fc,V:eE,na:tE,Ra:rE,ma:aE,Cb:T3,xa:I3,Db:b3,ya:m3,F:H3,e:XP,s:jP,x:VP,B:s3,Fb:f3,ba:h3,D:QP,za:E3,$:S3,ga:p3,Gb:d3,Hb:u3,Ba:_3,Aa:l3,Ib:c3,wa:g3,aa:$3,d:qP,A:JP,r:zP,Bb:x3,t:e3,y:i3,H:YP,E:t3,K:o3,R:L3,ia:n3,_:A3,Jb:a3,Kb:r3,g:$P,a:pa,Nb:bn,Eb:mP,ha:IP,O:SP,pa:LP,Lb:AP,ta:gP,Q:bP,yb:TP,zb:xP,ua:vP,ea:yP,P:DP,Ea:CP,va:wP,Z:NP,wb:BP,Zb:MP,S:PP,Ab:kP,tb:RP,ub:GP,vb:FP,fa:ZP,xb:UP,Mb:WP}}}async function Ke(){function u(E,A){var y=ea=E.exports;E={};for(let[w,R]of Object.entries(y))typeof R=="function"?(y=lM(R),E[w]=y):E[w]=R;return ea=E,ea=(function(){var w=ea,R=ee=>ye=>ee(ye)>>>0,q=ee=>()=>ee()>>>0;return(w=Object.assign({},w)).$b=R(w.$b),w.Cc=q(w.Cc),w.Ec=R(w.Ec),w.rd=(ee=>(ye,Be)=>ee(ye,Be)>>>0)(w.rd),w.wd=R(w.wd),w.xd=q(w.xd),w.Bd=R(w.Bd),w})(),Hf.push(ea.id),nE=(E=ea).$b,sE=E.ac,t._OrtInit=E.bc,t._OrtGetLastError=E.cc,t._OrtCreateSessionOptions=E.dc,t._OrtAppendExecutionProvider=E.ec,t._OrtAddFreeDimensionOverride=E.fc,t._OrtAddSessionConfigEntry=E.gc,t._OrtReleaseSessionOptions=E.hc,t._OrtCreateSession=E.ic,t._OrtReleaseSession=E.jc,t._OrtGetInputOutputCount=E.kc,t._OrtGetInputOutputMetadata=E.lc,t._OrtFree=E.mc,t._OrtCreateTensor=E.nc,t._OrtGetTensorData=E.oc,t._OrtReleaseTensor=E.pc,t._OrtCreateRunOptions=E.qc,t._OrtAddRunConfigEntry=E.rc,t._OrtReleaseRunOptions=E.sc,t._OrtCreateBinding=E.tc,t._OrtBindInput=E.uc,t._OrtBindOutput=E.vc,t._OrtClearBoundOutputs=E.wc,t._OrtReleaseBinding=E.xc,t._OrtRunWithBinding=E.yc,t._OrtRun=E.zc,t._OrtEndProfiling=E.Ac,al=t._OrtGetWebGpuDevice=E.Bc,ji=E.Cc,fr=t._free=E.Dc,Dn=t._malloc=E.Ec,iE=t._wgpuBufferRelease=E.Fc,oE=t._wgpuCreateInstance=E.Gc,HE=E.Hc,_E=E.Ic,cE=E.Jc,lE=E.Kc,uE=E.Lc,dE=E.Pc,pE=E.Zc,hE=E._c,fE=E.$c,nl=E.bd,sl=E.cd,il=E.dd,ol=E.ed,Bs=E.fd,Hl=E.gd,EE=E.hd,_l=E.kd,$E=E.ld,mE=E.md,IE=E.nd,cl=E.od,SE=E.pd,LE=E.qd,ll=E.rd,Le=E.sd,Ms=E.td,AE=E.ud,le=E.vd,qi=E.wd,ue=E.xd,gE=E.yd,ul=E.zd,bE=E.Ad,TE=E.Bd,xE=E.Cd,dl=E.Dd,vE=E.Ed,yE=E.Fd,DE=E.Gd,CE=E.Hd,wE=E.Id,NE=E.Jd,BE=E.Kd,ME=E.Ld,PE=E.Md,kE=E.Nd,RE=E.Od,OE=E.Pd,GE=E.Qd,FE=E.Rd,ZE=E.Td,UE=E.Ud,WE=E.Vd,KE=E.Wd,VE=E.Yd,jE=E.Zd,qE=E._d,XE=E.$d,zE=E.ae,JE=E.oe,QE=E.pe,YE=E.qe,e1=E.re,t1=E.se,r1=E.te,a1=E.ue,n1=E.ve,s1=E.we,i1=E.xe,o1=E.ye,H1=E.Ye,_1=E.Ze,c1=E._e,l1=E.$e,d=A,ea}var p,f=Bt();return t.instantiateWasm?new Promise(E=>{t.instantiateWasm(f,(A,y)=>{E(u(A,y))})}):n?u(new WebAssembly.Instance(d,Bt()),d):(U??=t.locateFile?t.locateFile?t.locateFile("ort-wasm-simd-threaded.asyncify.wasm",c):c+"ort-wasm-simd-threaded.asyncify.wasm":new URL("ort-wasm-simd-threaded.asyncify.wasm",Wt.url).href,p=await(async function(E){var A=U;if(!l&&!k(A))try{var y=fetch(A,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(y,E)}catch(w){x(`wasm streaming compile failed: ${w}`),x("falling back to ArrayBuffer instantiation")}return(async function(w,R){try{var q=await(async function(ee){if(!l)try{var ye=await i(ee);return new Uint8Array(ye)}catch{}if(ee==U&&l)ee=new Uint8Array(l);else{if(!o)throw"both async and sync fetching of the wasm failed";ee=o(ee)}return ee})(w);return await WebAssembly.instantiate(q,R)}catch(ee){x(`failed to asynchronously prepare wasm: ${ee}`),ce(ee)}})(A,E)})(f),u(p.instance,p.module))}class Ht{name="ExitStatus";constructor(p){this.message=`Program terminated with exit(${p})`,this.status=p}}var Mt=u=>{u.terminate(),u.onmessage=()=>{}},Fe=[],ve=0,_t=null,Tr=u=>{da.length==0&&(uf(),lf(da[0]));var p=da.pop();if(!p)return 6;Cs.push(p),Na[u.Nc]=p,p.Nc=u.Nc;var f={Oc:"run",ge:u.fe,Wc:u.Wc,Nc:u.Nc};return p.postMessage(f,u.Yc),0},De=0,Re=(u,p,...f)=>{var E,A=16*f.length,y=ue(),w=qi(A),R=w>>>3;for(E of f)typeof E=="bigint"?((L(),B)[R++>>>0]=1n,(L(),B)[R++>>>0]=E):((L(),B)[R++>>>0]=0n,(L(),te)[R++>>>0]=E);return u=mE(u,0,A,w,p),le(y),u};function bn(u){if(n)return Re(0,1,u);if(h=u,!(0<De)){for(var p of Cs)Mt(p);for(p of da)Mt(p);da=[],Cs=[],Na={},v=!0}H(0,new Ht(u))}function Ds(u){if(n)return Re(1,0,u);Fc(u)}var Fc=u=>{if(h=u,n)throw Ds(u),"unwind";bn(u)},da=[],Cs=[],Hf=[],Na={},_f=u=>{var p=u.Nc;delete Na[p],da.push(u),Cs.splice(Cs.indexOf(u),1),u.Nc=0,IE(p)};function cf(){Hf.forEach(u=>u())}var lf=u=>new Promise(p=>{u.onmessage=A=>{var y=A.data;if(A=y.Oc,y.Vc&&y.Vc!=ji()){var w=Na[y.Vc];w?w.postMessage(y,y.Yc):x(`Internal error! Worker sent a message "${A}" to target pthread ${y.Vc}, but that thread no longer exists!`)}else A==="checkMailbox"?Fi():A==="spawnThread"?Tr(y):A==="cleanupThread"?Pt(()=>{_f(Na[y.he])}):A==="loaded"?(u.loaded=!0,p(u)):y.target==="setimmediate"?u.postMessage(y):A==="uncaughtException"?u.onerror(y.error):A==="callHandler"?t[y.be](...y.args):A&&x(`worker sent an unknown command ${A}`)},u.onerror=A=>{throw x(`worker sent an error! ${A.filename}:${A.lineno}: ${A.message}`),A};var f,E=[];for(f of[])t.propertyIsEnumerable(f)&&E.push(f);u.postMessage({Oc:"load",ce:E,ie:pa,je:d})});function uf(){var u=new Worker((()=>{let p=URL;return Wt.url>"file:"&&Wt.url<"file;"?new p("ort.webgpu.bundle.min.mjs",Wt.url):new URL(Wt.url)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});da.push(u)}var pa,yB=(u,p)=>{De=0,u=dl(u,p),0<De?h=u:cl(u)},Oi=[],Gi=0,Lt=u=>-9007199254740992>u||9007199254740992<u?NaN:Number(u);function DB(u){var p=new Zc(u>>>=0);return(L(),X)[p.Qc+12>>>0]==0&&(df(p,!0),Gi--),pf(p,!1),Oi.push(p),TE(u)}var Tn=0,CB=()=>{Le(0,0);var u=Oi.pop();gE(u.Xc),Tn=0};function df(u,p){p=p?1:0,(L(),X)[u.Qc+12>>>0]=p}function pf(u,p){p=p?1:0,(L(),X)[u.Qc+13>>>0]=p}class Zc{constructor(p){this.Xc=p,this.Qc=p-24}}var Uc=u=>{var p=Tn;if(!p)return Ms(0),0;var f=new Zc(p);(L(),N)[f.Qc+16>>>2>>>0]=p;var E=(L(),N)[f.Qc+4>>>2>>>0];if(!E)return Ms(0),p;for(var A of u){if(A===0||A===E)break;if(bE(A,E,f.Qc+16))return Ms(A),p}return Ms(E),p};function wB(){return Uc([])}function NB(u){return Uc([u>>>0])}function BB(u,p,f,E){return Uc([u>>>0,p>>>0,f>>>0,E>>>0])}var MB=()=>{var u=Oi.pop();u||ce("no exception to throw");var p=u.Xc;throw(L(),X)[u.Qc+13>>>0]==0&&(Oi.push(u),pf(u,!0),df(u,!1),Gi++),ul(p),Tn=p};function PB(u,p,f){var E=new Zc(u>>>=0);throw p>>>=0,f>>>=0,(L(),N)[E.Qc+16>>>2>>>0]=0,(L(),N)[E.Qc+4>>>2>>>0]=p,(L(),N)[E.Qc+8>>>2>>>0]=f,ul(u),Gi++,Tn=u}var kB=()=>Gi;function hf(u,p,f,E){return n?Re(2,1,u,p,f,E):ff(u,p,f,E)}function ff(u,p,f,E){if(u>>>=0,p>>>=0,f>>>=0,E>>>=0,!globalThis.SharedArrayBuffer)return 6;var A=[];return n&&A.length===0?hf(u,p,f,E):(u={fe:f,Nc:u,Wc:E,Yc:A},n?(u.Oc="spawnThread",postMessage(u,A),0):Tr(u))}function RB(u){throw Tn||=u>>>0,Tn}var Ef=globalThis.TextDecoder&&new TextDecoder,$f=(u,p,f,E)=>{if(f=p+f,E)return f;for(;u[p]&&!(p>=f);)++p;return p},mf=(u,p=0,f,E)=>{if(16<(f=$f(u,p>>>=0,f,E))-p&&u.buffer&&Ef)return Ef.decode(u.buffer instanceof ArrayBuffer?u.subarray(p,f):u.slice(p,f));for(E="";p<f;){var A=u[p++];if(128&A){var y=63&u[p++];if((224&A)==192)E+=String.fromCharCode((31&A)<<6|y);else{var w=63&u[p++];65536>(A=(240&A)==224?(15&A)<<12|y<<6|w:(7&A)<<18|y<<12|w<<6|63&u[p++])?E+=String.fromCharCode(A):(A-=65536,E+=String.fromCharCode(55296|A>>10,56320|1023&A))}}else E+=String.fromCharCode(A)}return E},xn=(u,p,f)=>(u>>>=0)?mf((L(),Q),u,p,f):"";function If(u,p,f){return n?Re(3,1,u,p,f):0}function Sf(u,p){if(n)return Re(4,1,u,p)}function Lf(u,p){if(n)return Re(5,1,u,p)}function Af(u,p,f){if(n)return Re(6,1,u,p,f)}function gf(u,p,f){return n?Re(7,1,u,p,f):0}function bf(u,p){if(n)return Re(8,1,u,p)}function Tf(u,p,f){if(n)return Re(9,1,u,p,f)}function xf(u,p,f,E){if(n)return Re(10,1,u,p,f,E)}function vf(u,p,f,E){if(n)return Re(11,1,u,p,f,E)}function yf(u,p,f,E){if(n)return Re(12,1,u,p,f,E)}function Df(u){if(n)return Re(13,1,u)}function Cf(u,p){if(n)return Re(14,1,u,p)}function wf(u,p,f){if(n)return Re(15,1,u,p,f)}var OB=()=>ce(""),xr=u=>{u>>>=0;for(var p="";;){var f=(L(),Q)[u++>>>0];if(!f)return p;p+=String.fromCharCode(f)}},Wc={},Kc={},GB={},vn=class extends Error{constructor(u){super(u),this.name="BindingError"}};function Xr(u,p,f={}){return(function(E,A,y={}){var w=A.name;if(!E)throw new vn(`type "${w}" must have a positive integer typeid pointer`);if(Kc.hasOwnProperty(E)){if(y.de)return;throw new vn(`Cannot register type '${w}' twice`)}Kc[E]=A,delete GB[E],Wc.hasOwnProperty(E)&&(A=Wc[E],delete Wc[E],A.forEach(R=>R()))})(u,p,f)}var Nf=(u,p,f)=>{switch(p){case 1:return f?E=>(L(),X)[E>>>0]:E=>(L(),Q)[E>>>0];case 2:return f?E=>(L(),z)[E>>>1>>>0]:E=>(L(),M)[E>>>1>>>0];case 4:return f?E=>(L(),F)[E>>>2>>>0]:E=>(L(),N)[E>>>2>>>0];case 8:return f?E=>(L(),B)[E>>>3>>>0]:E=>(L(),O)[E>>>3>>>0];default:throw new TypeError(`invalid integer width (${p}): ${u}`)}};function FB(u,p,f,E,A){u>>>=0,f>>>=0,p=xr(p>>>0);let y=w=>w;if(E=E===0n){let w=8*f;y=R=>BigInt.asUintN(w,R),A=y(A)}Xr(u,{name:p,Mc:y,Sc:(w,R)=>(typeof R=="number"&&(R=BigInt(R)),R),Rc:Nf(p,f,!E),Tc:null})}function ZB(u,p,f,E){Xr(u>>>=0,{name:p=xr(p>>>0),Mc:function(A){return!!A},Sc:function(A,y){return y?f:E},Rc:function(A){return this.Mc((L(),Q)[A>>>0])},Tc:null})}var Bf=[],Ba=[0,1,,1,null,1,!0,1,!1,1];function Vc(u){9<(u>>>=0)&&--Ba[u+1]==0&&(Ba[u]=void 0,Bf.push(u))}var ir=u=>{if(!u)throw new vn(`Cannot use deleted val. handle = ${u}`);return Ba[u]},hr=u=>{switch(u){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let p=Bf.pop()||Ba.length;return Ba[p]=u,Ba[p+1]=1,p}};function jc(u){return this.Mc((L(),N)[u>>>2>>>0])}var UB={name:"emscripten::val",Mc:u=>{var p=ir(u);return Vc(u),p},Sc:(u,p)=>hr(p),Rc:jc,Tc:null};function WB(u){return Xr(u>>>0,UB)}var KB=(u,p)=>{switch(p){case 4:return function(f){return this.Mc((L(),G)[f>>>2>>>0])};case 8:return function(f){return this.Mc((L(),te)[f>>>3>>>0])};default:throw new TypeError(`invalid float width (${p}): ${u}`)}};function VB(u,p,f){f>>>=0,Xr(u>>>=0,{name:p=xr(p>>>0),Mc:E=>E,Sc:(E,A)=>A,Rc:KB(p,f),Tc:null})}function jB(u,p,f,E,A){u>>>=0,f>>>=0,p=xr(p>>>0);let y=R=>R;if(E===0){var w=32-8*f;y=R=>R<<w>>>w,A=y(A)}Xr(u,{name:p,Mc:y,Sc:(R,q)=>q,Rc:Nf(p,f,E!==0),Tc:null})}function qB(u,p,f){function E(y){var w=(L(),N)[y>>>2>>>0];return y=(L(),N)[y+4>>>2>>>0],new A((L(),X).buffer,y,w)}var A=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][p];Xr(u>>>=0,{name:f=xr(f>>>0),Mc:E,Rc:E},{de:!0})}var zr=(u,p,f)=>{var E=(L(),Q);if(p>>>=0,0<f){var A=p;f=p+f-1;for(var y=0;y<u.length;++y){var w=u.codePointAt(y);if(127>=w){if(p>=f)break;E[p++>>>0]=w}else if(2047>=w){if(p+1>=f)break;E[p++>>>0]=192|w>>6,E[p++>>>0]=128|63&w}else if(65535>=w){if(p+2>=f)break;E[p++>>>0]=224|w>>12,E[p++>>>0]=128|w>>6&63,E[p++>>>0]=128|63&w}else{if(p+3>=f)break;E[p++>>>0]=240|w>>18,E[p++>>>0]=128|w>>12&63,E[p++>>>0]=128|w>>6&63,E[p++>>>0]=128|63&w,y++}}E[p>>>0]=0,u=p-A}else u=0;return u},Jr=u=>{for(var p=0,f=0;f<u.length;++f){var E=u.charCodeAt(f);127>=E?p++:2047>=E?p+=2:55296<=E&&57343>=E?(p+=4,++f):p+=3}return p};function XB(u,p){Xr(u>>>=0,{name:p=xr(p>>>0),Mc(f){var E=(L(),N)[f>>>2>>>0];return E=xn(f+4,E,!0),fr(f),E},Sc(f,E){E instanceof ArrayBuffer&&(E=new Uint8Array(E));var A=typeof E=="string";if(!(A||ArrayBuffer.isView(E)&&E.BYTES_PER_ELEMENT==1))throw new vn("Cannot pass non-string to std::string");var y=A?Jr(E):E.length,w=Dn(4+y+1),R=w+4;return(L(),N)[w>>>2>>>0]=y,A?zr(E,R,y+1):(L(),Q).set(E,R>>>0),f!==null&&f.push(fr,w),w},Rc:jc,Tc(f){fr(f)}})}var Mf=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,zB=(u,p,f)=>{if(u>>>=1,16<(p=$f((L(),M),u,p/2,f))-u&&Mf)return Mf.decode((L(),M).slice(u,p));for(f="";u<p;++u){var E=(L(),M)[u>>>0];f+=String.fromCharCode(E)}return f},JB=(u,p,f)=>{if(f??=2147483647,2>f)return 0;var E=p;f=(f-=2)<2*u.length?f/2:u.length;for(var A=0;A<f;++A){var y=u.charCodeAt(A);(L(),z)[p>>>1>>>0]=y,p+=2}return(L(),z)[p>>>1>>>0]=0,p-E},QB=u=>2*u.length,YB=(u,p,f)=>{var E="";u>>>=2;for(var A=0;!(A>=p/4);A++){var y=(L(),N)[u+A>>>0];if(!y&&!f)break;E+=String.fromCodePoint(y)}return E},eM=(u,p,f)=>{if(p>>>=0,f??=2147483647,4>f)return 0;var E=p;f=E+f-4;for(var A=0;A<u.length;++A){var y=u.codePointAt(A);if(65535<y&&A++,(L(),F)[p>>>2>>>0]=y,(p+=4)+4>f)break}return(L(),F)[p>>>2>>>0]=0,p-E},tM=u=>{for(var p=0,f=0;f<u.length;++f)65535<u.codePointAt(f)&&f++,p+=4;return p};function rM(u,p,f){if(u>>>=0,p>>>=0,f=xr(f>>>=0),p===2)var E=zB,A=JB,y=QB;else E=YB,A=eM,y=tM;Xr(u,{name:f,Mc:w=>{var R=(L(),N)[w>>>2>>>0];return R=E(w+4,R*p,!0),fr(w),R},Sc:(w,R)=>{if(typeof R!="string")throw new vn(`Cannot pass non-string to C++ string type ${f}`);var q=y(R),ee=Dn(4+q+p);return(L(),N)[ee>>>2>>>0]=q/p,A(R,ee+4,q+p),w!==null&&w.push(fr,ee),ee},Rc:jc,Tc(w){fr(w)}})}function aM(u,p){Xr(u>>>=0,{ee:!0,name:p=xr(p>>>0),Mc:()=>{},Sc:()=>{}})}function nM(u){_l(u>>>0,!a,1,!r,131072,!1),cf()}var Pt=u=>{if(!v)try{if(u(),!(0<De))try{n?ji()&&cl(h):Fc(h)}catch(p){p instanceof Ht||p=="unwind"||H(0,p)}}catch(p){p instanceof Ht||p=="unwind"||H(0,p)}},sM=!Atomics.waitAsync||globalThis.navigator?.userAgent&&91>Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function qc(u){u>>>=0,sM||(Atomics.waitAsync((L(),F),u>>>2,u).value.then(Fi),u+=128,Atomics.store((L(),F),u>>>2,1))}var Fi=()=>Pt(()=>{var u=ji();u&&(qc(u),LE())});function iM(u,p){(u>>>=0)==p>>>0?setTimeout(Fi):n?postMessage({Vc:u,Oc:"checkMailbox"}):(u=Na[u])&&u.postMessage({Oc:"checkMailbox"})}var Xc=[];function oM(u,p,f,E,A){for(p>>>=0,A>>>=0,Xc.length=0,f=A>>>3,E=A+E>>>3;f<E;){var y;y=(L(),B)[f++>>>0]?(L(),B)[f++>>>0]:(L(),te)[f++>>>0],Xc.push(y)}return(p?pl[p]:KP[u])(...Xc)}var HM=()=>{De=0};function _M(u){u>>>=0,n?postMessage({Oc:"cleanupThread",he:u}):_f(Na[u])}function cM(u){}var Zi=u=>{try{u()}catch(p){ce(p)}};function lM(u){var p=(...f)=>{Ui.push(u);try{return u(...f)}finally{v||(Ui.pop(),vr&&ha===1&&Ui.length===0&&(ha=0,De+=1,Zi(_1),typeof Fibers<"u"&&Fibers.Be()))}};return Rf.set(u,p),p}var ha=0,vr=null,Pf=0,Ui=[],zc=new Map,kf=new Map,Rf=new Map,uM=0,Jc=null,dM=[],Of=u=>(function(p){if(!v){if(ha===0){var f=!1,E=!1;p((A=0)=>{if(!v&&(Pf=A,f=!0,E)){ha=2,Zi(()=>c1(vr)),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.resume(),A=!1;try{var y=(function(){var q=(L(),F)[vr+8>>>2>>>0];return q=kf.get(q),q=Rf.get(q),--De,q()})()}catch(q){y=q,A=!0}var w=!1;if(!vr){var R=Jc;R&&(Jc=null,(A?R.reject:R.resolve)(y),w=!0)}if(A&&!w)throw y}}),E=!0,f||(ha=1,vr=(function(){var A=Dn(65548),y=A+12;if((L(),N)[A>>>2>>>0]=y,(L(),N)[A+4>>>2>>>0]=y+65536,y=Ui[0],!zc.has(y)){var w=uM++;zc.set(y,w),kf.set(w,y)}return y=zc.get(y),(L(),F)[A+8>>>2>>>0]=y,A})(),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.pause(),Zi(()=>H1(vr)))}else ha===2?(ha=0,Zi(l1),fr(vr),vr=null,dM.forEach(Pt)):ce(`invalid state: ${ha}`);return Pf}})(p=>{u().then(p)});function pM(u){return u>>>=0,Of(async()=>{var p=await ir(u);return hr(p)})}var Qc=[],hM=u=>{var p=Qc.length;return Qc.push(u),p},fM=(u,p)=>{for(var f=Array(u),E=0;E<u;++E){var A=E,y=(L(),N)[p+4*E>>>2>>>0],w=Kc[y];if(w===void 0)throw u=`parameter ${E}`,y=nE(y),p=xr(y),fr(y),new vn(`${u} has unknown type ${p}`);f[A]=w}return f},EM=(u,p,f)=>{var E=[];return u=u(E,f),E.length&&((L(),N)[p>>>2>>>0]=hr(E)),u},$M={},Wi=u=>{var p=$M[u];return p===void 0?xr(u):p};function mM(u,p,f){var[E,...A]=fM(u,p>>>0);p=E.Sc.bind(E);var y=A.map(q=>q.Rc.bind(q));u--;var w={toValue:ir};switch(u=y.map((q,ee)=>{var ye=`argFromPtr${ee}`;return w[ye]=q,`${ye}(args${ee?"+"+8*ee:""})`}),f){case 0:var R="toValue(handle)";break;case 2:R="new (toValue(handle))";break;case 3:R="";break;case 1:w.getStringOrSymbol=Wi,R="toValue(handle)[getStringOrSymbol(methodName)]"}return R+=`(${u})`,E.ee||(w.toReturnWire=p,w.emval_returnValue=EM,R=`return emval_returnValue(toReturnWire, destructorsRef, ${R})`),R=`return function (handle, methodName, destructorsRef, args) {
10
- ${R}
11
- }`,f=new Function(Object.keys(w),R)(...Object.values(w)),R=`methodCaller<(${A.map(q=>q.name)}) => ${E.name}>`,hM(Object.defineProperty(f,"name",{value:R}))}function IM(u,p){return p>>>=0,(u=ir(u>>>0))==ir(p)}function SM(u){return(u>>>=0)?(u=Wi(u),hr(globalThis[u])):hr(globalThis)}function LM(u){return u=Wi(u>>>0),hr(t[u])}function AM(u,p){return p>>>=0,u=ir(u>>>0),p=ir(p),hr(u[p])}function gM(u){9<(u>>>=0)&&(Ba[u+1]+=1)}function Gf(u,p,f,E,A){return Qc[u>>>0](p>>>0,f>>>0,E>>>0,A>>>0)}function bM(u,p,f,E,A){return Gf(u>>>0,p>>>0,f>>>0,E>>>0,A>>>0)}function TM(){return hr([])}function xM(u){u=ir(u>>>0);for(var p=Array(u.length),f=0;f<u.length;f++)p[f]=u[f];return hr(p)}function vM(u){return hr(Wi(u>>>0))}function yM(){return hr({})}function DM(u){for(var p=ir(u>>>=0);p.length;){var f=p.pop();p.pop()(f)}Vc(u)}function CM(u,p,f){p>>>=0,f>>>=0,u=ir(u>>>0),p=ir(p),f=ir(f),u[p]=f}function wM(u,p){u=Lt(u),p>>>=0,u=new Date(1e3*u),(L(),F)[p>>>2>>>0]=u.getUTCSeconds(),(L(),F)[p+4>>>2>>>0]=u.getUTCMinutes(),(L(),F)[p+8>>>2>>>0]=u.getUTCHours(),(L(),F)[p+12>>>2>>>0]=u.getUTCDate(),(L(),F)[p+16>>>2>>>0]=u.getUTCMonth(),(L(),F)[p+20>>>2>>>0]=u.getUTCFullYear()-1900,(L(),F)[p+24>>>2>>>0]=u.getUTCDay(),u=(u.getTime()-Date.UTC(u.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,(L(),F)[p+28>>>2>>>0]=u}var Ff=u=>u%4==0&&(u%100!=0||u%400==0),Zf=[0,31,60,91,121,152,182,213,244,274,305,335],Uf=[0,31,59,90,120,151,181,212,243,273,304,334];function NM(u,p){u=Lt(u),p>>>=0,u=new Date(1e3*u),(L(),F)[p>>>2>>>0]=u.getSeconds(),(L(),F)[p+4>>>2>>>0]=u.getMinutes(),(L(),F)[p+8>>>2>>>0]=u.getHours(),(L(),F)[p+12>>>2>>>0]=u.getDate(),(L(),F)[p+16>>>2>>>0]=u.getMonth(),(L(),F)[p+20>>>2>>>0]=u.getFullYear()-1900,(L(),F)[p+24>>>2>>>0]=u.getDay();var f=(Ff(u.getFullYear())?Zf:Uf)[u.getMonth()]+u.getDate()-1|0;(L(),F)[p+28>>>2>>>0]=f,(L(),F)[p+36>>>2>>>0]=-60*u.getTimezoneOffset(),f=new Date(u.getFullYear(),6,1).getTimezoneOffset();var E=new Date(u.getFullYear(),0,1).getTimezoneOffset();u=0|(f!=E&&u.getTimezoneOffset()==Math.min(E,f)),(L(),F)[p+32>>>2>>>0]=u}function BM(u){u>>>=0;var p=new Date((L(),F)[u+20>>>2>>>0]+1900,(L(),F)[u+16>>>2>>>0],(L(),F)[u+12>>>2>>>0],(L(),F)[u+8>>>2>>>0],(L(),F)[u+4>>>2>>>0],(L(),F)[u>>>2>>>0],0),f=(L(),F)[u+32>>>2>>>0],E=p.getTimezoneOffset(),A=new Date(p.getFullYear(),6,1).getTimezoneOffset(),y=new Date(p.getFullYear(),0,1).getTimezoneOffset(),w=Math.min(y,A);return 0>f?(L(),F)[u+32>>>2>>>0]=+(A!=y&&w==E):0<f!=(w==E)&&(A=Math.max(y,A),p.setTime(p.getTime()+6e4*((0<f?w:A)-E))),(L(),F)[u+24>>>2>>>0]=p.getDay(),f=(Ff(p.getFullYear())?Zf:Uf)[p.getMonth()]+p.getDate()-1|0,(L(),F)[u+28>>>2>>>0]=f,(L(),F)[u>>>2>>>0]=p.getSeconds(),(L(),F)[u+4>>>2>>>0]=p.getMinutes(),(L(),F)[u+8>>>2>>>0]=p.getHours(),(L(),F)[u+12>>>2>>>0]=p.getDate(),(L(),F)[u+16>>>2>>>0]=p.getMonth(),(L(),F)[u+20>>>2>>>0]=p.getYear(),u=p.getTime(),BigInt(isNaN(u)?-1:u/1e3)}function Wf(u,p,f,E,A,y,w){return n?Re(16,1,u,p,f,E,A,y,w):-52}function Kf(u,p,f,E,A,y){if(n)return Re(17,1,u,p,f,E,A,y)}var ws={},MM=()=>performance.timeOrigin+performance.now();function Vf(u,p){if(n)return Re(18,1,u,p);if(ws[u]&&(clearTimeout(ws[u].id),delete ws[u]),!p)return 0;var f=setTimeout(()=>{delete ws[u],Pt(()=>SE(u,performance.timeOrigin+performance.now()))},p);return ws[u]={id:f,Ae:p},0}function PM(u,p,f,E){u>>>=0,p>>>=0,f>>>=0,E>>>=0;var A=new Date().getFullYear(),y=new Date(A,0,1).getTimezoneOffset();A=new Date(A,6,1).getTimezoneOffset();var w=Math.max(y,A);(L(),N)[u>>>2>>>0]=60*w,(L(),F)[p>>>2>>>0]=+(y!=A),u=(p=R=>{var q=Math.abs(R);return`UTC${0<=R?"-":"+"}${String(Math.floor(q/60)).padStart(2,"0")}${String(q%60).padStart(2,"0")}`})(y),p=p(A),A<y?(zr(u,f,17),zr(p,E,17)):(zr(u,E,17),zr(p,f,17))}var kM=()=>Date.now(),RM=1;function OM(u,p,f){if(f>>>=0,!(0<=u&&3>=u))return 28;if(u===0)u=Date.now();else{if(!RM)return 52;u=performance.timeOrigin+performance.now()}return u=Math.round(1e6*u),(L(),B)[f>>>3>>>0]=BigInt(u),0}var Yc=[],jf=(u,p)=>{Yc.length=0;for(var f;f=(L(),Q)[u++>>>0];){var E=f!=105;p+=(E&=f!=112)&&p%8?4:0,Yc.push(f==112?(L(),N)[p>>>2>>>0]:f==106?(L(),B)[p>>>3>>>0]:f==105?(L(),F)[p>>>2>>>0]:(L(),te)[p>>>3>>>0]),p+=E?8:4}return Yc};function GM(u,p,f){return u>>>=0,p=jf(p>>>0,f>>>0),pl[u](...p)}function FM(u,p,f){return u>>>=0,p=jf(p>>>0,f>>>0),pl[u](...p)}var ZM=()=>{};function UM(u,p){return x(xn(u>>>0,p>>>0))}var WM=()=>{throw De+=1,"unwind"};function KM(){return 4294901760}var VM=()=>1,jM=()=>navigator.hardwareConcurrency;function qM(u){u>>>=0;var p=(L(),Q).length;if(u<=p||4294901760<u)return!1;for(var f=1;4>=f;f*=2){var E=p*(1+.2/f);E=Math.min(E,u+100663296);e:{E=(Math.min(4294901760,65536*Math.ceil(Math.max(u,E)/65536))-pa.buffer.byteLength+65535)/65536|0;try{pa.grow(E),Se();var A=1;break e}catch{}A=void 0}if(A)return!0}return!1}var yr=u=>{var p=Jr(u)+1,f=qi(p);return zr(u,f,p),f},el=(u,p)=>{(L(),N)[u>>>2>>>0]=p;var f=(L(),N)[u>>>2>>>0];(L(),N)[u+4>>>2>>>0]=(p-f)/4294967296},Ns=u=>(L(),N)[u>>>2>>>0]+4294967296*(L(),F)[u+4>>>2>>>0],At=[],XM=(u,p)=>{At[u>>>0]=p},Qr=[],Ki=[],yn=(u,p)=>{Ki[u]=new Promise(f=>p.finally(()=>f(u)))},oe=u=>{if(u)return At[u>>>0]},zM=(u,p)=>{for(u=(L(),N)[u>>>2>>>0];u;u=(L(),N)[u>>>2>>>0])p[(L(),F)[u+4>>>2>>>0]](u)},Vi=(u,p,f)=>{(L(),N)[u>>>2>>>0]=p,(L(),N)[u+4>>>2>>>0]=f},qf=u=>{var p=(L(),N)[u>>>2>>>0];return u=(L(),N)[u+4>>>2>>>0],xn(p,u)},Yr=u=>{var p=(L(),N)[u>>>2>>>0];return u=(L(),N)[u+4>>>2>>>0],p?xn(p,u):u===0?"":void 0},JM=u=>{var p=Yr(u+4),f=(f=(L(),N)[u+12>>>2>>>0])?oe(f):"auto";if(u+=16){var E=oe((L(),N)[u+4>>>2>>>0]),A=(L(),N)[u+16>>>2>>>0],y=(L(),N)[u+20>>>2>>>0];if(A){for(var w={},R=0;R<A;++R){var q=y+24*R;w[qf(q+4)]=(L(),te)[q+16>>>3>>>0]}A=w}else A=void 0;u={module:E,constants:A,entryPoint:Yr(u+8)}}else u=void 0;return{label:p,layout:f,compute:u}},Xf=(u,p)=>{function f(E,A){E=u[E],(L(),N)[p+A>>>2>>>0]=E}f("maxTextureDimension1D",4),f("maxTextureDimension2D",8),f("maxTextureDimension3D",12),f("maxTextureArrayLayers",16),f("maxBindGroups",20),f("maxBindGroupsPlusVertexBuffers",24),f("maxBindingsPerBindGroup",28),f("maxDynamicUniformBuffersPerPipelineLayout",32),f("maxDynamicStorageBuffersPerPipelineLayout",36),f("maxSampledTexturesPerShaderStage",40),f("maxSamplersPerShaderStage",44),f("maxStorageBuffersPerShaderStage",48),f("maxStorageTexturesPerShaderStage",52),f("maxUniformBuffersPerShaderStage",56),f("minUniformBufferOffsetAlignment",80),f("minStorageBufferOffsetAlignment",84),el(p+64,u.maxUniformBufferBindingSize),el(p+72,u.maxStorageBufferBindingSize),f("maxVertexBuffers",88),el(p+96,u.maxBufferSize),f("maxVertexAttributes",104),f("maxVertexBufferArrayStride",108),f("maxInterStageShaderVariables",112),f("maxColorAttachments",116),f("maxColorAttachmentBytesPerSample",120),f("maxComputeWorkgroupStorageSize",124),f("maxComputeInvocationsPerWorkgroup",128),f("maxComputeWorkgroupSizeX",132),f("maxComputeWorkgroupSizeY",136),f("maxComputeWorkgroupSizeZ",140),f("maxComputeWorkgroupsPerDimension",144),u.ze!==void 0&&f("maxImmediateSize",148)},QM=[,"validation","out-of-memory","internal"],YM=[,"compatibility","core"],zf={1:"core-features-and-limits",2:"depth-clip-control",3:"depth32float-stencil8",4:"texture-compression-bc",5:"texture-compression-bc-sliced-3d",6:"texture-compression-etc2",7:"texture-compression-astc",8:"texture-compression-astc-sliced-3d",9:"timestamp-query",10:"indirect-first-instance",11:"shader-f16",12:"rg11b10ufloat-renderable",13:"bgra8unorm-storage",14:"float32-filterable",15:"float32-blendable",16:"clip-distances",17:"dual-source-blending",18:"subgroups",19:"texture-formats-tier1",20:"texture-formats-tier2",21:"primitive-index",22:"texture-component-swizzle",327692:"chromium-experimental-unorm16-texture-formats",327729:"chromium-experimental-multi-draw-indirect"},eP=[,"low-power","high-performance"],tP=[,"occlusion","timestamp"],rP={undefined:1,unknown:1,destroyed:2};function aP(u,p,f,E,A,y){p=Lt(p),f=Lt(f),E>>>=0,A>>>=0,y>>>=0;var w=oe(u>>>0);if(u={},y){var R=(L(),N)[y+12>>>2>>>0];if(R){var q=(L(),N)[y+16>>>2>>>0];u.requiredFeatures=Array.from((L(),N).subarray(q>>>2>>>0,q+4*R>>>2>>>0),_e=>zf[_e])}var ee=(L(),N)[y+20>>>2>>>0];if(ee){let _e=function(kt,ft,Ma=!1){ft=ee+ft,(ft=(L(),N)[ft>>>2>>>0])==4294967295||Ma&&ft==0||(Ze[kt]=ft)},ht=function(kt,ft){ft=ee+ft;var Ma=(L(),N)[ft>>>2>>>0],v3=(L(),N)[ft+4>>>2>>>0];Ma==4294967295&&v3==4294967295||(Ze[kt]=Ns(ft))};var ye=_e,Be=ht,Ze={};_e("maxTextureDimension1D",4),_e("maxTextureDimension2D",8),_e("maxTextureDimension3D",12),_e("maxTextureArrayLayers",16),_e("maxBindGroups",20),_e("maxBindGroupsPlusVertexBuffers",24),_e("maxDynamicUniformBuffersPerPipelineLayout",32),_e("maxDynamicStorageBuffersPerPipelineLayout",36),_e("maxSampledTexturesPerShaderStage",40),_e("maxSamplersPerShaderStage",44),_e("maxStorageBuffersPerShaderStage",48),_e("maxStorageTexturesPerShaderStage",52),_e("maxUniformBuffersPerShaderStage",56),_e("minUniformBufferOffsetAlignment",80),_e("minStorageBufferOffsetAlignment",84),ht("maxUniformBufferBindingSize",64),ht("maxStorageBufferBindingSize",72),_e("maxVertexBuffers",88),ht("maxBufferSize",96),_e("maxVertexAttributes",104),_e("maxVertexBufferArrayStride",108),_e("maxInterStageShaderVariables",112),_e("maxColorAttachments",116),_e("maxColorAttachmentBytesPerSample",120),_e("maxComputeWorkgroupStorageSize",124),_e("maxComputeInvocationsPerWorkgroup",128),_e("maxComputeWorkgroupSizeX",132),_e("maxComputeWorkgroupSizeY",136),_e("maxComputeWorkgroupSizeZ",140),_e("maxComputeWorkgroupsPerDimension",144),_e("maxImmediateSize",148,!0),u.requiredLimits=Ze}(R=(L(),N)[y+24>>>2>>>0])&&(R={label:Yr(R+4)},u.defaultQueue=R),u.label=Yr(y+4)}De+=1,yn(p,w.requestDevice(u).then(_e=>{--De,Pt(()=>{At[A>>>0]=_e.queue,At[E>>>0]=_e,De+=1,yn(f,_e.lost.then(ht=>{Pt(()=>{_e.onuncapturederror=()=>{};var kt=ue(),ft=yr(ht.message);sl(f,rP[ht.reason],ft),le(kt)}),--De})),_e.onuncapturederror=ht=>{var kt=5;ht.error instanceof GPUValidationError?kt=2:ht.error instanceof GPUOutOfMemoryError?kt=3:ht.error instanceof GPUInternalError&&(kt=4);var ft=ue();ht=yr(ht.error.message),EE(E,kt,ht),le(ft)},"adapterInfo"in _e||(_e.adapterInfo=w.info),Hl(p,1,E,0)})},_e=>{--De,Pt(()=>{var ht=ue(),kt=yr(_e.message);Hl(p,3,E,kt),f&&sl(f,4,kt),le(ht)})}))}function nP(u){var p=oe(u>>>=0),f=Qr[u];if(f){for(var E=0;E<f.length;++E)f[E]();delete Qr[u]}p.destroy()}function sP(u,p,f){f>>>=0;var E=oe(u>>>=0);f==4294967295&&(f=void 0);try{var A=E.getMappedRange(p>>>0,f)}catch{return 0}var y=ll(16,A.byteLength);return(L(),Q).set(new Uint8Array(A),y>>>0),Qr[u].push(()=>fr(y)),y}function iP(u,p,f){f>>>=0;var E=oe(u>>>=0);f==4294967295&&(f=void 0);try{var A=E.getMappedRange(p>>>0,f)}catch{return 0}var y=ll(16,A.byteLength);return(L(),Q).fill(0,y,A.byteLength),Qr[u].push(()=>{new Uint8Array(A).set((L(),Q).subarray(y>>>0,y+A.byteLength>>>0)),fr(y)}),y}function oP(u,p,f,E,A){u>>>=0,p=Lt(p),f=Lt(f),A>>>=0;var y=oe(u);Qr[u]=[],A==4294967295&&(A=void 0),De+=1,yn(p,y.mapAsync(f,E>>>0,A).then(()=>{--De,Pt(()=>{il(p,1,0)})},w=>{--De,Pt(()=>{ue();var R=yr(w.message);il(p,w.name==="AbortError"?4:w.name==="OperationError"?3:0,R),delete Qr[u]})}))}function HP(u){var p=oe(u>>>=0),f=Qr[u];if(f){for(var E=0;E<f.length;++E)f[E]();delete Qr[u],p.unmap()}}function _P(u){delete At[u>>>0]}function cP(u,p,f){u>>>=0,p>>>=0,f>>>=0;var E=!!(L(),N)[p+32>>>2>>>0];p={label:Yr(p+4),usage:(L(),N)[p+16>>>2>>>0],size:Ns(p+24),mappedAtCreation:E},u=oe(u);try{var A=u.createBuffer(p)}catch{return!1}return At[f>>>0]=A,E&&(Qr[f]=[]),!0}function lP(u,p,f,E){u>>>=0,p=Lt(p),E>>>=0,f=JM(f>>>0),u=oe(u),De+=1,yn(p,u.createComputePipelineAsync(f).then(A=>{--De,Pt(()=>{At[E>>>0]=A,nl(p,1,E,0)})},A=>{--De,Pt(()=>{var y=ue(),w=yr(A.message);nl(p,A.reason==="validation"?3:A.reason==="internal"?4:0,E,w),le(y)})}))}function uP(u,p,f){u>>>=0,p>>>=0,f>>>=0;var E=(L(),N)[p>>>2>>>0],A=(L(),F)[E+4>>>2>>>0];p={label:Yr(p+4),code:""},A===2&&(p.code=qf(E+8)),u=oe(u).createShaderModule(p),At[f>>>0]=u}var dP=u=>{(u=oe(u)).onuncapturederror=null,u.destroy()};function pP(u,p){p=Lt(p),u=oe(u>>>0),De+=1,yn(p,u.popErrorScope().then(f=>{--De,Pt(()=>{var E=5;f?f instanceof GPUValidationError?E=2:f instanceof GPUOutOfMemoryError?E=3:f instanceof GPUInternalError&&(E=4):E=1;var A=ue(),y=f?yr(f.message):0;ol(p,1,E,y),le(A)})},f=>{--De,Pt(()=>{var E=ue(),A=yr(f.message);ol(p,1,5,A),le(E)})}))}function hP(u,p,f,E){if(p=Lt(p),E>>>=0,f>>>=0){var A={featureLevel:YM[(L(),F)[f+4>>>2>>>0]],powerPreference:eP[(L(),F)[f+8>>>2>>>0]],forceFallbackAdapter:!!(L(),N)[f+12>>>2>>>0]};(u=(L(),N)[f>>>2>>>0])!==0&&(L(),A.De=!!(L(),N)[u+8>>>2>>>0])}"gpu"in navigator?(De+=1,yn(p,navigator.gpu.requestAdapter(A).then(y=>{--De,Pt(()=>{if(y)At[E>>>0]=y,Bs(p,1,E,0);else{var w=ue(),R=yr("WebGPU not available on this browser (requestAdapter returned null)");Bs(p,3,E,R),le(w)}})},y=>{--De,Pt(()=>{var w=ue(),R=yr(y.message);Bs(p,4,E,R),le(w)})}))):(A=ue(),u=yr("WebGPU not available on this browser (navigator.gpu is not available)"),Bs(p,3,E,u),le(A))}function fP(u,p,f){return u>>>=0,p>>>=0,f>>>=0,Of(async()=>{var E=[];if(f){var A=(L(),F)[f>>>2>>>0];E.length=p+1,E[p]=new Promise(R=>setTimeout(R,A,0))}else E.length=p;for(var y=0;y<p;++y){var w=Ns(u+8*y);if(!(w in Ki))return w;E[y]=Ki[w]}return E=await Promise.race(E),delete Ki[E],E})}var tl,rl={},Jf=()=>{if(!tl){var u,p={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8",_:"./this.program"};for(u in rl)rl[u]===void 0?delete p[u]:p[u]=rl[u];var f=[];for(u in p)f.push(`${u}=${p[u]}`);tl=f}return tl};function Qf(u,p){if(n)return Re(19,1,u,p);u>>>=0,p>>>=0;var f,E=0,A=0;for(f of Jf()){var y=p+E;(L(),N)[u+A>>>2>>>0]=y,E+=zr(f,y,1/0)+1,A+=4}return 0}function Yf(u,p){if(n)return Re(20,1,u,p);u>>>=0,p>>>=0;var f=Jf();for(var E of((L(),N)[u>>>2>>>0]=f.length,u=0,f))u+=Jr(E)+1;return(L(),N)[p>>>2>>>0]=u,0}function eE(u){return n?Re(21,1,u):52}function tE(u,p,f,E){return n?Re(22,1,u,p,f,E):52}function rE(u,p,f,E){return n?Re(23,1,u,p,f,E):70}var EP=[null,[],[]];function aE(u,p,f,E){if(n)return Re(24,1,u,p,f,E);p>>>=0,f>>>=0,E>>>=0;for(var A=0,y=0;y<f;y++){var w=(L(),N)[p>>>2>>>0],R=(L(),N)[p+4>>>2>>>0];p+=8;for(var q=0;q<R;q++){var ee=u,ye=(L(),Q)[w+q>>>0],Be=EP[ee];ye===0||ye===10?((ee===1?T:x)(mf(Be)),Be.length=0):Be.push(ye)}A+=R}return(L(),N)[E>>>2>>>0]=A,0}function $P(u){return u>>>0}function mP(u,p){return Xf(oe(u>>>0).limits,p>>>0),1}function IP(u,p){return oe(u>>>0).features.has(zf[p])}function SP(u){return BigInt(oe(u>>>0).size)}function LP(u){return BigInt(oe(u>>>0).usage)}function AP(u,p){if(u>>>=0,p>>>=0){var f=Yr(p+4);f={label:f,timestampWrites:p=(p=(L(),N)[p+12>>>2>>>0])!==0?{querySet:oe((L(),N)[p+4>>>2>>>0]),beginningOfPassWriteIndex:(L(),N)[p+8>>>2>>>0],endOfPassWriteIndex:(L(),N)[p+12>>>2>>>0]}:void 0}}return p=oe(u),u=uE(0),f=p.beginComputePass(f),At[u>>>0]=f,u}function gP(u,p,f,E){f=Lt(f),(E=Lt(E))==-1&&(E=void 0),(u=oe(u>>>0)).clearBuffer(oe(p>>>0),f,E)}function bP(u,p,f,E,A,y){f=Lt(f),A=Lt(A),y=Lt(y),oe(u>>>0).copyBufferToBuffer(oe(p>>>0),f,oe(E>>>0),A,y)}function TP(u){var p=oe(u>>>0);return u=cE(0),p=p.finish(),At[u>>>0]=p,u}function xP(u,p,f,E,A,y){y=Lt(y),oe(u>>>0).resolveQuerySet(oe(p>>>0),f,E,oe(A>>>0),y)}function vP(u,p,f,E){oe(u>>>0).dispatchWorkgroups(p,f,E)}function yP(u,p,f){f=Lt(f),oe(u>>>0).dispatchWorkgroupsIndirect(oe(p>>>0),f)}function DP(u){oe(u>>>0).end()}function CP(u,p,f,E,A){E>>>=0,A>>>=0,u=oe(u>>>0),f=oe(f>>>0),E==0?u.setBindGroup(p,f):u.setBindGroup(p,f,(L(),N),A>>>2,E)}function wP(u,p){oe(u>>>0).setPipeline(oe(p>>>0))}function NP(u,p,f){oe(u>>>0).Ce(oe(p>>>0),f)}function BP(u,p){var f=oe(u>>>0);return u=_E(0),p=f.getBindGroupLayout(p),At[u>>>0]=p,u}function MP(u,p){function f(A){var y=(L(),N)[A+8>>>2>>>0],w=(L(),N)[A+32>>>2>>>0],R=(L(),N)[A+36>>>2>>>0],q=0;return zM(A,{327681:ee=>{q=(L(),N)[ee+8>>>2>>>0]}}),y?((w=Ns(A+24))==-1&&(w=void 0),y={buffer:oe(y),offset:Ns(A+16),size:w}):y=oe(w||R||q),{binding:(L(),N)[A+4>>>2>>>0],resource:y}}u>>>=0,p={label:Yr(4+(p>>>=0)),layout:oe((L(),N)[p+12>>>2>>>0]),entries:(function(A,y){for(var w=[],R=0;R<A;++R)w.push(f(y+40*R));return w})((L(),N)[p+16>>>2>>>0],(L(),N)[p+20>>>2>>>0])},u=oe(u);var E=HE(0);return XM(E,u.createBindGroup(p)),E}function PP(u,p){var f;return u>>>=0,(p>>>=0)&&(f={label:Yr(p+4)}),p=oe(u),u=lE(0),f=p.createCommandEncoder(f),At[u>>>0]=f,u}function kP(u,p){u>>>=0,p>>>=0,p={type:tP[(L(),F)[p+12>>>2>>>0]],count:(L(),N)[p+16>>>2>>>0]};var f=oe(u);return u=dE(0),p=f.createQuerySet(p),At[u>>>0]=p,u}function RP(u,p){u=oe(u>>>0).adapterInfo,p>>>=0,(L(),N)[p+52>>>2>>>0]=u.subgroupMinSize,(L(),N)[p+56>>>2>>>0]=u.subgroupMaxSize;var f=u.vendor+u.architecture+u.device+u.description,E=Jr(f)+1,A=Dn(E);return A&&zr(f,A,E),f=A,E=Jr(u.vendor),Vi(p+4,f,E),f+=E,E=Jr(u.architecture),Vi(p+12,f,E),f+=E,E=Jr(u.device),Vi(p+20,f,E),Vi(p+28,f+E,Jr(u.description)),(L(),F)[p+36>>>2>>>0]=2,u=u.isFallbackAdapter?3:4,(L(),F)[p+40>>>2>>>0]=u,(L(),N)[p+44>>>2>>>0]=0,(L(),N)[p+48>>>2>>>0]=0,1}var OP={"core-features-and-limits":1,"depth-clip-control":2,"depth32float-stencil8":3,"texture-compression-bc":4,"texture-compression-bc-sliced-3d":5,"texture-compression-etc2":6,"texture-compression-astc":7,"texture-compression-astc-sliced-3d":8,"timestamp-query":9,"indirect-first-instance":10,"shader-f16":11,"rg11b10ufloat-renderable":12,"bgra8unorm-storage":13,"float32-filterable":14,"float32-blendable":15,"clip-distances":16,"dual-source-blending":17,subgroups:18,"texture-formats-tier1":19,"texture-formats-tier2":20,"primitive-index":21,"texture-component-swizzle":22,"chromium-experimental-unorm16-texture-formats":327692,"chromium-experimental-multi-draw-indirect":327729};function GP(u,p){p>>>=0;var f=oe(u>>>0);u=Dn(4*f.features.size);var E=0,A=0;for(let y of f.features)0<=(f=OP[y])&&((L(),F)[u+E>>>2>>>0]=f,E+=4,A++);(L(),N)[p+4>>>2>>>0]=u,(L(),N)[p>>>2>>>0]=A}function FP(u,p){return Xf(oe(u>>>0).limits,p>>>0),1}function ZP(u,p){oe(u>>>0).pushErrorScope(QM[p])}function UP(u,p,f){p>>>=0,f>>>=0,u=oe(u>>>0),p=Array.from((L(),F).subarray(f>>>2>>>0,f+4*p>>>2>>>0),E=>oe(E)),u.submit(p)}function WP(u,p,f,E,A){f=Lt(f),E>>>=0,A>>>=0,u=oe(u>>>0),p=oe(p>>>0),E=(L(),Q).subarray(E>>>0,E+A>>>0),u.writeBuffer(p,f,E,0,A)}n||(function(){for(var u=t.numThreads-1;u--;)uf();Fe.push(async()=>{var p=(async function(){if(!n)return Promise.all(da.map(lf))})();ve++,await p,--ve==0&&_t&&(p=_t,_t=null,p())})})(),n||(pa=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),Se()),t.wasmBinary&&(l=t.wasmBinary),t.stackSave=()=>ue(),t.stackRestore=u=>le(u),t.stackAlloc=u=>qi(u),t.setValue=function(u,p,f="i8"){switch(f.endsWith("*")&&(f="*"),f){case"i1":case"i8":(L(),X)[u>>>0]=p;break;case"i16":(L(),z)[u>>>1>>>0]=p;break;case"i32":(L(),F)[u>>>2>>>0]=p;break;case"i64":(L(),B)[u>>>3>>>0]=BigInt(p);break;case"float":(L(),G)[u>>>2>>>0]=p;break;case"double":(L(),te)[u>>>3>>>0]=p;break;case"*":(L(),N)[u>>>2>>>0]=p;break;default:ce(`invalid type for setValue: ${f}`)}},t.getValue=function(u,p="i8"){switch(p.endsWith("*")&&(p="*"),p){case"i1":case"i8":return(L(),X)[u>>>0];case"i16":return(L(),z)[u>>>1>>>0];case"i32":return(L(),F)[u>>>2>>>0];case"i64":return(L(),B)[u>>>3>>>0];case"float":return(L(),G)[u>>>2>>>0];case"double":return(L(),te)[u>>>3>>>0];case"*":return(L(),N)[u>>>2>>>0];default:ce(`invalid type for getValue: ${p}`)}},t.UTF8ToString=xn,t.stringToUTF8=zr,t.lengthBytesUTF8=Jr;var nE,sE,al,ji,fr,Dn,iE,oE,HE,_E,cE,lE,uE,dE,pE,hE,fE,nl,sl,il,ol,Bs,Hl,EE,_l,$E,mE,IE,cl,SE,LE,ll,Le,Ms,AE,le,qi,ue,gE,ul,bE,TE,xE,dl,vE,yE,DE,CE,wE,NE,BE,ME,PE,kE,RE,OE,GE,FE,ZE,UE,WE,KE,VE,jE,qE,XE,zE,JE,QE,YE,e1,t1,r1,a1,n1,s1,i1,o1,H1,_1,c1,l1,ea,KP=[bn,Ds,hf,If,Sf,Lf,Af,gf,bf,Tf,xf,vf,yf,Df,Cf,wf,Wf,Kf,Vf,Qf,Yf,eE,tE,rE,aE],pl={970348:(u,p,f,E,A)=>{if(t===void 0||!t.Uc)return 1;if((u=xn(Number(u>>>0))).startsWith("./")&&(u=u.substring(2)),!(u=t.Uc.get(u)))return 2;if(p=Number(p>>>0),f=Number(f>>>0),E=Number(E>>>0),p+f>u.byteLength)return 3;try{let y=u.subarray(p,p+f);switch(A){case 0:(L(),Q).set(y,E>>>0);break;case 1:t.ad?t.ad(E,y):t.ne(E,y);break;default:return 4}return 0}catch{return 4}},971172:(u,p,f)=>{t.Sd(u,(L(),Q).subarray(p>>>0,p+f>>>0))},971236:()=>t.le(),971278:u=>{t.jd(u)},971315:()=>typeof wasmOffsetConverter<"u"};function VP(u,p,f,E){var A=ue();try{return ME(u,p,f,E)}catch(y){if(le(A),y!==y+0)throw y;Le(1,0)}}function jP(u,p,f){var E=ue();try{return wE(u,p,f)}catch(A){if(le(E),A!==A+0)throw A;Le(1,0)}}function qP(u){var p=ue();try{vE(u)}catch(f){if(le(p),f!==f+0)throw f;Le(1,0)}}function XP(u,p){var f=ue();try{return dl(u,p)}catch(E){if(le(f),E!==E+0)throw E;Le(1,0)}}function zP(u,p,f){var E=ue();try{xE(u,p,f)}catch(A){if(le(E),A!==A+0)throw A;Le(1,0)}}function JP(u,p){var f=ue();try{PE(u,p)}catch(E){if(le(f),E!==E+0)throw E;Le(1,0)}}function QP(u,p,f,E,A,y,w){var R=ue();try{return CE(u,p,f,E,A,y,w)}catch(q){if(le(R),q!==q+0)throw q;Le(1,0)}}function YP(u,p,f,E,A,y){var w=ue();try{yE(u,p,f,E,A,y)}catch(R){if(le(w),R!==R+0)throw R;Le(1,0)}}function e3(u,p,f,E){var A=ue();try{BE(u,p,f,E)}catch(y){if(le(A),y!==y+0)throw y;Le(1,0)}}function t3(u,p,f,E,A,y,w){var R=ue();try{RE(u,p,f,E,A,y,w)}catch(q){if(le(R),q!==q+0)throw q;Le(1,0)}}function r3(u,p,f,E,A,y,w){var R=ue();try{OE(u,p,f,E,A,y,w)}catch(q){if(le(R),q!==q+0)throw q;Le(1,0)}}function a3(u,p,f,E,A,y,w,R){var q=ue();try{qE(u,p,f,E,A,y,w,R)}catch(ee){if(le(q),ee!==ee+0)throw ee;Le(1,0)}}function n3(u,p,f,E,A,y,w,R,q,ee,ye,Be){var Ze=ue();try{GE(u,p,f,E,A,y,w,R,q,ee,ye,Be)}catch(_e){if(le(Ze),_e!==_e+0)throw _e;Le(1,0)}}function s3(u,p,f,E,A){var y=ue();try{return kE(u,p,f,E,A)}catch(w){if(le(y),w!==w+0)throw w;Le(1,0)}}function i3(u,p,f,E,A){var y=ue();try{DE(u,p,f,E,A)}catch(w){if(le(y),w!==w+0)throw w;Le(1,0)}}function o3(u,p,f,E,A,y,w,R){var q=ue();try{NE(u,p,f,E,A,y,w,R)}catch(ee){if(le(q),ee!==ee+0)throw ee;Le(1,0)}}function H3(u){var p=ue();try{return XE(u)}catch(f){if(le(p),f!==f+0)throw f;Le(1,0)}}function _3(u,p,f){var E=ue();try{return zE(u,p,f)}catch(A){if(le(E),A!==A+0)throw A;Le(1,0)}}function c3(u,p){var f=ue();try{return o1(u,p)}catch(E){if(le(f),E!==E+0)throw E;return Le(1,0),0n}}function l3(u){var p=ue();try{return FE(u)}catch(f){if(le(p),f!==f+0)throw f;return Le(1,0),0n}}function u3(u,p,f,E){var A=ue();try{return JE(u,p,f,E)}catch(y){if(le(A),y!==y+0)throw y;Le(1,0)}}function d3(u,p,f,E,A){var y=ue();try{return QE(u,p,f,E,A)}catch(w){if(le(y),w!==w+0)throw w;Le(1,0)}}function p3(u,p,f,E,A,y){var w=ue();try{return YE(u,p,f,E,A,y)}catch(R){if(le(w),R!==R+0)throw R;Le(1,0)}}function h3(u,p,f,E,A,y){var w=ue();try{return VE(u,p,f,E,A,y)}catch(R){if(le(w),R!==R+0)throw R;Le(1,0)}}function f3(u,p,f,E,A,y){var w=ue();try{return e1(u,p,f,E,A,y)}catch(R){if(le(w),R!==R+0)throw R;Le(1,0)}}function E3(u,p,f,E,A,y,w,R){var q=ue();try{return jE(u,p,f,E,A,y,w,R)}catch(ee){if(le(q),ee!==ee+0)throw ee;Le(1,0)}}function $3(u,p,f,E,A){var y=ue();try{return t1(u,p,f,E,A)}catch(w){if(le(y),w!==w+0)throw w;return Le(1,0),0n}}function m3(u,p,f,E){var A=ue();try{return r1(u,p,f,E)}catch(y){if(le(A),y!==y+0)throw y;Le(1,0)}}function I3(u,p,f,E){var A=ue();try{return a1(u,p,f,E)}catch(y){if(le(A),y!==y+0)throw y;Le(1,0)}}function S3(u,p,f,E,A,y,w,R,q,ee,ye,Be){var Ze=ue();try{return n1(u,p,f,E,A,y,w,R,q,ee,ye,Be)}catch(_e){if(le(Ze),_e!==_e+0)throw _e;Le(1,0)}}function L3(u,p,f,E,A,y,w,R,q,ee,ye){var Be=ue();try{s1(u,p,f,E,A,y,w,R,q,ee,ye)}catch(Ze){if(le(Be),Ze!==Ze+0)throw Ze;Le(1,0)}}function A3(u,p,f,E,A,y,w,R,q,ee,ye,Be,Ze,_e,ht,kt){var ft=ue();try{i1(u,p,f,E,A,y,w,R,q,ee,ye,Be,Ze,_e,ht,kt)}catch(Ma){if(le(ft),Ma!==Ma+0)throw Ma;Le(1,0)}}function g3(u,p,f){var E=ue();try{return UE(u,p,f)}catch(A){if(le(E),A!==A+0)throw A;return Le(1,0),0n}}function b3(u,p,f){var E=ue();try{return ZE(u,p,f)}catch(A){if(le(E),A!==A+0)throw A;Le(1,0)}}function T3(u,p,f){var E=ue();try{return WE(u,p,f)}catch(A){if(le(E),A!==A+0)throw A;Le(1,0)}}function x3(u,p,f,E){var A=ue();try{KE(u,p,f,E)}catch(y){if(le(A),y!==y+0)throw y;Le(1,0)}}function Xi(){if(0<ve)_t=Xi;else if(n)$?.(t),We();else{for(var u=Fe;0<u.length;)u.shift()(t);0<ve?_t=Xi:(t.calledRun=!0,v||(We(),$?.(t)))}}return n||(ea=await Ke(),Xi()),t.PTR_SIZE=4,t.webgpuInit=u=>{let p=new WeakMap,f,E,A=1;t.webgpuRegisterDevice=R=>{if(E!==void 0)throw Error("another WebGPU EP inference session is being created.");if(R){var q=p.get(R);if(!q){let ee=((ye,Be=0)=>{var Ze=fE(Be);return Be=hE(Be,Ze),At[Ze>>>0]=ye.queue,At[Be>>>0]=ye,Be})(R,q=oE(0));q=[A++,q,ee],p.set(R,q)}return f=R,E=q[0],q}f=void 0,E=0};let y=new Map;t.webgpuOnCreateSession=R=>{if(E!==void 0){var q=E;if(E=void 0,R){let ee=al(q);y.set(R,ee),q===0&&u(f??oe(ee))}f=void 0}},t.webgpuOnReleaseSession=R=>{y.delete(R)};let w=Symbol("gpuBufferMetadata");t.webgpuRegisterBuffer=(R,q,ee)=>{if(ee)return R[w]=[ee,NaN],ee;if(ee=R[w])return ee[1]++,ee[0];if((q=y.get(q))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");return q=((ye,Be=0)=>(ye.mapState==="unmapped"||ce(),Be=pE(Be),At[Be>>>0]=ye,Be))(R,q),R[w]=[q,1],q},t.webgpuUnregisterBuffer=R=>{let q=R[w];if(!q)throw Error("Buffer is not registered");q[1]--,q[1]===0&&(iE(q[0]),delete R[w])},t.webgpuGetBuffer=R=>oe(R),t.webgpuCreateDownloader=(R,q,ee)=>{if((ee=y.get(ee))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");let ye=oe(ee),Be=16*Math.ceil(Number(q)/16);return async()=>{let Ze=ye.createBuffer({size:Be,usage:9});try{let _e=ye.createCommandEncoder();return _e.copyBufferToBuffer(R,0,Ze,0,Be),ye.queue.submit([_e.finish()]),await Ze.mapAsync(GPUMapMode.READ),Ze.getMappedRange().slice(0,q)}finally{Ze.destroy()}}},t.ad=(R,q)=>{var ee=q.buffer;let ye=q.byteOffset,Be=q.byteLength;if(q=16*Math.ceil(Number(Be)/16),R=oe(R),!f){var Ze=al(E);f=oe(Ze)}let _e=(Ze=f.createBuffer({mappedAtCreation:!0,size:q,usage:6})).getMappedRange();new Uint8Array(_e).set(new Uint8Array(ee,ye,Be)),Ze.unmap(),(ee=f.createCommandEncoder()).copyBufferToBuffer(Ze,0,R,0,q),f.queue.submit([ee.finish()]),Ze.destroy()}},t.webnnInit=u=>{let p=u[0];[t.le,t.jd,t.webnnEnsureTensor,t.Sd,t.webnnDownloadTensor,t.ke,t.webnnEnableTraceEvent]=u.slice(1),t.webnnReleaseTensorId=t.jd,t.webnnUploadTensor=t.Sd,t.webnnRegisterMLContext=t.ke,t.webnnOnRunStart=f=>p.onRunStart(f),t.webnnOnRunEnd=p.onRunEnd.bind(p),t.webnnOnReleaseSession=f=>{p.onReleaseSession(f)},t.webnnCreateMLTensorDownloader=(f,E)=>p.createMLTensorDownloader(f,E),t.webnnRegisterMLTensor=(f,E,A,y)=>p.registerMLTensor(f,E,A,y),t.webnnCreateMLContext=f=>p.createMLContext(f),t.webnnRegisterMLConstant=(f,E,A,y,w,R)=>p.registerMLConstant(f,E,A,y,w,t.Uc,R),t.webnnRegisterGraphInput=p.registerGraphInput.bind(p),t.webnnIsGraphInput=p.isGraphInput.bind(p),t.webnnRegisterGraphOutput=p.registerGraphOutput.bind(p),t.webnnIsGraphOutput=p.isGraphOutput.bind(p),t.webnnCreateTemporaryTensor=p.createTemporaryTensor.bind(p),t.webnnIsGraphInputOutputTypeSupported=p.isGraphInputOutputTypeSupported.bind(p)},Y?t:new Promise((u,p)=>{$=u,m=p})}async function YL(e){let t=e.split("/").pop(),r;try{if(r=await hs(),r){let n=await r.match(e);if(n)return n}}catch(n){fe.warn(`Failed to load ${t} from cache:`,n)}let a=await ge.fetch(e);if(!a.ok)throw new Error(`Failed to fetch ${t}: ${a.status} ${a.statusText}`);if(r)try{await r.put(e,a.clone())}catch(n){fe.warn(`Failed to cache ${t}:`,n)}return a}async function PF(e){let t=await YL(e);if(!t||typeof t=="string")return null;try{return await t.arrayBuffer()}catch(r){return fe.warn("Failed to read WASM binary:",r),null}}async function kF(e){if(Ie.IS_SERVICE_WORKER_ENV||Ie.IS_CHROME_AVAILABLE)return e;let t=await YL(e);if(!t||typeof t=="string")return null;try{let r=await t.text();r=r.replaceAll("globalThis.process?.versions?.node","false");let a=new Blob([r],{type:"text/javascript"});return URL.createObjectURL(a)}catch(r){return fe.warn("Failed to read WASM factory:",r),null}}function eA(e){return e<=ur.DEBUG?0:e<=ur.INFO?2:e<=ur.WARNING||e<=ur.ERROR?3:4}function FF(e=null){if(!e)return id;switch(e){case"auto":return lr;case"gpu":return lr.filter(t=>["webgpu","cuda","dml","webnn-gpu"].includes(t))}if(lr.includes(e))return[RF[e]??e];throw new Error(`Unsupported device: "${e}". Should be one of: ${lr.join(", ")}.`)}async function ZF(){if(Qn)return Qn;if(!(ge.useWasmCache&&typeof lt?.wasm?.wasmPaths=="object"&&lt?.wasm?.wasmPaths?.wasm&&lt?.wasm?.wasmPaths?.mjs)){if(Ie.IS_DENO_WEB_RUNTIME)throw new Error("env.useWasmCache=false is not supported in Deno's web runtime. Remove the useWasmCache override.");return Qn=Promise.resolve(),Qn}return Qn=(async()=>{let t=lt.wasm.wasmPaths,r=!1;await Promise.all([t.wasm&&!BI(t.wasm)?(async()=>{try{let a=await PF(MI(t.wasm));a&&(lt.wasm.wasmBinary=a,r=!0)}catch(a){fe.warn("Failed to pre-load WASM binary:",a)}})():Promise.resolve(),t.mjs&&!BI(t.mjs)?(async()=>{try{let a=await kF(MI(t.mjs));a&&(lt.wasm.wasmPaths.mjs=a)}catch(a){fe.warn("Failed to pre-load WASM factory:",a)}})():Promise.resolve()]),r||(lt.wasm.wasmPaths.mjs=t.mjs)})(),Qn}async function tA(e,t,r){await ZF();let a=eA(ge.logLevel??ur.WARNING),n=()=>GF.create(e,{logSeverityLevel:a,...t}),s=await(Ie.IS_WEB_ENV?dS=dS.then(n):n());return s.config=r,s}async function rA(e,t){let r=()=>e.run(t);return Ie.IS_WEB_ENV?pS=pS.then(r):r()}function aA(e){return e instanceof _s.Tensor}function Zd(){return lt?.wasm?.proxy}function nA(e,t,{warn:r}={}){return e?typeof e=="string"?e:e.hasOwnProperty(t)?e[t]:(r&&r(`device not specified for "${t}". Using the default device (${Ku}).`),Ku):Ku}function sA(e,t,r,{configDtype:a=null,warn:n}={}){let s,i=!1;e&&typeof e!="string"?e.hasOwnProperty(t)?s=e[t]:(s=null,i=!0):s=e;let o;if(s===it.auto){if(a){let H=typeof a=="string"?a:a?.[t];if(H&&H!==it.auto&&it.hasOwnProperty(H))return H}o=fS[r]??hS}else s&&it.hasOwnProperty(s)?o=s:o=fS[r]??hS;return i&&n&&n(`dtype not specified for "${t}". Using the default dtype (${o}) for this device (${r}).`),o}function KF(e,t){let r=e.length,a=t.reduce((s,i)=>s*i);if(r!==a)throw Error(`cannot reshape array of size ${r} into shape (${t})`);let n=e;for(let s=t.length-1;s>=0;s--)n=n.reduce((i,o)=>{let H=i[i.length-1];return H.length<t[s]?H.push(o):i.push([o]),i},[[]]);return n[0]}function iA(e,t){let[r,a]=Q6(e.data,e.dims,t);return new j(e.type,r,a)}function Ud(e,[t,r],a="bilinear",n=!1){let s=e.dims.at(-3)??1,i=e.dims.at(-2),o=e.dims.at(-1),H=J6(e.data,[s,i,o],[t,r],a,n);return new j(e.type,H,[s,t,r])}async function dr(e,{size:t=null,mode:r="bilinear"}={}){if(e.dims.length!==4)throw new Error("`interpolate_4d` currently only supports 4D input.");if(!t)throw new Error("`interpolate_4d` requires a `size` argument.");let a;if(t.length===2)a=[...e.dims.slice(0,2),...t];else if(t.length===3)a=[e.dims[0],...t];else if(t.length===4)a=t;else throw new Error("`size` must be of length 2, 3, or 4.");let n;if(r==="nearest")n=await rn.nearest_interpolate_4d;else if(r==="bilinear")n=await rn.bilinear_interpolate_4d;else if(r==="bicubic")n=await rn.bicubic_interpolate_4d;else throw new Error(`Unsupported mode: ${r}`);let s=new j("int64",new BigInt64Array(a.map(BigInt)),[a.length]);return await n({x:e,s})}async function oA(e,t){return await(await rn.matmul)({a:e,b:t})}async function VF(e,t){return await(await rn.rfft)({x:e,a:t})}async function _n(e,t){let r=await rn.top_k;return t==null?t=e.dims.at(-1):t=Math.min(t,e.dims.at(-1)),await r({x:e,k:new j("int64",[BigInt(t)],[1])})}async function Wd(e,t,r,a,n){return await(await rn.slice)({x:e,s:Ko(t),e:Ko(r),a:Ko(a),t:Ko(n??new Array(a.length).fill(1))})}function HA(e,t){let r=e.data,a=t.data,n=[e.dims[0],e.dims[2]],s=new r.constructor(n[0]*n[1]),[i,o,H]=e.dims,_=0;for(let c=0;c<i;++c){let l=c*H*o;for(let d=0;d<H;++d){let h=0,$=0,m=c*o,S=l+d;for(let g=0;g<o;++g){let T=Number(a[m+g]);$+=T,h+=r[S+g*H]*T}let I=h/$;s[_++]=I}}return new j(e.type,s,n)}function jF(e,t,{eps:r=1e-5}={}){if(e.dims.length!==2)throw new Error("`layer_norm` currently only supports 2D input.");let[a,n]=e.dims;if(t.length!==1&&t[0]!==n)throw new Error("`normalized_shape` must be a 1D array with shape `[input.dims[1]]`.");let[s,i]=Kd(e,1,0,!0),o=s.data,H=i.data,_=e.data,c=new _.constructor(_.length);for(let l=0;l<a;++l){let d=l*n;for(let h=0;h<n;++h){let $=d+h;c[$]=(_[$]-H[l])/(o[l]+r)}}return new j(e.type,c,e.dims)}function ES(e,t){return e=e.slice(),t===null?e=e.filter(r=>r!==1):typeof t=="number"?e[t]===1&&e.splice(t,1):Array.isArray(t)&&(e=e.filter((r,a)=>r!==1||!t.includes(a))),e}function $S(e,t){return t=Zr(t,e.length+1),e=e.slice(),e.splice(t,0,1),e}function Zr(e,t,r=null,a=!0){if(e<-t||e>=t){if(a)throw new Error(`IndexError: index ${e} is out of bounds for dimension${r===null?"":" "+r} with size ${t}`);return e<-t?0:t}return e<0&&(e=(e%t+t)%t),e}function Ue(e,t=0){t=Zr(t,e[0].dims.length);let r=e[0].dims.slice();r[t]=e.reduce((i,o)=>i+o.dims[t],0);let a=r.reduce((i,o)=>i*o,1),n=new e[0].data.constructor(a),s=e[0].type;if(t===0){let i=0;for(let o of e){let H=o.data;n.set(H,i),i+=H.length}}else{let i=0;for(let o=0;o<e.length;++o){let{data:H,dims:_}=e[o];for(let c=0;c<H.length;++c){let l=0;for(let d=_.length-1,h=c,$=1;d>=0;--d){let m=_[d],S=h%m;d===t&&(S+=i),l+=S*$,$*=r[d],h=Math.floor(h/m)}n[l]=H[c]}i+=_[t]}}return new j(s,n,r)}function Ur(e,t=0){return Ue(e.map(r=>r.unsqueeze(t)),t)}function ai(e,t,r,a=!1,n=null){let s=t.data,i=t.dims;r=Zr(r,i.length);let o=i.slice();o[r]=1;let H=new s.constructor(s.length/i[r]);n!==null&&H.fill(n);for(let _=0;_<s.length;++_){let c=0;for(let l=i.length-1,d=_,h=1;l>=0;--l){let $=i[l];if(l!==r){let m=d%$;c+=m*h,h*=o[l]}d=Math.floor(d/$)}H[c]=e(H[c],s[_],_,c)}return a||o.splice(r,1),[t.type,H,o]}function Kd(e,t=null,r=1,a=!1){let n=e.data,s=e.dims;if(t===null){let h=n.reduce((I,g)=>I+g,0)/n.length,$=Math.sqrt(n.reduce((I,g)=>I+(g-h)**2,0)/(n.length-r)),m=new j(e.type,[h],[]);return[new j(e.type,[$],[]),m]}t=Zr(t,s.length);let i=bH(e,t,a),o=i.data,[H,_,c]=ai((d,h,$,m)=>d+(h-o[m])**2,e,t,a);for(let d=0;d<_.length;++d)_[d]=Math.sqrt(_[d]/(s[t]-r));return[new j(H,_,c),i]}function bH(e,t=null,r=!1){let a=e.dims,n=e.data;if(t===null){let H=n.reduce((_,c)=>_+c,0);return new j(e.type,[H/n.length],[])}t=Zr(t,a.length);let[s,i,o]=ai((H,_)=>H+_,e,t,r);if(a[t]!==1)for(let H=0;H<i.length;++H)i[H]/=a[t];return new j(s,i,o)}function Vu(e){let t=new Array(e.length);for(let r=e.length-1,a=1;r>=0;--r)t[r]=a,a*=e[r];return t}function Vd(e,t,r,a){let n=e.reduce((s,i)=>s*i,1);return new j(r,new a(n).fill(t),e)}function xt(e,t){let r,a;if(typeof t=="number")r="float32",a=Float32Array;else if(typeof t=="bigint")r="int64",a=BigInt64Array;else if(typeof t=="boolean")r="bool",a=Uint8Array;else throw new Error(`Unsupported data type: ${typeof t}`);return Vd(e,t,r,a)}function dH(e,t){return xt(e.dims,t)}function Kt(e){return Vd(e,1n,"int64",BigInt64Array)}function jd(e){return Kt(e.dims)}function qd(e){return Vd(e,0n,"int64",BigInt64Array)}function Xd(e){return qd(e.dims)}function qF(e){let t=e.reduce((r,a)=>r*a,1);return new j("float32",Float32Array.from({length:t},()=>ui.random()),e)}function _A(e){let t=e.reduce((r,a)=>r*a,1);return new j("float32",Float32Array.from({length:t},()=>ui.gauss()),e)}function cA(e,t){if(e.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(e.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(t))throw new Error("The precision must be either 'binary' or 'ubinary'");let r=t==="binary",a=r?"int8":"uint8",n=r?Int8Array:Uint8Array,s=e.data,i=new n(s.length/8);for(let o=0;o<s.length;++o){let H=s[o]>0?1:0,_=Math.floor(o/8),c=o%8;i[_]|=H<<7-c,r&&c===0&&(i[_]-=128)}return new j(a,i,[e.dims[0],e.dims[1]/8])}async function zd(e){if(!e)throw new Error("modelId is required for get_tokenizer_files");return(await sn(e,"tokenizer_config.json",{})).exists?["tokenizer.json","tokenizer_config.json"]:[]}async function lA(e,t){let r=await zd(e);return await Promise.all(r.map(a=>jr(e,a,!0,t)))}function Jd(e){let t=e.dims;switch(t.length){case 1:return e.tolist();case 2:if(t[0]!==1)throw new Error("Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs.");return e.tolist()[0];default:throw new Error(`Expected tensor to have 1-2 dimensions, got ${t.length}.`)}}function zF(e,t,r,a){for(let n of Object.keys(e)){let s=t-e[n].length,i=r(n),o=new Array(s).fill(i);e[n]=a==="right"?$r(e[n],o):$r(o,e[n])}}function JF(e,t){for(let r of Object.keys(e))e[r].length=t}function ja(e,...t){for(let r of t){if(!Object.hasOwn(e,r))continue;let a=e[r];if(a)if(typeof a=="object"){if(a.__type==="AddedToken")return a.content;throw Error(`Unknown token: ${a}`)}else return a}return null}function QF(e){let t=[];for(let r of e.get_added_tokens_decoder().values())r.special&&t.push(r);return t}function Qd(e,t,r,a){if(!("language_codes"in e)||!Array.isArray(e.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in e)||!(e.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in e)||typeof e.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");let n=a.src_lang,s=a.tgt_lang;if(!e.language_codes.includes(s))throw new Error(`Target language code "${s}" is not valid. Must be one of: {${e.language_codes.join(", ")}}`);if(n!==void 0){if(!e.language_codes.includes(n))throw new Error(`Source language code "${n}" is not valid. Must be one of: {${e.language_codes.join(", ")}}`);for(let i of e._tokenizer.post_processor.config.single)if("SpecialToken"in i&&e.languageRegex.test(i.SpecialToken.id)){i.SpecialToken.id=e.lang_to_token(n);break}}return a.forced_bos_token_id=e._tokenizer.token_to_id(e.lang_to_token(s)),e._call(t,r)}function tZ(e){e=e.toLowerCase();let t=eZ.get(e);if(t===void 0){let r=e.match(/^<\|([a-z]{2})\|>$/);if(r&&(e=r[1]),Yo.has(e))t=e;else{let n=e.length===2?Yo.keys():Yo.values();throw new Error(`Language "${e}" is not supported. Must be one of: ${JSON.stringify(Array.from(n))}`)}}return t}function yt(e,t){if(!(e instanceof Float32Array||e instanceof Float64Array))throw new Error(`${t} expects input to be a Float32Array or a Float64Array, but got ${e?.constructor?.name??typeof e} 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.`)}async function _g(e,t){if(Ie.IS_BROWSER_ENV){if(Ie.IS_WEBWORKER_ENV)throw new Error("Unable to save a file from a Web Worker.");let r=URL.createObjectURL(t),a=document.createElement("a");a.href=r,a.download=e,a.click(),a.remove(),URL.revokeObjectURL(r)}else if(Ie.IS_FS_AVAILABLE){let r=t.stream(),a=og.Readable.fromWeb(r),n=ig.default.createWriteStream(e);await(0,Hg.pipeline)(a,n)}else throw new Error("Unable to save because filesystem is disabled in this environment.")}async function cg(e,t){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.");let r=await(await si(e)).arrayBuffer(),a=new AudioContext({sampleRate:t});typeof t>"u"&&fe.warn(`No sampling rate provided, using default of ${a.sampleRate}Hz.`);let n=await a.decodeAudioData(r),s;if(n.numberOfChannels===2){let i=Math.sqrt(2),o=n.getChannelData(0),H=n.getChannelData(1);s=new Float32Array(o.length);for(let _=0;_<n.length;++_)s[_]=i*(o[_]+H[_])/2}else s=n.getChannelData(0);return s}function ug(e,t){if(e<1)return new Float64Array;if(e===1)return new Float64Array([1]);let r=1-t,a=2*Math.PI/(e-1),n=new Float64Array(e);for(let s=0;s<e;++s)n[s]=t-r*Math.cos(s*a);return n}function IS(e){return ug(e,.5)}function nZ(e){return ug(e,.54)}function ju(e,t="htk"){let r=sZ[t];if(!r)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof e=="number"?r(e):e.map(a=>r(a))}function oZ(e,t="htk"){let r=iZ[t];if(!r)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof e=="number"?r(e):e.map(a=>r(a))}function HZ(e,t){let r=Float64Array.from({length:t.length-1},(i,o)=>t[o+1]-t[o]),a=Array.from({length:e.length},()=>new Array(t.length));for(let i=0;i<e.length;++i){let o=a[i];for(let H=0;H<t.length;++H)o[H]=t[H]-e[i]}let n=t.length-2,s=Array.from({length:n},()=>new Array(e.length));for(let i=0;i<e.length;++i){let o=a[i];for(let H=0;H<n;++H){let _=-o[H]/r[H],c=o[H+2]/r[H+1];s[H][i]=Math.max(0,Math.min(_,c))}}return s}function SS(e,t,r){let a=(t-e)/(r-1);return Float64Array.from({length:r},(n,s)=>e+a*s)}function Wr(e,t,r,a,n,s=null,i="htk",o=!1){if(s!==null&&s!=="slaney")throw new Error('norm must be one of null or "slaney"');if(e<2)throw new Error(`Require num_frequency_bins: ${e} >= 2`);if(r>a)throw new Error(`Require min_frequency: ${r} <= max_frequency: ${a}`);let H=ju(r,i),_=ju(a,i),c=SS(H,_,t+2),l=oZ(c,i),d;if(o){let $=n/((e-1)*2);d=ju(Float64Array.from({length:e},(m,S)=>S*$),i),l=c}else d=SS(0,Math.floor(n/2),e);let h=HZ(d,l);if(s!==null&&s==="slaney")for(let $=0;$<t;++$){let m=h[$],S=2/(l[$+2]-l[$]);for(let I=0;I<e;++I)m[I]*=S}return h}function _Z(e,t,r){let a=new e.constructor(e.length+t+r),n=e.length-1;for(let s=0;s<e.length;++s)a[t+s]=e[s];for(let s=1;s<=t;++s)a[t-s]=e[nH(s,n)];for(let s=1;s<=r;++s)a[n+t+s]=e[nH(n-s,n)];return a}function dg(e,t,r,a,n){if(r<=0)throw new Error("reference must be greater than zero");if(a<=0)throw new Error("min_value must be greater than zero");r=Math.max(a,r);let s=Math.log10(r);for(let i=0;i<e.length;++i)e[i]=t*Math.log10(Math.max(a,e[i])-s);if(n!==null){if(n<=0)throw new Error("db_range must be greater than zero");let i=nt(e)[0]-n;for(let o=0;o<e.length;++o)e[o]=Math.max(e[o],i)}return e}function cZ(e,t=1,r=1e-5,a=null){return dg(e,20,t,r,a)}function lZ(e,t=1,r=1e-10,a=null){return dg(e,10,t,r,a)}async function qr(e,t,r,a,{fft_length:n=null,power:s=1,center:i=!0,pad_mode:o="reflect",onesided:H=!0,preemphasis:_=null,preemphasis_htk_flavor:c=!0,mel_filters:l=null,mel_floor:d=1e-10,log_mel:h=null,max_log_mel:$=null,reference:m=1,min_value:S=1e-10,db_range:I=null,remove_dc_offset:g=null,min_num_frames:T=null,max_num_frames:x=null,do_pad:v=!0,transpose:k=!1,mel_offset:L=0,mel_floor_mode:V="clamp"}={}){let K=t.length;if(n===null&&(n=r),r>n)throw Error(`frame_length (${r}) may not be larger than fft_length (${n})`);if(K!==r)throw new Error(`Length of the window (${K}) must equal frame_length (${r})`);if(a<=0)throw new Error("hop_length must be greater than zero");if(s===null&&l!==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(!c)throw new Error("`preemphasis_htk_flavor=false` is not currently supported.");if(i){let Y=Math.floor(r/2);switch(o){case"reflect":{e=_Z(e,Y,Y);break}case"constant":{let Se=new e.constructor(e.length+2*Y);Se.set(e,Y),e=Se;break}case"semicausal":{let Se=new e.constructor(e.length+Y);Se.set(e,Y),e=Se;break}default:throw new Error(`pad_mode="${o}" not implemented yet.`)}}let X=Math.floor(1+Math.floor((e.length-r)/a));T!==null&&X<T&&(X=T);let Q=H?Math.floor(n/2)+1:n,z=X,M=X;x!==null&&(x>X?v&&(M=x):M=z=x);let F=new tF(n),N=new Float64Array(n),G=new Float64Array(F.outputBufferSize),te=new Float32Array(Q*M);for(let Y=0;Y<z;++Y){let Se=Y*a,We=Math.min(e.length-Se,r);We!==r&&N.fill(0,0,r);for(let ce=0;ce<We;++ce)N[ce]=e[Se+ce];if(g){let ce=0;for(let Ke=0;Ke<We;++Ke)ce+=N[Ke];let Bt=ce/We;for(let Ke=0;Ke<We;++Ke)N[Ke]-=Bt}if(_!==null){for(let ce=We-1;ce>=1;--ce)N[ce]-=_*N[ce-1];N[0]*=1-_}for(let ce=0;ce<t.length;++ce)N[ce]*=t[ce];F.realTransform(G,N);for(let ce=0;ce<Q;++ce){let Bt=ce<<1;te[ce*M+Y]=G[Bt]**2+G[Bt+1]**2}}if(s!==null&&s!==2){let Y=s/2;for(let Se=0;Se<te.length;++Se)te[Se]**=Y}let B=l.length,O=await oA(new j("float32",l.flat(),[B,Q]),new j("float32",te,[Q,M]));k&&(O=O.transpose(1,0));let U=O.data;if(V==="add")for(let Y=0;Y<U.length;++Y)U[Y]=L+U[Y]+d;else for(let Y=0;Y<U.length;++Y)U[Y]=L+Math.max(d,U[Y]);if(s!==null&&h!==null){let Y=Math.min(U.length,z*B);switch(h){case"log":for(let Se=0;Se<Y;++Se)U[Se]=Math.log(U[Se]);break;case"log10":for(let Se=0;Se<Y;++Se)U[Se]=Math.log10(U[Se]);break;case"log10_max_norm":{for(let ce=0;ce<Y;++ce)U[ce]=Math.log10(U[ce]);let We=($??nt(U)[0])-8;for(let ce=0;ce<Y;++ce)U[ce]=(Math.max(U[ce],We)+4)/4;break}case"dB":if(s===1)cZ(U,m,S,I);else if(s===2)lZ(U,m,S,I);else throw new Error(`Cannot use log_mel option '${h}' with power ${s}`);break;default:throw new Error(`log_mel must be one of null, 'log', 'log10', 'log10_max_norm', or 'dB'. Got '${h}'`)}}return O}function la(e,t,{periodic:r=!0,frame_length:a=null,center:n=!0}={}){let s=r?e+1:e,i;switch(t){case"boxcar":i=new Float64Array(s).fill(1);break;case"hann":case"hann_window":i=IS(s);break;case"hamming":i=nZ(s);break;case"povey":i=IS(s).map(_=>Math.pow(_,.85));break;default:throw new Error(`Unknown window type ${t}.`)}if(r&&(i=i.subarray(0,e)),a===null||e===a)return i;if(e>a)throw new Error(`Length of the window (${e}) may not be larger than frame_length (${a})`);let o=new Float64Array(a),H=n?Math.floor((a-e)/2):0;return o.set(i,H),o}function uZ(e,t){let r=e.reduce((s,i)=>s+i.length,0),a=new ArrayBuffer(44),n=new DataView(a);return Vo(n,0,"RIFF"),n.setUint32(4,36+r*4,!0),Vo(n,8,"WAVE"),Vo(n,12,"fmt "),n.setUint32(16,16,!0),n.setUint16(20,3,!0),n.setUint16(22,1,!0),n.setUint32(24,t,!0),n.setUint32(28,t*4,!0),n.setUint16(32,4,!0),n.setUint16(34,32,!0),Vo(n,36,"data"),n.setUint32(40,r*4,!0),new Blob([a,...e.map(s=>s.buffer)],{type:"audio/wav"})}function Vo(e,t,r){for(let a=0;a<r.length;++a)e.setUint8(t+a,r.charCodeAt(a))}function LS(e,t,r=0,a=null){let n=e/t,s=aF(n)*t;return a!==null&&s>a&&(s=Math.floor(n)*t),s<r&&(s=Math.ceil(n)*t),s}function AS([e,t],r){return[Math.max(Math.floor(e/r),1)*r,Math.max(Math.floor(t/r),1)*r]}function Cg([e,t,r,a]){return[e-r/2,t-a/2,e+r/2,t+a/2]}function xH(e,t=.5,r=null,a=!1){let n=e.logits,s=e.pred_boxes,[i,o,H]=n.dims;if(r!==null&&r.length!==i)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let _=[];for(let c=0;c<i;++c){let l=r!==null?r[c]:null,d={boxes:[],classes:[],scores:[]},h=n[c],$=s[c];for(let m=0;m<o;++m){let S=h[m],I=[],g;if(a){g=S.sigmoid().data;for(let T=0;T<g.length;++T)g[T]>t&&I.push(T)}else{let T=nt(S.data)[1];if(T===H-1||(g=St(S.data),g[T]<t))continue;I.push(T)}for(let T of I){let x=$[m].data;x=Cg(x),l!==null&&(x=x.map((v,k)=>v*l[(k+1)%2])),d.boxes.push(x),d.classes.push(T),d.scores.push(g[T])}}_.push(d)}return _}function wg(e,t=null){let r=e.logits,a=r.dims[0];if(t!==null&&t.length!==a)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let n=[];for(let s=0;s<a;++s){let i=t!==null?t[s]:null,o=r[s];i!==null&&(o=Ud(o,i,"bilinear",!1));let[H,_]=i??o.dims.slice(-2),c=new j("int32",new Int32Array(H*_),[H,_]),l=o[0].data,d=c.data;for(let m=1;m<o.dims[0];++m){let S=o[m].data;for(let I=0;I<S.length;++I)S[I]>l[I]&&(l[I]=S[I],d[I]=m)}let h=new Array(o.dims[0]);for(let m=0;m<d.length;++m){let S=d[m];h[S]=S}let $=h.filter(m=>m!==void 0);n.push({segmentation:c,labels:$})}return n}function $Z(e,t,r,a){let n=[],s=[],i=[];for(let o=0;o<e.dims[0];++o){let H=e[o],_=t[o],c=nt(H.data)[1];if(c===a)continue;let d=St(H.data)[c];d>r&&(n.push(_),s.push(d),i.push(c))}return[n,s,i]}function mZ(e,t,r,a=.5,n=.8){let s=[],i=0,o=0,H=t[r].data;for(let c=0;c<e.length;++c)e[c]===r&&(s.push(c),++i),H[c]>=a&&++o;let _=i>0&&o>0;return _&&(_=i/o>n),[_,s]}function IZ(e,t,r,a,n,s=null,i=null){let[o,H]=i??e[0].dims,_=new j("int32",new Int32Array(o*H),[o,H]),c=[];if(i!==null)for(let m=0;m<e.length;++m)e[m]=Ud(e[m],i,"bilinear",!1);let l=new Int32Array(e[0].data.length),d=new Float32Array(e[0].data.length);for(let m=0;m<e.length;++m){let S=t[m],I=e[m].data;for(let g=0;g<I.length;++g)I[g]*=S,I[g]>d[g]&&(l[g]=m,d[g]=I[g])}let h=0,$=_.data;for(let m=0;m<r.length;++m){let S=r[m],[I,g]=mZ(l,e,m,a,n);if(I){++h;for(let T of g)$[T]=h;c.push({id:h,label_id:S,score:t[m]})}}return[_,c]}function Hp(e,t,r=28,a=3136,n=784*1280,s=1){if(e<r||t<r){let H=Math.max(r/e,r/t);e=Math.round(e*H),t=Math.round(t*H)}if(Math.max(e,t)/Math.min(e,t)>200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(e,t)/Math.min(e,t)}`);let i=Math.round(e/r)*r,o=Math.round(t/r)*r;if(s*i*o>n){let H=Math.sqrt(s*e*t/n);i=Math.max(r,Math.floor(e/H/r)*r),o=Math.max(r,Math.floor(t/H/r)*r)}else if(s*i*o<a){let H=Math.sqrt(a/(s*e*t));i=Math.ceil(e*H/r)*r,o=Math.ceil(t*H/r)*r}return[o,i]}function Ng(e,t=.5,r=.5,a=.8,n=null,s=null){n===null&&(fe.warn("`label_ids_to_fuse` unset. No instance will be fused."),n=new Set);let i=e.class_queries_logits??e.logits,H=(e.masks_queries_logits??e.pred_masks).sigmoid(),[_,c,l]=i.dims;if(l-=1,s!==null&&s.length!==_)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let d=[];for(let h=0;h<_;++h){let $=s!==null?s[h]:null,m=i[h],S=H[h],[I,g,T]=$Z(m,S,t,l);if(T.length===0){let[k,L]=$??S.dims.slice(-2),V=new j("int32",new Int32Array(k*L).fill(-1),[k,L]);d.push({segmentation:V,segments_info:[]});continue}let[x,v]=IZ(I,g,T,r,a,n,$);d.push({segmentation:x,segments_info:v})}return d}function Bg(e,t=.5,r=null){throw new Error("`post_process_instance_segmentation` is not yet implemented.")}function SZ(e,t,r,a,n){let s=a*r**2,i=Math.sqrt(s/(e*t)),o=n*r,H=Math.floor(i*e/o)*o,_=Math.floor(i*t/o)*o;if(H===0&&_===0)throw new Error(`Attempting to resize to a 0 x 0 image. Resized height should be divisible by \`pooling_kernel_size * patch_size\`=${o}.`);let c=Math.floor(a/n**2)*o;return H===0?(H=o,_=Math.min(Math.floor(t/e)*o,c)):_===0&&(_=o,H=Math.min(Math.floor(e/t)*o,c)),[H,_]}function LZ(e,t,r,a,n,s,i){let o=Math.floor(t/n),H=Math.floor(r/n),_=o*H,c=n*n*a,l=new Float32Array(s*c),d=0;for(let m=0;m<o;++m)for(let S=0;S<H;++S)for(let I=0;I<n;++I){let g=(m*n+I)*r*a+S*n*a;for(let T=0;T<n;++T){let x=g+T*a;for(let v=0;v<a;++v)l[d++]=e[x+v]}}let h=new BigInt64Array(s*2).fill(-1n),$=0;for(let m=0;m<o;++m)for(let S=0;S<H;++S)h[$++]=BigInt(S),h[$++]=BigInt(m);return{patches:new j("float32",l,[s,c]),positions:new j("int64",h,[s,2]),num_soft_tokens:Math.floor(_/i**2)}}function gS(e,t){return Math.round(e/t)*t}function AZ(e,t,r,a,n){let s=1/0,i=[1,1],o=r*a;for(let H of t){let _=Math.abs(e-H[0]/H[1]);_<s?(s=_,i=H):_===s&&o>.5*n*n*H[0]*H[1]&&(i=H)}return i}function gZ(e,t){let r=[],a=new Set;for(let n=e;n<=t;++n)for(let s=1;s<=n;++s)for(let i=1;i<=n;++i){let o=s*i;if(o>=e&&o<=t){let H=s<<16|i;a.has(H)||(a.add(H),r.push([s,i]))}}return r.sort((n,s)=>n[0]*n[1]-s[0]*s[1])}function bZ(e,t){let[r,a,n,s]=e.dims,i=Math.floor(n/t),o=Math.floor(s/t),H=t*t*a,_=e.data,c=new Float32Array(r*i*o*H),l=n*s;for(let d=0;d<r;++d){let h=d*a*l,$=d*i*o*H;for(let m=0;m<i;++m)for(let S=0;S<o;++S){let I=$+(m*o+S)*H;for(let g=0;g<t;++g){let T=(m*t+g)*s+S*t;for(let x=0;x<t;++x){let v=T+x;for(let k=0;k<a;++k)c[I++]=_[h+k*l+v]}}}}return new j("float32",c,[r,i*o,H])}function TZ(e,t){let[,r,a]=e.dims,n=new BigInt64Array(t);n.fill(1n,0,r);let s=e;if(r<t){let i=new Float32Array(t*a);i.set(e.data),s=new j("float32",i,[1,t,a])}return{padded:s,mask:new j("int64",n,[t])}}function vZ(e,t){let a=e.dims.at(-1)-1,n=e.tolist();n.fill(!1,0,1),n.fill(!1,a);let s=t.tolist();return n.map((i,o)=>i?o:null).filter(i=>i!==null).map(i=>s[i])}function yZ(e,t,r,a,n,s){let i="";for(let o=0;o<t;++o){for(let H=0;H<r;++H)i+=a+`<row_${o+1}_col_${H+1}>`+n.repeat(e);i+=`
12
- `}return i+=`
13
- ${a}${s}`+n.repeat(e)+`${a}`,i}function DZ(e,t,r,a){return`${t}${a}`+r.repeat(e)+`${t}`}function CZ(e,t,r,a,n,s){return e===0&&t===0?DZ(r,a,n,s):yZ(r,e,t,a,n,s)}function wZ(e,t,r,a,n){return`${a.repeat(r*n)}${t}${e}
14
- `}function PZ(e,t){let r=[];for(let a=0;a<e.length;a+=t)r.push(e.subarray(a,Math.min(a+t,e.length)));return r}async function OZ(e,t){return await jr(e,"config.json",!0,t)}function as(e){let t={},r={};switch(e.model_type){case"llava":case"paligemma":case"gemma3":case"florence2":case"llava_onevision":case"idefics3":case"granite_speech":case"ultravox":case"voxtral":case"voxtral_realtime":case"smolvlm":case"gemma3n":case"gemma4":case"lfm2_vl":case"chatterbox":case"lighton_ocr":case"glm_ocr":case"mistral3":case"qwen2_5_vl":case"qwen3_vl":case"qwen3_vl_moe":r=as(e.text_config);break;case"moondream1":r=as(e.phi_config);break;case"musicgen":r=as(e.decoder);break;case"multi_modality":r=as(e.language_config);break;case"gpt2":case"gptj":case"jais":case"codegen":case"gpt_bigcode":t.num_heads="n_head",t.num_layers="n_layer",t.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"falcon":case"modernbert-decoder":t.num_heads="num_attention_heads",t.num_layers="num_hidden_layers",t.hidden_size="hidden_size";break;case"gpt_oss":case"llama":case"llama4_text":case"nanochat":case"apertus":case"arcee":case"afmoe":case"lfm2":case"lfm2_moe":case"smollm3":case"olmo":case"olmo2":case"olmo3":case"mobilellm":case"granite":case"granitemoehybrid":case"cohere":case"cohere2":case"mistral":case"voxtral_realtime_text":case"voxtral_realtime_encoder":case"starcoder2":case"qwen2":case"qwen2_moe":case"qwen2_vl":case"qwen2_vl_text":case"qwen2_5_vl_text":case"qwen3_moe":case"qwen3_vl_text":case"qwen3_vl_moe_text":case"phi":case"phi3":case"phi3_v":case"llava_qwen2":t.num_heads="num_key_value_heads",t.num_layers="num_hidden_layers",t.hidden_size="hidden_size",t.num_attention_heads="num_attention_heads",t.dim_kv="head_dim";break;case"qwen3":case"solar_open":case"glm_ocr_text":case"gemma":case"gemma2":case"vaultgemma":case"gemma3_text":case"gemma3n_text":case"gemma4_text":case"glm":case"helium":case"ernie4_5":case"hunyuan_v1_dense":case"falcon_h1":case"nemotron_h":case"ministral":case"ministral3":t.num_heads="num_key_value_heads",t.num_layers="num_hidden_layers",t.dim_kv="head_dim";break;case"openelm":t.num_heads="num_kv_heads",t.num_layers="num_transformer_layers",t.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":t.num_heads="num_heads",t.num_layers="num_layers",t.hidden_size="hidden_size";break;case"bloom":t.num_heads="n_head",t.num_layers="n_layer",t.hidden_size="hidden_size";break;case"mpt":t.num_heads="n_heads",t.num_layers="n_layers",t.hidden_size="d_model";break;case"exaone":t.num_heads="num_key_value_heads",t.num_layers="num_layers",t.dim_kv="head_dim",t.num_attention_heads="num_attention_heads";break;case"youtu":case"deepseek_v3":case"glm_moe_dsa":case"mistral4":t.num_heads="num_key_value_heads",t.num_layers="num_hidden_layers",t.dim_kv="qk_head_dim",t.num_attention_heads="num_attention_heads";break;case"t5":case"mt5":case"longt5":t.num_decoder_layers="num_decoder_layers",t.num_decoder_heads="num_heads",t.decoder_dim_kv="d_kv",t.num_encoder_layers="num_layers",t.num_encoder_heads="num_heads",t.encoder_dim_kv="d_kv";break;case"bart":case"mbart":case"marian":case"whisper":case"lite-whisper":case"m2m_100":case"blenderbot":case"blenderbot-small":case"florence2_language":t.num_decoder_layers="decoder_layers",t.num_decoder_heads="decoder_attention_heads",t.decoder_hidden_size="d_model",t.num_encoder_layers="encoder_layers",t.num_encoder_heads="encoder_attention_heads",t.encoder_hidden_size="d_model";break;case"speecht5":t.num_decoder_layers="decoder_layers",t.num_decoder_heads="decoder_attention_heads",t.decoder_hidden_size="hidden_size",t.num_encoder_layers="encoder_layers",t.num_encoder_heads="encoder_attention_heads",t.encoder_hidden_size="hidden_size";break;case"trocr":t.num_encoder_layers=t.num_decoder_layers="decoder_layers",t.num_encoder_heads=t.num_decoder_heads="decoder_attention_heads",t.encoder_hidden_size=t.decoder_hidden_size="d_model";break;case"musicgen_decoder":t.num_encoder_layers=t.num_decoder_layers="num_hidden_layers",t.num_encoder_heads=t.num_decoder_heads="num_attention_heads",t.encoder_hidden_size=t.decoder_hidden_size="hidden_size";break;case"moonshine":t.num_decoder_layers="decoder_num_hidden_layers",t.num_decoder_heads="decoder_num_key_value_heads",t.num_encoder_layers="encoder_num_hidden_layers",t.num_encoder_heads="encoder_num_key_value_heads",t.encoder_hidden_size=t.decoder_hidden_size="hidden_size";break;case"cohere_asr":t.num_decoder_layers="num_hidden_layers",t.num_decoder_heads="num_key_value_heads",t.decoder_hidden_size="hidden_size",t.decoder_dim_kv="head_dim";let{num_hidden_layers:n,num_attention_heads:s,hidden_size:i}=e.encoder_config;r={num_encoder_layers:n,num_encoder_heads:s,encoder_hidden_size:i,encoder_dim_kv:e.head_dim};break;case"vision-encoder-decoder":let o=as(e.decoder),H="num_decoder_layers"in o,_=It(e,["model_type","is_encoder_decoder"]);return H?(_.num_decoder_layers=o.num_decoder_layers,_.num_decoder_heads=o.num_decoder_heads,_.decoder_hidden_size=o.decoder_hidden_size,_.num_encoder_layers=o.num_encoder_layers,_.num_encoder_heads=o.num_encoder_heads,_.encoder_hidden_size=o.encoder_hidden_size):(_.num_layers=o.num_layers,_.num_heads=o.num_heads,_.hidden_size=o.hidden_size),_}let a={...r,...It(e,["model_type","multi_query","is_encoder_decoder"])};for(let n in t)a[n]=e[t[n]];return a}function wH(e,t){e instanceof fH||(e=new fH(e));let r=t?.prefix??"past_key_values",a=r==="present"?"present":"past",n=new Set;if(["lfm2","lfm2_moe"].includes(e.model_type)){let{layer_types:s}=e;for(let i=0;i<s.length;++i)if(s[i]==="full_attention")n.add(`${r}.${i}.key`),n.add(`${r}.${i}.value`);else if(s[i]==="conv")n.add(`${a}_conv.${i}`);else throw new Error(`Unsupported layer type: ${s[i]}`);return n}else if(["granitemoehybrid","falcon_h1","nemotron_h"].includes(e.model_type)){let s=e,i=s.layer_types??s.layers_block_type,o=s.num_hidden_layers??i?.length;for(let H=0;H<o;++H)(!i||i[H]==="mamba")&&(n.add(`${a}_conv.${H}`),n.add(`${a}_ssm.${H}`)),(!i||i[H]==="attention")&&(n.add(`${r}.${H}.key`),n.add(`${r}.${H}.value`));return n}else if(["qwen3_next","qwen3_5_text","qwen3_5_moe_text","olmo_hybrid"].includes(e.model_type)){let{layer_types:s}=e;for(let i=0;i<s.length;++i)if(s[i]==="full_attention")n.add(`${r}.${i}.key`),n.add(`${r}.${i}.value`);else if(s[i]==="linear_attention")e.model_type==="olmo_hybrid"?(n.add(`${a}_conv.${i}.key`),n.add(`${a}_conv.${i}.value`),n.add(`${a}_conv.${i}.query`)):n.add(`${a}_conv.${i}`),n.add(`${a}_recurrent.${i}`);else throw new Error(`Unsupported layer type: ${s[i]}`);return n}else if(["gemma4","gemma4_text"].includes(e.model_type)){let s=e.model_type==="gemma4"?e.text_config:e,i=s.num_hidden_layers,o=s.num_kv_shared_layers??0,H=i-o;for(let _=0;_<H;++_)n.add(`${r}.${_}.key`),n.add(`${r}.${_}.value`);return n}else if(["lfm2_vl","qwen3_5","qwen3_5_moe","voxtral_realtime"].includes(e.model_type)){let s;return e.model_type==="voxtral_realtime"&&t?.session_name==="audio_encoder"?s=e.audio_config:s=e.text_config,wH(s,t)}return GZ(e,{prefix:r})}function GZ(e,{prefix:t="past_key_values"}={}){let r=new Set,a=e.normalized_config;if(a.is_encoder_decoder&&"num_encoder_heads"in a&&"num_decoder_heads"in a)for(let n=0;n<a.num_decoder_layers;++n)r.add(`${t}.${n}.encoder.key`),r.add(`${t}.${n}.encoder.value`),r.add(`${t}.${n}.decoder.key`),r.add(`${t}.${n}.decoder.value`);else if(a.multi_query)for(let n=0;n<a.num_layers;++n)r.add(`${t}.${n}.key_value`);else for(let n=0;n<a.num_layers;++n)r.add(`${t}.${n}.key`),r.add(`${t}.${n}.value`);return r}function Jb(e,t,r){return e?typeof e=="object"&&e!==null?e.hasOwnProperty(t)?+e[t]:e.hasOwnProperty(r)?+e[r]:0:+e:0}function Qb(e,t){let r=[];for(let a=0;a<t;++a)r.push(`${e}_data${a===0?"":"_"+a}`);return r}async function FZ(e,t,r,a){let n=`${t}${a}.onnx`,s=`${r.subfolder??""}/${n}`;return await oH(e,s,!0,r,Ie.IS_NODE_ENV)}async function ZZ(e,t,r,a,n,s={}){let i=`${t}${r}.onnx`,o=Ie.IS_NODE_ENV,H=[],_=Jb(n,i,t);if(_>0){if(_>NI)throw new Error(`The number of external data chunks (${_}) exceeds the maximum allowed value (${NI}).`);let c=Qb(i,_);for(let l of c){let d=`${a.subfolder??""}/${l}`;H.push(new Promise(async(h,$)=>{let m=await oH(e,d,!0,a,o);h(m instanceof Uint8Array?{path:l,data:m}:l)}))}}else s.externalData!==void 0&&(H=s.externalData.map(async c=>{if(typeof c.data=="string"){let l=await oH(e,c.data,!0,a);return{...c,data:l}}return c}));return Promise.all(H)}async function UZ(e,t,r,a=!1,n=void 0){let s=r.config?.["transformers.js_config"]??{},i=nA(r.device??s.device,t,{warn:g=>fe.info(g)}),o=FF(i),H=s.device_config??{};H.hasOwnProperty(i)&&(s={...s,...H[i]});let _=sA(r.dtype??s.dtype,t,i,{configDtype:s.dtype,warn:g=>fe.info(g)});if(oi.hasOwnProperty(_)){if(i==="webgpu"&&!Ie.IS_NODE_ENV&&_===it.fp16&&!await WF())throw new Error(`The device (${i}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${_}. Should be one of: ${Object.keys(it).join(", ")}`);let c=oi[_],l={...r.session_options};l.executionProviders??=o;let d=s.free_dimension_overrides;d?l.freeDimensionOverrides??=d:i.startsWith("webnn")&&!l.freeDimensionOverrides&&fe.warn(`WebNN does not currently support dynamic shapes and requires 'free_dimension_overrides' to be set in config.json, preferably as a field within config["transformers.js_config"]["device_config"]["${i}"]. When 'free_dimension_overrides' is not set, you may experience significant performance degradation.`);let h=FZ(e,t,r,c),$=r.use_external_data_format??s.use_external_data_format,m=await ZZ(e,t,c,r,$,l);if(m.length>0&&(!Ie.IS_NODE_ENV||m.some(g=>typeof g!="string"))&&(l.externalData=m),a&&i==="webgpu"){let g=wH(r.config,{prefix:"present",session_name:n});if(g.size>0&&!Zd()){let T={};for(let x of g)T[x]="gpu-buffer";l.preferredOutputLocation=T}}return{buffer_or_path:await h,session_options:l,session_config:{dtype:_,device:i}}}async function WZ(e,t,r,a=void 0){return Object.fromEntries(await Promise.all(Object.keys(t).map(async n=>{let s=a?.[n]??!1,{buffer_or_path:i,session_options:o,session_config:H}=await UZ(e,t[n],r,s,n),_=await tA(i,o,H);return[n,_]})))}function Yb(e){for(let t in e)aA(e[t])?e[t]=new j(e[t]):typeof e[t]=="object"&&Yb(e[t]);return e}async function xe(e,t){let r=KZ(e,t);try{let a=Object.fromEntries(Object.entries(r).map(([s,i])=>{let o=i.ort_tensor;return Ie.IS_NODE_ENV&&typeof Float16Array<"u"&&o.cpuData instanceof Float16Array&&(o.cpuData=new Uint16Array(o.cpuData.buffer)),[s,o]})),n=await rA(e,a);return Yb(n)}catch(a){let n=Object.fromEntries(Object.entries(r).map(([s,i])=>{let o={type:i.type,dims:i.dims,location:i.location};return o.location!=="gpu-buffer"&&(o.data=i.data),[s,o]}));throw fe.error(`An error occurred during model execution: "${a}".`),fe.error("Inputs given to model:",n),a}}function KZ(e,t){let r=Object.create(null),a=[];for(let i of e.inputNames){let o=t[i];if(!(o instanceof j)){a.push(i);continue}r[i]=Zd()?o.clone():o}if(a.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${a.join(", ")}.`);let n=Object.keys(t).length,s=e.inputNames.length;if(n>s){let i=Object.keys(t).filter(o=>!e.inputNames.includes(o));fe.warn(`WARNING: Too many inputs were provided (${n} > ${s}). The following inputs will be ignored: "${i.join(", ")}".`)}return r}function e7(e){return oa[e]?.text_only_sessions??null}function hT(e,t,r={}){let a=oa[e]??oa.default;return{sessions:a.sessions(t,r,r.textOnly??!1),cache_sessions:a.cache_sessions,optional_configs:a.optional_configs}}function Dp(e,{warn:t=!0}={}){let r=e.architectures||[];for(let a of r){let n=Ha.get(a);if(n!==void 0)return n}if(e.model_type){let a=Ha.get(e.model_type);if(a!==void 0)return a;for(let n of Object.values(ns))if(n.has(e.model_type)){let s=Ha.get(n.get(e.model_type));if(s!==void 0)return s}}if(t){let a=r.length>0?r.join(", "):"(none)";fe.warn(`[resolve_model_type] Architecture(s) not found in MODEL_TYPE_MAPPING: [${a}] for model type '${e.model_type}'. Falling back to EncoderOnly (single model.onnx file). If you encounter issues, please report at: ${TH}`)}return J.EncoderOnly}function Cp(e,{config:t=null,cache_dir:r=null,local_files_only:a=!1,revision:n="main"}={}){if(t!==null)return ls.from_pretrained(e,{config:t,cache_dir:r,local_files_only:a,revision:n});let s=JSON.stringify([e,r,a,n]);return YS(s,()=>ls.from_pretrained(e,{config:t,cache_dir:r,local_files_only:a,revision:n}))}async function wp(e,{config:t=null,dtype:r=null,device:a=null,model_file_name:n=null}={}){t=await Cp(e,{config:t});let s=["config.json"],i=t["transformers.js_config"]??{},o=i.use_external_data_format,H="onnx",_=a??i.device,c=r??i.dtype,l=Dp(t),d=(m,S=null)=>{S=S??m;let I=nA(_,m),g=sA(c,m,I),T=oi[g]??"",x=`${S}${T}.onnx`,v=H?`${H}/${x}`:x;s.push(v);let k=Jb(o,x,m);for(let L of Qb(x,k)){let V=H?`${H}/${L}`:L;s.push(V)}},{sessions:h,optional_configs:$}=hT(l,t,{model_file_name:n});for(let[m,S]of Object.entries(h))d(m,S);if($)for(let m of Object.values($))s.push(m);return s}function t7(e){ns=e}function ld(e){if(e instanceof j)return e;if(e.length===0)throw Error("items must be non-empty");if(Array.isArray(e[0])){if(e.some(t=>t.length!==e[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 j("int64",BigInt64Array.from(e.flat().map(t=>BigInt(t))),[e.length,e[0].length])}else return new j("int64",BigInt64Array.from(e.map(t=>BigInt(t))),[1,e.length])}function fT(e){return new j("bool",[e],[1])}function yS(e,t){let r=Ha.get(e),a=!1,n=t?.architectures?.[0];if(n&&n!==e&&e?.endsWith("ForCausalLM")&&n.endsWith("ForConditionalGeneration")){let o=Ha.get(n);o!==void 0&&(r=o,a=!0)}let s=vS[r]??vS.default,i=oa[r]??oa.default;return{typeConfig:{...s,...i},textOnly:a,modelType:r}}async function Xo(e,t){let{encoder_outputs:r,input_ids:a,decoder_input_ids:n,decoder_attention_mask:s,...i}=t;if(!r){let o=It(t,e.sessions.model.inputNames);r=(await Da(e,o)).last_hidden_state}return i.input_ids=n,i.encoder_hidden_states=r,e.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(i.encoder_attention_mask=t.attention_mask),s&&!i.attention_mask&&(i.attention_mask=s),await _a(e,i,!0)}async function Da(e,t){let r=e.sessions.model,a=It(t,r.inputNames);if(r.inputNames.includes("inputs_embeds")&&!a.inputs_embeds){if(!t.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");a.inputs_embeds=await e.encode_text({input_ids:t.input_ids})}if(r.inputNames.includes("token_type_ids")&&!a.token_type_ids){if(!a.input_ids)throw new Error("Both `input_ids` and `token_type_ids` are missing in the model inputs.");a.token_type_ids=Xd(a.input_ids)}if(r.inputNames.includes("pixel_mask")&&!a.pixel_mask){if(!a.pixel_values)throw new Error("Both `pixel_values` and `pixel_mask` are missing in the model inputs.");let n=a.pixel_values.dims;a.pixel_mask=Kt([n[0],n[2],n[3]])}return await xe(r,a)}async function r7(e,t){let r=await e.encode(t);return await e.decode(r)}function ud(e,t){let r=Object.create(null);for(let a in e)if(a.startsWith("present")){let n=a.replace("present_ssm","past_ssm").replace("present_conv","past_conv").replace("present_recurrent","past_recurrent").replace("present","past_key_values");a.includes("encoder")&&t?r[n]=t[n]:r[n]=e[a]}return t?(t.update(r),t):new MH(r)}function a7(e){let t={};for(let r of["cross_attentions","encoder_attentions","decoder_attentions"])for(let a in e)a.startsWith(r)&&(r in t||(t[r]=[]),t[r].push(e[a]));return t}function ET(e,t){return e.map(r=>typeof r=="number"?r:t[r]??0)}function Bp(e,t,r){if(r&&Object.keys(r).length>0)return Object.assign(t,r),r;let a=e.sessions.decoder_model_merged??e.sessions.model,n=(t[e.main_input_name]??t.attention_mask)?.dims?.[0]??1,s=wH(e.config),i=e.config?.normalized_config?.num_heads,o={batch_size:n};typeof i=="number"&&(o["batch_size x num_heads"]=n*i);let H=Object.create(null);for(let _ of a.inputMetadata){if(!s.has(_.name))continue;let c=ET(_.shape,o),l=c.reduce(($,m)=>$*m,1),d=Hi[_.type],h=new j(_.type,new d(l),c);t[_.name]=h,H[_.name]=h}return r?(r.update(H),r):new MH(H)}async function _a(e,t,r=!1){let a=e.sessions[r?"decoder_model_merged":"model"],{past_key_values:n,...s}=t;if(a.inputNames.includes("use_cache_branch")&&(s.use_cache_branch=fT(n!=null&&Object.keys(n).length>0)),a.inputNames.includes("position_ids")&&s.attention_mask&&!s.position_ids){let o=["paligemma","gemma3_text","gemma3"].includes(e.config.model_type)?1:0;s.position_ids=i7(s,n,o)}a.inputNames.includes("num_logits_to_keep")&&!s.num_logits_to_keep&&(s.num_logits_to_keep=new j("int64",[0n],[])),Bp(e,s,n);let i=It(s,a.inputNames);return await xe(a,i)}async function $T(e,{encode_function:t,merge_function:r,modality_input_names:a,modality_output_name:n,input_ids:s=null,attention_mask:i=null,position_ids:o=null,inputs_embeds:H=null,past_key_values:_=null,generation_config:c=null,logits_processor:l=null,...d}){if(!H){H=await e.encode_text({input_ids:s,...d});let $=It(d,a);if(Object.keys($).length>0){if(s.dims[1]!==1){let m=await t({...$,...d});({inputs_embeds:H,attention_mask:i}=r({[n]:m,inputs_embeds:H,input_ids:s,attention_mask:i}))}else if(_&&s.dims[1]===1){let m=s.dims[1],S=_.get_seq_length();i=Ue([Kt([s.dims[0],S]),i.slice(null,[i.dims[1]-m,i.dims[1]])],1)}}}if(!o&&["qwen2_vl","qwen2_vl_text","qwen2_5_vl","qwen2_5_vl_text","qwen3_vl","qwen3_vl_text","qwen3_vl_moe","qwen3_vl_moe_text","qwen3_5","qwen3_5_text","qwen3_5_moe","qwen3_5_moe_text","glm_ocr","glm_ocr_text"].includes(e.config.model_type)){let{image_grid_thw:$,video_grid_thw:m}=d;[o]=e.get_rope_index(s,$,m,i)}return await _a(e,{inputs_embeds:H,past_key_values:_,attention_mask:i,position_ids:o,generation_config:c,logits_processor:l},!0)}async function n7(e,t){return await $T(e,{...t,modality_input_names:["audio_values","input_features"],modality_output_name:"audio_features",encode_function:e.encode_audio.bind(e),merge_function:e._merge_input_ids_with_audio_features.bind(e)})}async function s7(e,t){return await $T(e,{...t,modality_input_names:["pixel_values"],modality_output_name:"image_features",encode_function:e.encode_image.bind(e),merge_function:e._merge_input_ids_with_image_features.bind(e)})}function mT(e,t=0){let[r,a]=e.dims,n=e.data,s=new BigInt64Array(n.length);for(let i=0;i<r;++i){let o=i*a,H=BigInt(t);for(let _=0;_<a;++_){let c=o+_;n[c]===0n?s[c]=BigInt(1):(s[c]=H,H+=n[c])}}return{data:s,dims:e.dims}}function i7(e,t=null,r=0){let{input_ids:a,inputs_embeds:n,attention_mask:s}=e,{data:i,dims:o}=mT(s,r),H=new j("int64",i,o);if(t){let _=-(a??n).dims.at(1);H=H.slice(null,[_,null])}return H}function ni(e,t,r,a){let n=r.past_key_values?r.past_key_values.get_seq_length():0;if((e.sessions.decoder_model_merged??e.sessions.model)?.inputNames.includes("num_logits_to_keep")&&!r.num_logits_to_keep&&(r.num_logits_to_keep=new j("int64",[1n],[])),!r.attention_mask){let i;for(let o of["input_ids","inputs_embeds","position_ids"])if(r[o]){i=r[o].dims;break}if(!i)throw new Error("attention_mask is not provided, and unable to infer its shape from model inputs.");r.attention_mask=Kt([i[0],n+i[1]])}if(r.past_key_values){let{input_ids:i,attention_mask:o}=r;o&&o.dims[1]>i.dims[1]||n<i.dims[1]&&(r.input_ids=i.slice(null,[n,null]))}return r}function $H(e,t,r,a){return r.past_key_values&&(t=t.map(n=>[n.at(-1)])),{...r,decoder_input_ids:ld(t)}}function zo(e,...t){return e.config.is_encoder_decoder?$H(e,...t):ni(e,...t)}function IT({modality_token_id:e,inputs_embeds:t,modality_features:r,input_ids:a,attention_mask:n}){let s=a.tolist().map(_=>_.reduce((c,l,d)=>(l==e&&c.push(d),c),[])),i=s.reduce((_,c)=>_+c.length,0),o=r.dims[0];if(i!==o)throw new Error(`Number of tokens and features do not match: tokens: ${i}, features ${o}`);let H=0;for(let _=0;_<s.length;++_){let c=s[_],l=t[_];for(let d=0;d<c.length;++d)l[c[d]].data.set(r[H++].data)}return{inputs_embeds:t,attention_mask:n}}function Mp({image_token_id:e,inputs_embeds:t,image_features:r,input_ids:a,attention_mask:n}){return IT({modality_token_id:e,inputs_embeds:t,modality_features:r,input_ids:a,attention_mask:n})}function ST({audio_token_id:e,inputs_embeds:t,audio_features:r,input_ids:a,attention_mask:n}){return IT({modality_token_id:e,inputs_embeds:t,modality_features:r,input_ids:a,attention_mask:n})}async function o7(e,t,r){return Object.fromEntries(await Promise.all(Object.keys(t).map(async a=>{let n=await jr(e,t[a],!1,r);return[a,n]})))}function c7(e,t){let{text_config:r,audio_config:a}=e.config,n=e.sessions.audio_encoder,{num_mel_bins:s,hidden_size:i}=a,o=s+i,H=new MH,_=wH(a),c={batch_size:1},l="float32";for(let m of n.inputMetadata){if(m.name==="past_padding_cache"){l=m.type;continue}if(!_.has(m.name))continue;let S=ET(m.shape,c),I=S.reduce((T,x)=>T*x,1),g=Hi[m.type];H[m.name]=new j(m.type,new g(I),S)}let d=Hi[l],h=new j(l,new d(o*CS),[1,o,CS]),$=t[Symbol.asyncIterator]?.()??t[Symbol.iterator]?.();if(!$)throw new Error("input_features must be iterable or async iterable");return{encoder_session:n,enc_kv_cache:H,enc_padding_cache:h,enc_past_seq_len:0,audio_embed_queue:[],audio_embed_total_tokens:0,audio_queue_offset:0,audio_consumed:0,stream_exhausted:!1,chunks_iter:$,text_hidden_size:r.hidden_size}}async function l7(e,t){let r=t.dims[2],a=Math.floor((_7+r-3)/2)+1,n=new j("int64",BigInt64Array.from({length:a},(c,l)=>BigInt(e.enc_past_seq_len+l)),[1,a]),s=e.enc_past_seq_len+a,i=Kt([1,s]),{audio_embeds:o,present_padding_cache:H,..._}=await xe(e.encoder_session,{input_features:t,attention_mask:i,position_ids:n,past_padding_cache:e.enc_padding_cache,...e.enc_kv_cache});e.enc_padding_cache.location==="gpu-buffer"&&e.enc_padding_cache.dispose(),e.enc_padding_cache=H;for(let c in _)if(c.startsWith("present.")){let l=c.replace("present","past_key_values"),d=e.enc_kv_cache[l];d?.location==="gpu-buffer"&&d.dispose(),e.enc_kv_cache[l]=_[c]}return e.enc_past_seq_len=s,o}async function u7(e,t){for(;e.audio_embed_total_tokens<t&&!e.stream_exhausted;){let r=await e.chunks_iter.next();if(r.done){e.stream_exhausted=!0;break}let a=await l7(e,r.value);e.audio_embed_queue.push({data:a.data,tokens:a.dims[1]}),e.audio_embed_total_tokens+=a.dims[1]}}function d7(e,t,r){if(e.audio_embed_queue.length===0)return;let a=t.data,n=0,s=r;for(;s>0&&e.audio_embed_queue.length>0;){let i=e.audio_embed_queue[0],o=i.tokens-e.audio_queue_offset,H=Math.min(s,o),_=e.audio_queue_offset*e.text_hidden_size;for(let c=0;c<H*e.text_hidden_size;++c)a[n*e.text_hidden_size+c]+=i.data[_+c];n+=H,s-=H,e.audio_queue_offset+=H,e.audio_queue_offset>=i.tokens&&(e.audio_embed_queue.shift(),e.audio_queue_offset=0)}e.audio_consumed+=r-s}async function gr(e){return Array.isArray(e)||(e=[e]),await Promise.all(e.map(t=>Xt.read(t)))}async function os(e,t){return Array.isArray(e)||(e=[e]),await Promise.all(e.map(r=>typeof r=="string"||r instanceof URL?lg(r,t):r instanceof Float64Array?new Float32Array(r):r))}function Ed(e,t){t&&(e=e.map(i=>i|0));let[r,a,n,s]=e;return{xmin:r,ymin:a,xmax:n,ymax:s}}function N7(e){let t=e[0];return e[1]==="-"&&(t==="B"||t==="I"||t==="E"||t==="S")?[t,e.slice(2)]:["I",e]}function B7(e,t,r){let a=[],n=null;for(let s=0;s<e.length;++s){let[i,o]=N7(e[s].entity);n===o&&i!=="B"&&i!=="S"?(a[a.length-1].end=s+1,i==="E"&&(n=null)):(a.push({tag:o,start:s,end:s+1}),n=i==="S"?null:o)}return a.map(({tag:s,start:i,end:o})=>{let H=0,_=[];for(let c=i;c<o;++c)H+=e[c].score,_.push(t[e[c].index]);return{entity_group:s,score:H/(o-i),word:r.decode(_,{skip_special_tokens:!0})}})}function wS(e){return Array.isArray(e)&&e.every(t=>"role"in t&&"content"in t)}async function pB(e){if(!e)throw new Error("modelId is required");return(await sn(e,_i,{})).exists?[_i]:[]}async function Bi(e,{config:t=null,dtype:r=null,device:a=null,model_file_name:n=null,include_tokenizer:s=!0,include_processor:i=!0}={}){let o=await wp(e,{config:t,dtype:r,device:a,model_file_name:n});if(s){let H=await zd(e);o.push(...H)}if(i){let H=await pB(e);o.push(...H)}return o}async function Mi(e,t,r={}){e=dB[e]??e;let a=mH[e];if(!a)throw new Error(`Unsupported pipeline task: ${e}. Must be one of [${Object.keys(mH).join(", ")}]`);let{type:n}=a,o=await Bi(t,{...r,include_tokenizer:n!=="audio"&&n!=="image",include_processor:n!=="text"});if(e==="text-generation"){let H=await Cp(t,r),_=Dp(H),c=e7(_);if(c){let l=Object.values(c).map(d=>`onnx/${d}`);return o.filter(d=>!d.startsWith("onnx/")||l.some(h=>d.startsWith(h)))}}return o}async function M7(e,t=null,{progress_callback:r=null,config:a=null,cache_dir:n=null,local_files_only:s=!1,revision:i="main",device:o=null,dtype:H=null,subfolder:_="onnx",use_external_data_format:c=null,model_file_name:l=null,session_options:d={}}={}){e=dB[e]??e;let h=mH[e.split("_",1)[0]];if(!h)throw Error(`Unsupported pipeline: ${e}. Must be one of [${Object.keys(mH)}]`);t||(t=h.default.model,fe.info(`No model specified. Using default model: "${t}".`),!H&&h.default.dtype&&(H=h.default.dtype));let $=await Mi(e,t,{device:o,dtype:H}),m={};r&&(await Promise.all($.map(async Q=>sn(t,Q)))).forEach((Q,z)=>{Q.exists&&(m[$[z]]={loaded:0,total:Q.size??0})});let S={progress_callback:r?new Qu(r,m):void 0,config:a,cache_dir:n,local_files_only:s,revision:i,device:o,dtype:H,subfolder:_,use_external_data_format:c,model_file_name:l,session_options:d},I=$.includes("tokenizer.json"),g=$.includes("preprocessor_config.json"),T=h.model,x;if(Array.isArray(T)){let X=a??await ls.from_pretrained(t,S),{model_type:Q}=X,z=T.find(M=>M.supports(Q));if(!z)throw Error(`Unsupported model type "${Q}" for task "${e}". None of the candidate model classes support this type.`);x=z.from_pretrained(t,{...S,config:X})}else x=T.from_pretrained(t,S);let[v,k,L]=await Promise.all([I?we.from_pretrained(t,S):null,g?zb.from_pretrained(t,S):null,x]),V={task:e,model:L};v&&(V.tokenizer=v),k&&(V.processor=k),xa(r,{status:"ready",task:e,model:t});let K=h.pipeline;return new K(V)}async function R7(e,{num_frames:t=null,fps:r=null}={}){if(!Ie.IS_BROWSER_ENV)throw new Error("`load_video` is currently only supported in browser environments.");if(t==null&&r==null)throw new Error("Either num_frames or fps must be provided.");let a=[],n=document.createElement("video");if(n.crossOrigin="anonymous",n.muted=!0,typeof e=="string")n.src=e;else if(e instanceof Blob)n.src=URL.createObjectURL(e);else if(e instanceof HTMLVideoElement)n.src=e.src;else throw new Error("Invalid URL or video element provided.");if(await new Promise(l=>n.onloadedmetadata=l),n.seekable.start(0)===n.seekable.end(0)){let d=await(await ge.fetch(n.src)).blob();n.src=URL.createObjectURL(d),await new Promise(h=>n.onloadedmetadata=h)}let s=n.duration,i,o;t!=null?(i=t,o=t===1?0:s/(t-1)):(o=1/r,i=Math.floor(s/o));let H=[];for(let l=0;l<i;++l)H.push(t===1?s/2:l*o);let _=document.createElement("canvas");_.width=n.videoWidth,_.height=n.videoHeight;let c=_.getContext("2d",{willReadFrequently:!0});for(let l of H){n.currentTime=l,await new Promise(m=>{n.onseeked=m}),c.drawImage(n,0,0,_.width,_.height);let d=c.getImageData(0,0,_.width,_.height),h=new Xt(d.data,_.width,_.height,4),$=new af(h,l);a.push($)}return n.remove(),new EB(a,s)}async function Oc(e,t,r={}){let a=await hs(r?.cache_dir);if(!a)return{allCached:!1,files:t.map(i=>({file:i,cached:!1}))};let n=await Promise.all(t.map(async s=>{let{localPath:i,proposedCacheKey:o}=di(e,s,r,a),H=await pi(a,i,o);return{file:s,cached:!!H}}));return{allCached:n.every(s=>s.cached),files:n}}async function $B(e,t,r={}){let a=await hs(r?.cache_dir);if(!a)return!1;let{localPath:n,proposedCacheKey:s}=di(e,t,r,a);return!!await pi(a,n,s)}async function O7(e,t={}){if(!e)throw new Error("modelId is required");if(!await $B(e,"config.json",t))return!1;let r=await Bi(e,t);return(await Oc(e,r,t)).allCached}async function G7(e,t={}){if(!e)throw new Error("modelId is required");let r=await Bi(e,t);return await Oc(e,r,t)}async function F7(e,t,r={}){if(!e)throw new Error("task is required");if(!t)throw new Error("modelId is required");if(!await $B(t,"config.json",r))return!1;let a=await Mi(e,t,r);return(await Oc(t,a,r)).allCached}async function Z7(e,t,r={}){if(!e)throw new Error("task is required");if(!t)throw new Error("modelId is required");let a=await Mi(e,t,r);return await Oc(t,a,r)}async function mB(e,t,r={}){let a=await hs(r?.cache_dir);if(!a)return{filesDeleted:0,filesCached:0,files:t.map(s=>({file:s,deleted:!1,wasCached:!1}))};if(!a.delete)throw new Error("Cache does not support delete operation");let n=await Promise.all(t.map(async s=>{let{localPath:i,proposedCacheKey:o}=di(e,s,r,a),_=!!await pi(a,i,o),c=!1;if(_){let l=await a.delete(o),d=!l&&o!==i?await a.delete(i):!1;c=l||d}return{file:s,deleted:c,wasCached:_}}));return{filesDeleted:n.filter(s=>s.deleted).length,filesCached:n.filter(s=>s.wasCached).length,files:n}}async function U7(e,t={}){if(!e)throw new Error("modelId is required");let r=await Bi(e,t);return await mB(e,r,t)}async function W7(e,t,r={}){if(!e)throw new Error("task is required");if(!t)throw new Error("modelId is required");let a=await Mi(e,t,r);return await mB(t,a,r)}async function V7(e,{config:t=null,model_file_name:r=null,revision:a="main",cache_dir:n=null,local_files_only:s=!1}={}){t=await Cp(e,{config:t,cache_dir:n,local_files_only:s,revision:a});let i="onnx",o=Dp(t),{sessions:H}=hT(o,t,{model_file_name:r}),_=Object.values(H),c={revision:a,cache_dir:n,local_files_only:s};return(await Promise.all(K7.map(async d=>{let h=oi[d]??"",$=await Promise.all(_.map(async m=>{let S=`${i}/${m}${h}.onnx`;return(await sn(e,S,c)).exists}));return{dtype:d,available:$.every(Boolean)}}))).filter(d=>d.available).map(d=>d.dtype)}var MS,en,PS,Xa,ts,ei,iF,ig,og,Hg,pH,Wt,uO,Xn,us,dO,$d,Hs,kS,rH,pO,vK,IH,RS,OS,md,Id,hO,fO,EO,$O,mO,IO,SO,LO,Ie,Sd,aH,AO,lI,gO,bO,ur,uI,ge,zt,Qu,fe,yO,hI,DO,CO,FS,wO,NO,fI,BO,sH,Ld,SH,MO,PO,kO,RO,OO,GO,mr,Ad,FO,ZS,EI,ZO,UO,ci,WO,ca,KO,VO,jO,qO,XO,zO,JO,QO,YO,LH,e9,t9,r9,a9,n9,s9,i9,o9,H9,_9,c9,l9,u9,d9,p9,h9,US,E9,Sr,$9,m9,I9,S9,L9,A9,g9,b9,T9,x9,v9,y9,D9,C9,w9,N9,B9,M9,P9,k9,R9,O9,WS,F9,AH,Z9,$I,mI,U9,W9,Lu,K9,V9,q9,II,X9,z9,J9,Q9,Y9,SI,eG,tG,aG,nG,li,sG,iG,oG,HG,_G,cG,lG,uG,dG,pG,jS,fG,Lr,EG,$G,mG,IG,SG,LG,AG,gG,bG,TG,xG,vG,yG,DG,CG,wG,NG,BG,MG,PG,qS,RG,OG,Z,cr,GG,FG,Ar,WG,KG,VG,jG,qG,XG,zG,JG,nr,QG,gI,zn,ds,YG,e6,bI,t6,TI,r6,js,a6,n6,s6,i6,o6,H6,_6,c6,l6,u6,vI,yI,Vr,me,tt,ie,pe,I6,mt,Ys,Ae,CI,qe,ze,je,qa,L6,ut,A6,g6,B6,M6,iH,gH,Gr,ui,P6,k6,JS,R6,NI,O6,QS,U6,PI,kI,K6,V6,Au,Ro,nL,eF,tF,sF,sL,bd,oF,HF,_F,cF,be,hi,lF,HH,qs,Sa,Ya,OI,iL,oL,uF,HL,dF,gu,$t,_L,Xe,pF,cL,lL,hF,Oo,uL,dL,pL,hL,fL,fF,Ja,ri,bu,EL,EF,$L,mL,$F,ar,Td,Er,IL,_H,Tu,an,nn,va,ya,SL,LL,mF,xd,IF,SF,LF,AF,gF,gL,on,vd,bL,xu,vu,TL,bF,xL,vL,FI,TF,yu,td,ZI,tr,yL,Go,UI,WI,Du,KI,Cu,DL,wu,CL,yd,Nu,Fo,Xs,Bu,VI,jI,qI,Dd,ke,Hn,rr,cH,Ce,Cd,wL,xF,XI,zI,JI,Zo,La,QI,NL,vF,Qa,Qo,rs,ii,lH,wd,Nd,rd,fs,Bd,BL,ML,yF,YI,eS,tS,rS,PL,aS,wt,kL,Mu,ad,Pu,nS,ku,sS,Ru,Ou,Gu,iS,RL,DF,OL,zs,oS,GL,CF,HS,Md,Pd,Aa,_S,Fu,uH,kd,Rd,Zu,Od,Gd,Fd,FL,ga,_r,Jn,Js,Qs,Uo,Uu,Wo,Ka,Va,cS,ZL,UL,WL,KL,VL,jL,qL,XL,Wu,lS,zL,wF,JL,nd,sd,QL,NF,BF,MF,RF,OF,lr,id,_s,uS,GF,dS,Qn,pS,lt,ba,rn,UF,Ku,WF,it,hS,fS,oi,Hi,j,Ko,XF,he,uA,dA,pA,hA,fA,EA,$A,mA,IA,SA,LA,AA,gA,bA,TA,xA,vA,yA,DA,CA,wA,NA,BA,MA,PA,kA,RA,Yd,OA,GA,FA,ZA,UA,WA,KA,VA,jA,qA,XA,zA,JA,YF,QA,YA,eg,Yo,eZ,rZ,mS,aZ,tg,rg,ag,we,TH,ep,_i,ng,sg,Ne,od,vt,tp,lg,sZ,iZ,pg,hg,rp,fg,Eg,dZ,ap,$g,np,sp,ip,mg,Ig,op,Sg,Lg,Ag,gg,bg,Tg,xg,sr,vg,pZ,yg,za,Dg,Ta,hZ,fZ,Xt,EZ,Ee,hH,Mg,Pg,kg,Rg,_p,Og,cp,Gg,lp,Fg,up,Zg,Ug,vH,Wg,dp,Kg,Vg,jg,pp,hp,qg,Xg,zg,Hd,Jg,Qg,Yg,eb,yH,tb,rb,fp,ab,Ep,nb,$p,sb,mp,ib,Ip,ob,Hb,DH,_b,cb,er,xZ,qu,Yn,Xu,lb,ub,db,pb,eH,Sp,hb,Lp,fb,Eb,$b,Ap,mb,Ib,Sb,gp,Lb,Dt,Ab,gb,bb,Tb,CH,xb,vb,yb,_d,Db,Cb,wb,Nb,bS,Bb,Mb,Pb,es,kb,TS,NZ,Rb,Ob,Gb,bp,Fb,Tp,xp,Zb,Ub,Wb,jo,BZ,MZ,Kb,xS,zu,qo,kZ,RZ,Vb,jb,qb,Xb,zb,fH,ls,dt,de,ot,pt,Nt,cn,VZ,pr,NH,EH,eT,tT,rT,vp,aT,nT,sT,iT,oT,HT,_T,cT,jZ,qZ,lT,Es,yp,dT,pT,XZ,BH,zZ,JZ,QZ,YZ,MH,J,oa,ns,vS,Ha,Np,cs,C,Pp,$s,LT,AT,gT,bT,PH,TT,xT,kH,vT,yT,RH,DT,CT,OH,wT,NT,fi,BT,MT,PT,GH,kT,RT,ln,OT,GT,FT,ZT,UT,FH,WT,KT,ZH,VT,jT,UH,qT,XT,un,zT,JT,QT,YT,ex,H7,DS,kp,Rp,Op,tx,Gp,rx,Ei,ax,Fp,Zp,Ca,nx,sx,Up,ix,ox,WH,Hx,_x,KH,cx,lx,VH,ux,dx,jH,px,hx,qH,fx,Ex,dn,$x,mx,Ix,Sx,Lx,XH,Ax,gx,zH,bx,Tx,JH,xx,vx,ms,QH,yx,Dx,Wp,Kp,$i,Cx,Vp,jp,pn,wx,Nx,Bx,Mx,Px,YH,kx,Rx,hn,Ox,Gx,Fx,Zx,Ux,qp,Wx,e_,Kx,Vx,Xp,jx,zp,qx,mi,Xx,zx,Jx,t_,Jp,r_,Qx,Yx,a_,ev,tv,Qp,rv,Yp,av,fn,nv,sv,iv,ov,Hv,eh,_v,n_,cv,lv,s_,uv,dv,En,pv,hv,fv,Ev,$v,i_,mv,Iv,Is,Sv,Lv,Av,gv,Ss,bv,Tv,xv,vv,o_,yv,Dv,H_,Cv,wv,__,Nv,Bv,c_,Mv,Pv,th,kv,l_,Rv,Ov,u_,Gv,Fv,rh,Kr,Zv,Uv,ah,Wv,nh,Kv,sh,Ii,Vv,d_,jv,p_,qv,Xv,h_,zv,Jv,ih,f_,oh,E_,Hh,Qv,$_,Yv,ey,m_,ty,ry,I_,ay,ny,S_,sy,iy,L_,oy,Hy,A_,_y,cy,g_,ly,uy,b_,dy,py,T_,hy,fy,_h,x_,Ey,ch,$y,lh,my,v_,Iy,Sy,y_,Ly,Ay,ua,gy,by,Ty,xy,vy,yy,Dy,Cy,D_,wy,Ny,uh,C_,By,My,w_,Py,ky,Si,Ry,dh,Oy,N_,Gy,Fy,Zy,B_,Uy,Wy,Ky,M_,Vy,jy,ph,qy,P_,Xy,zy,k_,Jy,Qy,R_,Yy,eD,O_,tD,rD,Ls,aD,nD,sD,iD,hh,oD,fh,HD,Eh,$h,_D,mh,Ih,Li,cD,Sh,Lh,G_,lD,uD,F_,dD,pD,As,hD,fD,ED,$D,Z_,mD,ID,Ai,SD,LD,AD,gi,gD,bD,TD,bi,xD,vD,yD,Ti,DD,CD,wD,U_,ND,BD,W_,MD,PD,gs,kD,RD,OD,GD,K_,FD,ZD,V_,UD,WD,$n,KD,VD,jD,qD,XD,j_,zD,JD,q_,QD,YD,Ah,eC,X_,tC,rC,gh,z_,aC,nC,J_,sC,iC,mn,oC,HC,_C,cC,lC,bh,uC,Q_,dC,pC,Y_,hC,fC,ec,EC,$C,tc,mC,IC,rc,SC,LC,ac,AC,gC,nc,bC,TC,sc,xC,vC,ic,yC,DC,CC,Th,wC,oc,NC,BC,Hc,MC,PC,_c,kC,RC,cc,OC,GC,xh,vh,lc,FC,ZC,uc,UC,WC,dc,KC,VC,pc,jC,qC,hc,XC,zC,fc,JC,QC,Ec,YC,ew,$c,yh,tw,rw,mc,Dh,aw,nw,Ic,sw,iw,Sc,ow,Hw,Ch,In,_w,cw,lw,uw,dw,Sn,pw,hw,fw,Ew,$w,Lc,mw,Iw,wh,Nh,Bh,Sw,Mh,Ph,Ac,Lw,Aw,xi,gw,bw,Tw,vi,xw,vw,yw,gc,Dw,kh,Cw,bc,ww,Nw,Bw,yi,Mw,Rh,Oh,Tc,Pw,kw,Di,Rw,Ow,Gw,Fw,bs,Zw,Uw,Ww,Kw,xc,Vw,jw,vc,qw,Xw,Gh,zw,Fh,Zh,Ci,Jw,Qw,Yw,yc,eN,tN,Dc,rN,aN,Cc,nN,sN,Uh,Wh,iN,wi,oN,HN,_N,Ts,cN,lN,uN,dN,wc,pN,hN,fN,Nc,EN,$N,Kh,mN,Bc,IN,SN,Vh,LN,jh,AN,qh,Xh,gN,bN,CS,_7,Ju,p7,zh,Jh,Ni,TN,xN,vN,Qh,Ln,yN,DN,CN,wN,NN,Yh,BN,h7,Mc,MN,ef,PN,An,kN,RN,ON,GN,FN,gn,ZN,UN,WN,KN,VN,Pc,jN,qN,tf,kc,XN,zN,f7,E7,$7,m7,JN,QN,YN,e2,t2,r2,a2,I7,n2,s2,i2,o2,H2,S7,_2,c2,l2,ss,u2,d2,p2,h2,f2,E2,$2,m2,L7,I2,S2,L2,A2,g2,b2,A7,T2,g7,Me,Pe,is,dd,x2,tH,v2,y2,D2,C2,w2,N2,B2,M2,pd,hd,fd,P2,k2,b7,R2,O2,T7,x7,G2,v7,F2,Z2,y7,D7,U2,C7,w7,rt,W2,K2,V2,j2,Rc,q2,X2,z2,J2,Q2,Y2,eB,tB,rB,aB,NS,rf,nB,sB,iB,oB,HB,_B,cB,lB,uB,mH,dB,P7,hB,BS,fB,k7,af,EB,K7,j7,SB=Qe(()=>{"use strict";MS=Dr(require("fs"),1),en=Dr(require("path"),1),PS=Dr(require("url"),1),Xa=Dr(require("fs"),1),ts=Dr(require("fs"),1),ei=Dr(require("path"),1),iF=Dr($$(),1);K$();ig=Dr(require("fs"),1),og=require("stream"),Hg=require("stream/promises"),pH=Dr(cI(),1),Wt={},uO=Object.defineProperty,Xn=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),us=(e,t)=>{for(var r in t)uO(e,r,{get:t[r],enumerable:!0})},dO="4.2.0",$d=typeof self<"u",Hs=!GS(MS.default),kS=!GS(en.default),rH=$d&&"caches"in self,pO=typeof globalThis.Deno<"u",vK=typeof globalThis.Bun<"u",IH=pO&&rH&&!Hs,RS=typeof process<"u",OS=RS&&process?.release?.name==="node"&&!IH,md=typeof window<"u"&&typeof window.document<"u",Id=$d&&["DedicatedWorkerGlobalScope","ServiceWorkerGlobalScope","SharedWorkerGlobalScope"].includes(self.constructor?.name),hO=md||Id||IH,fO=OS||typeof navigator<"u"&&"gpu"in navigator,EO=typeof navigator<"u"&&"ml"in navigator,$O=typeof crypto<"u"&&typeof crypto.getRandomValues=="function",mO=typeof chrome<"u"&&typeof chrome.runtime<"u"&&typeof chrome.runtime.id=="string",IO=typeof ServiceWorkerGlobalScope<"u"&&$d&&self instanceof ServiceWorkerGlobalScope,SO=()=>{if(typeof navigator>"u")return!1;let e=navigator.userAgent,r=(navigator.vendor||"").indexOf("Apple")>-1,a=!e.match(/CriOS|FxiOS|EdgiOS|OPiOS|mercury|brave/i)&&!e.includes("Chrome")&&!e.includes("Android");return r&&a},LO=SO(),Ie=Object.freeze({IS_BROWSER_ENV:md,IS_WEBWORKER_ENV:Id,IS_WEB_ENV:hO,IS_SERVICE_WORKER_ENV:IO,IS_DENO_WEB_RUNTIME:IH,IS_WEB_CACHE_AVAILABLE:rH,IS_WEBGPU_AVAILABLE:fO,IS_WEBNN_AVAILABLE:EO,IS_SAFARI:LO,IS_PROCESS_AVAILABLE:RS,IS_NODE_ENV:OS,IS_FS_AVAILABLE:Hs,IS_PATH_AVAILABLE:kS,IS_CRYPTO_AVAILABLE:$O,IS_CHROME_AVAILABLE:mO}),Sd=Hs&&kS,aH="./";if(Sd){let e=Object(Wt).url;e?aH=en.default.dirname(en.default.dirname(PS.default.fileURLToPath(e))):typeof __dirname<"u"&&(aH=en.default.dirname(__dirname))}AO=Sd?en.default.join(aH,"/.cache/"):null,lI="/models/",gO=Sd?en.default.join(aH,lI):lI,bO=typeof globalThis.fetch=="function"?globalThis.fetch.bind(globalThis):void 0,ur=Object.freeze({DEBUG:10,INFO:20,WARNING:30,ERROR:40,NONE:50}),uI=ur.WARNING,ge={version:dO,backends:{onnx:{}},get logLevel(){return uI},set logLevel(e){uI=e,ge.backends.onnx?.setLogLevel?.(e)},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(md||Id||IH),localModelPath:gO,useFS:Hs,useBrowserCache:rH,useFSCache:Hs,cacheDir:AO,useCustomCache:!1,customCache:null,useWasmCache:rH||Hs,cacheKey:"transformers-cache",experimental_useCrossOriginStorage:!1,fetch:bO};zt=class{constructor(){let e=function(...t){return e._call(...t)};return Object.setPrototypeOf(e,new.target.prototype)}_call(...e){throw Error("Must implement _call method in subclass")}};Qu=class extends zt{constructor(e,t){super(),this.callback=e,this.files_loading=t}_call(e){if(e.status==="progress"){this.files_loading[e.file]={loaded:e.loaded,total:e.total};let t=Object.values(this.files_loading).reduce((n,s)=>n+s.loaded,0),r=Object.values(this.files_loading).reduce((n,s)=>n+s.total,0),a=r>0?t/r*100:0;this.callback({status:"progress_total",name:e.name,progress:a,loaded:t,total:r,files:structuredClone(this.files_loading)})}this.callback(e)}};fe={error(...e){ge.logLevel<=ur.ERROR&&console.error(...e)},warn(...e){ge.logLevel<=ur.WARNING&&console.warn(...e)},info(...e){ge.logLevel<=ur.INFO&&console.log(...e)},debug(...e){ge.logLevel<=ur.DEBUG&&console.log(...e)},log(...e){this.info(...e)}},yO=class{constructor(e){this.trie=this._build_trie(e)}_build_trie(e){let t=Object.create(null);for(let r of e){let a=t;for(let n=0;n<r.length;++n){let s=r[n];a=a[s]??=Object.create(null)}a.end=r}return t}split(e){let t=[],r=e.length,a=0,n=0;for(;n<r;){let s=this.trie,i=null,o=n;for(;o<r&&(s=s[e[o]]);)s.end&&(i=s.end),++o;i?(n>a&&t.push(e.slice(a,n)),t.push(i),n+=i.length,a=n):++n}return a<r&&t.push(e.slice(a)),t}},hI=yO,DO=class{constructor(e){this.content=e.content,this.id=e.id,this.single_word=e.single_word??!1,this.lstrip=e.lstrip??!1,this.rstrip=e.rstrip??!1,this.special=e.special??!1,this.normalized=e.normalized??!this.special}},CO=DO,FS=(()=>{let e=[...Array.from({length:94},(n,s)=>s+33),...Array.from({length:12},(n,s)=>s+161),...Array.from({length:82},(n,s)=>s+174)],t=e.slice(),r=0;for(let n=0;n<256;++n)e.includes(n)||(e.push(n),t.push(256+r),r+=1);let a=t.map(n=>String.fromCharCode(n));return Object.fromEntries(e.map((n,s)=>[n,a[s]]))})(),wO=e=>Object.fromEntries(Object.entries(e).map(([t,r])=>[r,t])),NO=wO(FS),fI=".,!?\u2026\u3002\uFF0C\u3001\u0964\u06D4\u060C",BO=new Map([["(?i:'s|'t|'re|'ve|'m|'ll|'d)","(?:'([sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD]))"],["(?i:[sdmt]|ll|ve|re)","(?:[sS]|[dD]|[mM]|[tT]|[lL][lL]|[vV][eE]|[rR][eE])"],["[^\\r\\n\\p{L}\\p{N}]?+","[^\\r\\n\\p{L}\\p{N}]?"],["[^\\s\\p{L}\\p{N}]++","[^\\s\\p{L}\\p{N}]+"],["(?>\\p{Nd}{510})","(?:\\p{Nd}{510})"],["\\p{Nd}{3}+","(?:\\p{Nd}{3})+"],["\\G",""],[` ?[^(\\s|[${fI}])]+`,` ?[^\\s${fI}]+`]]),sH="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",Ld=e=>e.replace(/ \./g,".").replace(/ \?/g,"?").replace(/ \!/g,"!").replace(/ ,/g,",").replace(/ \' /g,"'").replace(/ n't/g,"n't").replace(/ 'm/g,"'m").replace(/ 's/g,"'s").replace(/ 've/g,"'ve").replace(/ 're/g,"'re"),SH=(e,t=!0)=>{if(e.Regex!==void 0){let r=e.Regex.replace(/\\([#&~])/g,"$1");r=r.replace(/\\A/g,"^").replace(/\\z/g,"$").replace(/\\Z/g,"(?=\\r?\\n?$)");for(let[a,n]of BO)r=r.replaceAll(a,n);try{return new RegExp(r,"gu")}catch(a){if(!(a instanceof SyntaxError)||!a.message.toLowerCase().includes("invalid property name"))throw a;let n=!1,s=r.replace(/(\\[pP])\{([^}=]+)\}/g,(i,o,H)=>{try{return new RegExp(`\\p{${H}}`,"u"),`${o}{${H}}`}catch{return n=!0,`${o}{Script=${H}}`}});if(!n)throw a;try{return new RegExp(s,"gu")}catch{throw a}}}else if(e.String!==void 0){let r=MO(e.String);return new RegExp(t?r:`(${r})`,"gu")}else return console.warn("Unknown pattern type:",e),null},MO=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),PO=(e,t,r)=>{let a=[],n=0;for(;n<e.length;){if(a.push(e[n]),(t.get(e[n])??r)!==r){++n;continue}for(;++n<e.length&&(t.get(e[n])??r)===r;)t.get(a.at(-1))!==r&&(a[a.length-1]+=e[n])}return a},kO=e=>e>=19968&&e<=40959||e>=13312&&e<=19903||e>=131072&&e<=173791||e>=173824&&e<=177983||e>=177984&&e<=178207||e>=178208&&e<=183983||e>=63744&&e<=64255||e>=194560&&e<=195103,RO=e=>Number.isInteger(e)||typeof e=="bigint",OO=e=>{let t=0;for(let r of e)++t;return t},GO=e=>ZS(e.toLowerCase()),mr=(...e)=>Array.prototype.concat.apply([],e),Ad=e=>new Map(Object.entries(e)),FO=(e,t)=>{let r=[],a=0;for(let n of e.matchAll(t)){let s=n[0];a<n.index&&r.push(e.slice(a,n.index)),s.length>0&&r.push(s),a=n.index+s.length}return a<e.length&&r.push(e.slice(a)),r},ZS=e=>e.replace(/\p{M}/gu,""),EI=(e,t,r=[])=>{if(!e||Array.isArray(e)||typeof e!="object")return`${t} must be a valid object`;for(let a of r)if(!(a in e))return`${t} must contain a "${a}" property`;return null},ZO=e=>e.match(/\S+/g)||[],UO=class{constructor(){let e=function(...t){return e._call(...t)};return Object.setPrototypeOf(e,new.target.prototype)}},ci=UO,WO=class extends ci{constructor(e){super(),this.config=e}_call(e){return this.normalize(e)}},ca=WO,KO=class extends ca{tokenize_chinese_chars(e){let t=[];for(let r=0;r<e.length;++r){let a=e[r],n=a.charCodeAt(0);kO(n)?(t.push(" "),t.push(a),t.push(" ")):t.push(a)}return t.join("")}strip_accents(e){return e.normalize("NFD").replace(/\p{Mn}/gu,"")}is_control(e){switch(e){case" ":case`
15
- `:case"\r":return!1;default:return/^\p{Cc}|\p{Cf}|\p{Co}|\p{Cs}$/u.test(e)}}clean_text(e){let t=[];for(let r of e){let a=r.charCodeAt(0);a===0||a===65533||this.is_control(r)||(/^\s$/.test(r)?t.push(" "):t.push(r))}return t.join("")}normalize(e){return this.config.clean_text&&(e=this.clean_text(e)),this.config.handle_chinese_chars&&(e=this.tokenize_chinese_chars(e)),this.config.lowercase?(e=e.toLowerCase(),this.config.strip_accents!==!1&&(e=this.strip_accents(e))):this.config.strip_accents&&(e=this.strip_accents(e)),e}},VO=KO,jO=class extends ca{constructor(e){super(e),this.charsmap=e.precompiled_charsmap??null}normalize(e){return e=e.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm,""),e=e.replace(/[\u0009\u000A\u000C\u000D\u00A0\u1680\u2000-\u200F\u2028\u2029\u202F\u205F\u2581\u3000\uFEFF\uFFFD]/gm," "),e.includes("\uFF5E")?e=e.split("\uFF5E").map(r=>r.normalize("NFKC")).join("\uFF5E"):e=e.normalize("NFKC"),e}},qO=jO,XO=class extends ca{constructor(e){super(e),this.normalizers=(e.normalizers??[]).map(t=>US(t))}normalize(e){return this.normalizers.reduce((t,r)=>r?r.normalize(t):t,e)}},zO=XO,JO=class extends ca{normalize(e){let t=SH(this.config.pattern??{});return t===null?e:e.replaceAll(t,this.config.content??"")}},QO=JO,YO=class extends ca{constructor(){super(...arguments),this.form="NFC"}normalize(e){return e=e.normalize(this.form),e}},LH=YO,e9=class extends LH{constructor(){super(...arguments),this.form="NFC"}},t9=e9,r9=class extends LH{constructor(){super(...arguments),this.form="NFD"}},a9=r9,n9=class extends LH{constructor(){super(...arguments),this.form="NFKC"}},s9=n9,i9=class extends LH{constructor(){super(...arguments),this.form="NFKD"}},o9=i9,H9=class extends ca{normalize(e){return this.config.strip_left&&this.config.strip_right?e=e.trim():(this.config.strip_left&&(e=e.trimStart()),this.config.strip_right&&(e=e.trimEnd())),e}},_9=H9,c9=class extends ca{normalize(e){return ZS(e)}},l9=c9,u9=class extends ca{normalize(e){return e.toLowerCase()}},d9=u9,p9=class extends ca{normalize(e){return e=this.config.prepend+e,e}},h9=p9;US=f9,E9=class extends ci{pre_tokenize(e,t){return(Array.isArray(e)?e.map(r=>this.pre_tokenize_text(r,t)):this.pre_tokenize_text(e,t)).flat()}_call(e,t){return this.pre_tokenize(e,t)}},Sr=E9,$9=class extends Sr{constructor(e){super(),this.config=e,this.add_prefix_space=this.config.add_prefix_space??!1,this.trim_offsets=this.config.trim_offsets??!1,this.use_regex=this.config.use_regex??!0,this.pattern=/'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+/gu,this.byte_encoder=FS,this.text_encoder=new TextEncoder}pre_tokenize_text(e,t){return this.add_prefix_space&&!e.startsWith(" ")&&(e=" "+e),(this.use_regex?e.match(this.pattern)||[]:[e]).map(a=>Array.from(this.text_encoder.encode(a),n=>this.byte_encoder[n]).join(""))}},m9=$9,I9=class extends Sr{pre_tokenize_text(e,t){return e.match(/\w+|[^\w\s]+/g)||[]}},S9=I9,L9=class extends Sr{constructor(e){super(),this.replacement=e.replacement??"\u2581",this.str_rep=e.str_rep||this.replacement,this.prepend_scheme=e.prepend_scheme??"always"}pre_tokenize_text(e,t){let{section_index:r=void 0}=t??{},a=e.replaceAll(" ",this.str_rep);return!a.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&r===0)&&(a=this.str_rep+a),[a]}},A9=L9,g9=class extends Sr{constructor(e){super(),this.config=e,this.pattern=SH(this.config.pattern??{},this.config.invert??!0)}pre_tokenize_text(e){return this.pattern===null?[]:this.config.invert?e.match(this.pattern)||[]:this.config.behavior?.toLowerCase()==="removed"?e.split(this.pattern).filter(t=>t):FO(e,this.pattern)}},b9=g9,T9=class extends Sr{constructor(e){super(),this.config=e,this.pattern=new RegExp(`[^${sH}]+|[${sH}]+`,"gu")}pre_tokenize_text(e){return e.match(this.pattern)||[]}},x9=T9,v9=class extends Sr{constructor(e){super(),this.config=e;let t=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(t,"gu")}pre_tokenize_text(e){return e.match(this.pattern)||[]}},y9=v9,D9=class extends Sr{constructor(){super(),this.pattern=new RegExp(`[^\\s${sH}]+|[${sH}]`,"gu")}pre_tokenize_text(e,t){return e.trim().match(this.pattern)||[]}},C9=D9,w9=class extends Sr{constructor(e){super(),this.config=e,this.pattern=SH(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(e){return this.pattern===null?[e]:[e.replaceAll(this.pattern,this.config.content??"")]}},N9=w9,B9=class extends Sr{constructor(e){super(),this.tokenizers=(e.pretokenizers??[]).map(t=>WS(t))}pre_tokenize_text(e,t){return this.tokenizers.reduce((r,a)=>a?a.pre_tokenize(r,t):r,[e])}},M9=B9,P9=class extends Sr{pre_tokenize_text(e){return ZO(e)}},k9=P9,R9=class extends Sr{constructor(e){super(),this.config=e,this._length=e.length}pre_tokenize_text(e){let t=[];for(let r=0;r<e.length;r+=this._length)t.push(e.slice(r,r+this._length));return t}},O9=R9;WS=G9,F9=class extends ci{constructor(e){super(),this.config=e,this.vocab=[],this.tokens_to_ids=new Map,this.unk_token_id=void 0,this.unk_token=void 0,this.end_of_word_suffix=void 0,this.fuse_unk=this.config.fuse_unk??!1}_call(e){let t=this.encode(e);return this.fuse_unk&&(t=PO(t,this.tokens_to_ids,this.unk_token_id)),t}},AH=F9,Z9=class extends AH{constructor(e){super(e),this.max_input_chars_per_word=100,this.tokens_to_ids=Ad(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.max_input_chars_per_word=e.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(let[t,r]of this.tokens_to_ids)this.vocab[r]=t}encode(e){let t=[];for(let r of e){let a=[...r];if(a.length>this.max_input_chars_per_word){t.push(this.unk_token);continue}let n=!1,s=0,i=[];for(;s<a.length;){let o=a.length,H=null;for(;s<o;){let _=a.slice(s,o).join("");if(s>0&&(_=this.config.continuing_subword_prefix+_),this.tokens_to_ids.has(_)){H=_;break}--o}if(H===null){n=!0;break}i.push(H),s=o}n?t.push(this.unk_token):t.push(...i)}return t}},$I=Z9,mI=class KS{constructor(t,r){this.is_leaf=t,this.children=r}static default(){return new KS(!1,new Map)}},U9=class{constructor(){this.root=mI.default()}extend(e){for(let t of e)this.push(t)}push(e){let t=this.root;for(let r of e){let a=t.children.get(r);a===void 0&&(a=mI.default(),t.children.set(r,a)),t=a}t.is_leaf=!0}*common_prefix_search(e){let t=this.root;if(t===void 0)return;let r="";for(let a of e){if(r+=a,t=t.children.get(a),t===void 0)return;t.is_leaf&&(yield r)}}},W9=U9,Lu=class VS{constructor(t,r,a,n,s){this.token_id=t,this.node_id=r,this.pos=a,this.length=n,this.score=s,this.prev=null,this.backtrace_score=0}clone(){let t=new VS(this.token_id,this.node_id,this.pos,this.length,this.score);return t.prev=this.prev,t.backtrace_score=this.backtrace_score,t}},K9=class{constructor(e,t,r){this.chars=Array.from(e),this.len=this.chars.length,this.bos_token_id=t,this.eos_token_id=r,this.nodes=[],this.begin_nodes=Array.from({length:this.len+1},()=>[]),this.end_nodes=Array.from({length:this.len+1},()=>[]);let a=new Lu(this.bos_token_id??0,0,0,0,0),n=new Lu(this.eos_token_id??0,1,this.len,0,0);this.nodes.push(a.clone()),this.nodes.push(n.clone()),this.begin_nodes[this.len].push(n),this.end_nodes[0].push(a)}insert(e,t,r,a){let n=this.nodes.length,s=new Lu(a,n,e,t,r);this.begin_nodes[e].push(s),this.end_nodes[e+t].push(s),this.nodes.push(s)}viterbi(){let e=this.len,t=0;for(;t<=e;){if(this.begin_nodes[t].length==0)return[];for(let i of this.begin_nodes[t]){i.prev=null;let o=0,H=null;for(let _ of this.end_nodes[t]){let c=_.backtrace_score+i.score;(H===null||c>o)&&(H=_.clone(),o=c)}if(H!==null)i.prev=H,i.backtrace_score=o;else return[]}++t}let r=[],n=this.begin_nodes[e][0].prev;if(n===null)return[];let s=n.clone();for(;s.prev!==null;)r.push(s.clone()),s=s.clone().prev.clone();return r.reverse(),r}piece(e){return this.chars.slice(e.pos,e.pos+e.length).join("")}tokens(){return this.viterbi().map(t=>this.piece(t))}token_ids(){return this.viterbi().map(t=>t.token_id)}},V9=K9;q9=class extends AH{constructor(e,t){super(e);let r=e.vocab.length;this.vocab=new Array(r),this.scores=new Array(r);for(let a=0;a<r;++a)[this.vocab[a],this.scores[a]]=e.vocab[a];this.unk_token_id=e.unk_id,this.unk_token=this.vocab[e.unk_id],this.tokens_to_ids=new Map(this.vocab.map((a,n)=>[a,n])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=t,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.min_score=j9(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new W9,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(e){let t=e.chars,r=1,a=0;for(;a<t.length;){let n=!1,s=[],i=t.slice(a).join(""),o=this.trie.common_prefix_search(i);for(let H of o){s.push(H);let _=this.tokens_to_ids.get(H),c=this.scores[_],l=OO(H);e.insert(a,l,c,_),!n&&l===r&&(n=!0)}n||e.insert(a,r,this.unk_score,this.unk_token_id),a+=r}}tokenize(e){let t=new V9(e,this.bos_token_id,this.eos_token_id);return this.populate_nodes(t),t.tokens()}encode(e){let t=[];for(let r of e){let a=this.tokenize(r);t.push(...a)}return t}},II=q9,X9=class{constructor(e=(r,a)=>r>a,t=1/0){this._heap=[],this._comparator=e,this._max_size=t}get size(){return this._heap.length}is_empty(){return this.size===0}peek(){return this._heap[0]}push(...e){return this.extend(e)}extend(e){for(let t of e)if(this.size<this._max_size)this._heap.push(t),this._sift_up();else{let r=this._smallest();this._comparator(t,this._heap[r])&&(this._heap[r]=t,this._sift_up_from(r))}return this.size}pop(){let e=this.peek(),t=this.size-1;return t>0&&this._swap(0,t),this._heap.pop(),this._sift_down(),e}replace(e){let t=this.peek();return this._heap[0]=e,this._sift_down(),t}_parent(e){return(e+1>>>1)-1}_left(e){return(e<<1)+1}_right(e){return e+1<<1}_greater(e,t){return this._comparator(this._heap[e],this._heap[t])}_swap(e,t){let r=this._heap[e];this._heap[e]=this._heap[t],this._heap[t]=r}_sift_up(){this._sift_up_from(this.size-1)}_sift_up_from(e){for(;e>0&&this._greater(e,this._parent(e));)this._swap(e,this._parent(e)),e=this._parent(e)}_sift_down(){let e=0;for(;this._left(e)<this.size&&this._greater(this._left(e),e)||this._right(e)<this.size&&this._greater(this._right(e),e);){let t=this._right(e)<this.size&&this._greater(this._right(e),this._left(e))?this._right(e):this._left(e);this._swap(e,t),e=t}}_smallest(){return 2**Math.floor(Math.log2(this.size))-1}},z9=X9,J9=class{constructor(e){this.capacity=e,this.cache=new Map}get(e){if(!this.cache.has(e))return;let t=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,t),t}put(e,t){this.cache.has(e)&&this.cache.delete(e),this.cache.set(e,t),this.cache.size>this.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}},Q9=J9,Y9=class extends AH{constructor(e){super(e),this.tokens_to_ids=Ad(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(let[r,a]of this.tokens_to_ids)this.vocab[a]=r;let t=Array.isArray(e.merges[0]);this.merges=t?e.merges:e.merges.map(r=>r.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((r,a)=>[JSON.stringify(r),a])),this.end_of_word_suffix=e.end_of_word_suffix,this.continuing_subword_suffix=e.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.max_length_to_cache=256,this.cache_capacity=1e4,this.cache=new Q9(this.cache_capacity)}clear_cache(){this.cache.clear()}bpe(e){if(e.length===0)return[];let t=this.cache.get(e);if(t!==void 0)return t;let r=Array.from(e);this.end_of_word_suffix&&(r[r.length-1]+=this.end_of_word_suffix);let a=[];if(r.length>1){let n=new z9((o,H)=>o.score<H.score),s={token:r[0],bias:0,prev:null,next:null},i=s;for(let o=1;o<r.length;++o){let H={bias:o/r.length,token:r[o],prev:i,next:null};i.next=H,this.add_node(n,i),i=H}for(;!n.is_empty();){let o=n.pop();if(o.deleted||!o.next||o.next.deleted)continue;if(o.deleted=!0,o.next.deleted=!0,o.prev){let _={...o.prev};o.prev.deleted=!0,o.prev=_,_.prev?_.prev.next=_:s=_}let H={token:o.token+o.next.token,bias:o.bias,prev:o.prev,next:o.next.next};H.prev?(H.prev.next=H,this.add_node(n,H.prev)):s=H,H.next&&(H.next.prev=H,this.add_node(n,H))}for(let o=s;o!==null;o=o.next)a.push(o.token)}else a=r;if(this.continuing_subword_suffix)for(let n=0;n<a.length-1;++n)a[n]+=this.continuing_subword_suffix;return e.length<this.max_length_to_cache&&this.cache.put(e,a),a}add_node(e,t){let r=this.bpe_ranks.get(JSON.stringify([t.token,t.next.token]));r!==void 0&&(t.score=r+t.bias,e.push(t))}encode(e){let t=[];for(let r of e){if(this.ignore_merges&&this.tokens_to_ids.has(r)){t.push(r);continue}let a=this.bpe(r);for(let n of a)if(this.tokens_to_ids.has(n))t.push(n);else if(this.byte_fallback){let s=Array.from(this.text_encoder.encode(n)).map(i=>`<0x${i.toString(16).toUpperCase().padStart(2,"0")}>`);s.every(i=>this.tokens_to_ids.has(i))?t.push(...s):this.unk_token!=null&&t.push(this.unk_token)}else this.unk_token!=null&&t.push(this.unk_token)}return t}},SI=Y9,eG=class extends AH{constructor(e,t){super(e);let r=e.vocab;this.tokens_to_ids=Ad(t.target_lang?r[t.target_lang]:r),this.bos_token=t.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=t.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=t.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=t.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(let[a,n]of this.tokens_to_ids)this.vocab[n]=a}encode(e){return e}},tG=eG;aG=rG,nG=class extends ci{constructor(e){super(),this.config=e}_call(e,...t){return this.post_process(e,...t)}},li=nG,sG=class extends li{post_process(e,t=null,r=!0){let a=t===null?this.config.single:this.config.pair,n=[],s=[];for(let i of a)"SpecialToken"in i?r&&(n.push(i.SpecialToken.id),s.push(i.SpecialToken.type_id)):"Sequence"in i&&(i.Sequence.id==="A"?(n=mr(n,e),s=mr(s,new Array(e.length).fill(i.Sequence.type_id))):i.Sequence.id==="B"&&(n=mr(n,t),s=mr(s,new Array(t.length).fill(i.Sequence.type_id))));return{tokens:n,token_type_ids:s}}},iG=sG,oG=class extends li{post_process(e,t=null){return{tokens:e,tokens_pair:t}}},HG=oG,_G=class extends li{constructor(e){super(e),this.sep=e.sep,this.cls=e.cls}post_process(e,t=null,r=!0){r&&(e=mr([this.cls[0]],e,[this.sep[0]]));let a=new Array(e.length).fill(0);if(t){let n=[],s=r?[this.sep[0]]:[];e=mr(e,n,t,s),a=mr(a,new Array(t.length+n.length+s.length).fill(1))}return{tokens:e,token_type_ids:a}}},cG=_G,lG=class extends li{constructor(e){super(e),this.sep=e.sep,this.cls=e.cls}post_process(e,t,r=!0){r&&(e=mr([this.cls[0]],e,[this.sep[0]]));let a=new Array(e.length).fill(0);if(t){let n=r?[this.sep[0]]:[],s=r?[this.sep[0]]:[];e=mr(e,n,t,s),a=mr(a,new Array(t.length+n.length+s.length).fill(1))}return{tokens:e,token_type_ids:a}}},uG=lG,dG=class extends li{constructor(e){super(e),this.processors=(e.processors??[]).map(t=>jS(t))}post_process(e,t=null,r=!0){let a={tokens:e,tokens_pair:t};for(let n of this.processors)a=n.post_process(a.tokens,a.tokens_pair,r);return a}},pG=dG;jS=hG,fG=class extends ci{constructor(e){super(),this.config=e,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets="trim_offsets"in e?e.trim_offsets:!1}_call(e){return this.decode(e)}decode(e){return this.decode_chain(e).join("")}},Lr=fG,EG=class extends Lr{constructor(e){super(e),this.byte_decoder=NO,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(e){let t=e.join(""),r=new Uint8Array([...t].map(a=>this.byte_decoder[a]));return this.text_decoder.decode(r)}decode_chain(e){let t=[],r=[];for(let a of e)this.added_tokens.find(n=>n.content===a)!==void 0?(r.length>0&&(t.push(this.convert_tokens_to_string(r)),r=[]),t.push(a)):r.push(a);return r.length>0&&t.push(this.convert_tokens_to_string(r)),t}},$G=EG,mG=class extends Lr{constructor(e){super(e),this.cleanup=e.cleanup}decode_chain(e){return e.map((t,r)=>{if(r!==0){let a=this.config.prefix;a&&t.startsWith(a)?t=t.replace(a,""):t=" "+t}return this.cleanup&&(t=Ld(t)),t})}},IG=mG,SG=class extends Lr{constructor(e){super(e),this.replacement=e.replacement??"\u2581"}decode_chain(e){let t=[];for(let r=0;r<e.length;++r){let a=e[r].replaceAll(this.replacement," ");r==0&&a.startsWith(" ")&&(a=a.substring(1)),t.push(a)}return t}},LG=SG,AG=class extends Lr{constructor(e){super(e),this.suffix=e.suffix??""}decode_chain(e){return e.map((t,r)=>t.replaceAll(this.suffix,r===e.length-1?"":" "))}},gG=AG,bG=class extends Lr{constructor(e){super(e),this.pad_token=e.pad_token??"",this.word_delimiter_token=e.word_delimiter_token??"",this.cleanup=e.cleanup}convert_tokens_to_string(e){if(e.length===0)return"";let t=[e[0]];for(let n=1;n<e.length;++n)e[n]!==t.at(-1)&&t.push(e[n]);let a=t.filter(n=>n!==this.pad_token).join("");return this.cleanup&&(a=Ld(a).replaceAll(this.word_delimiter_token," ").trim()),a}decode_chain(e){return[this.convert_tokens_to_string(e)]}},TG=bG,xG=class extends Lr{constructor(e){super(e),this.decoders=(e.decoders??[]).map(t=>qS(t))}decode_chain(e){return this.decoders.reduce((t,r)=>r.decode_chain(t),e)}},vG=xG,yG=class extends Lr{decode_chain(e){let t=SH(this.config.pattern),r=this.config.content??"";return t===null?e:e.map(a=>a.replaceAll(t,r))}},DG=yG,CG=class extends Lr{decode_chain(e){return[e.join("")]}},wG=CG,NG=class extends Lr{constructor(e){super(e),this.content=e.content??"",this.start=e.start??0,this.stop=e.stop??0}decode_chain(e){return e.map(t=>{let r=0;for(let n=0;n<this.start&&t[n]===this.content;++n){r=n+1;continue}let a=t.length;for(let n=0;n<this.stop;++n){let s=t.length-n-1;if(t[s]===this.content){a=s;continue}else break}return t.slice(r,a)})}},BG=NG,MG=class extends Lr{constructor(e){super(e),this.text_decoder=new TextDecoder}decode_chain(e){let t=[],r=[];for(let a of e){let n=null;if(a.length===6&&a.startsWith("<0x")&&a.endsWith(">")){let s=parseInt(a.slice(3,5),16);isNaN(s)||(n=s)}if(n!==null)r.push(n);else{if(r.length>0){let s=this.text_decoder.decode(Uint8Array.from(r));t.push(s),r=[]}t.push(a)}}if(r.length>0){let a=this.text_decoder.decode(Uint8Array.from(r));t.push(a),r=[]}return t}},PG=MG;qS=kG,RG=class{constructor(e,t){let r=EI(e,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(r)throw new Error(r);let a=EI(t,"Config");if(a)throw new Error(a);this.tokenizer=e,this.config=t,this.normalizer=US(this.tokenizer.normalizer),this.pre_tokenizer=WS(this.tokenizer.pre_tokenizer),this.model=aG(this.tokenizer.model,this.config),this.post_processor=jS(this.tokenizer.post_processor),this.decoder=qS(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];let n=[],s=[];this.added_tokens_map=new Map;for(let i of this.tokenizer.added_tokens){let o=new CO(i);if(this.added_tokens.push(o),this.model.tokens_to_ids.set(o.content,o.id),this.model.vocab[o.id]=o.content,o.special&&(this.special_tokens.push(o.content),this.all_special_ids.push(o.id)),this.added_tokens_map.set(o.content,o),o.normalized&&this.normalizer!==null){let H=this.normalizer(o.content);s.push(H),this.added_tokens_map.set(H,o)}else n.push(o.content)}(this.config.additional_special_tokens??[]).forEach(i=>{this.special_tokens.includes(i)||this.special_tokens.push(i)}),this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.splitter_unnormalized=new hI(n),this.splitter_normalized=new hI(s),this.remove_space=this.config.remove_space,this.clean_up_tokenization_spaces=this.config.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=this.config.do_lowercase_and_remove_accent??!1}encode(e,{text_pair:t=null,add_special_tokens:r=!0,return_token_type_ids:a=null}={}){let{tokens:n,token_type_ids:s}=this.tokenize_helper(e,{text_pair:t,add_special_tokens:r}),i=n.map(H=>this.added_tokens_map.get(H)?.id??this.model.tokens_to_ids.get(H)??this.model.unk_token_id),o={ids:i,tokens:n,attention_mask:new Array(i.length).fill(1)};return a&&s&&(o.token_type_ids=s),o}decode(e,t={}){if(!Array.isArray(e)||e.length===0||!RO(e[0]))throw Error("token_ids must be a non-empty array of integers.");let r=e.map(n=>this.model.vocab[Number(n)]??this.model.unk_token);t.skip_special_tokens&&(r=r.filter(n=>!this.special_tokens.includes(n)));let a=this.decoder?this.decoder(r):r.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(a=a.replaceAll(this.decoder.end_of_word_suffix," "),t.skip_special_tokens&&(a=a.trim())),(t.clean_up_tokenization_spaces??this.clean_up_tokenization_spaces)&&(a=Ld(a)),a}tokenize(e,{text_pair:t=null,add_special_tokens:r=!1}={}){return this.tokenize_helper(e,{text_pair:t,add_special_tokens:r}).tokens}encode_text(e){if(e===null)return null;let t=this.splitter_unnormalized.split(e);return t.forEach((r,a)=>{let n=this.added_tokens_map.get(r);n&&(n.lstrip&&a>0&&(t[a-1]=t[a-1].trimEnd()),n.rstrip&&a<t.length-1&&(t[a+1]=t[a+1].trimStart()))}),t.flatMap((r,a)=>{if(r.length===0)return[];if(this.added_tokens_map.has(r))return[r];if(this.remove_space===!0&&(r=r.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(r=GO(r)),this.normalizer!==null&&(r=this.normalizer(r)),r.length===0)return[];let n=this.splitter_normalized.split(r);return n.forEach((s,i)=>{let o=this.added_tokens_map.get(s);o&&(o.lstrip&&i>0&&(n[i-1]=n[i-1].trimEnd()),o.rstrip&&i<n.length-1&&(n[i+1]=n[i+1].trimStart()))}),n.flatMap(s=>{if(s.length===0)return[];if(this.added_tokens_map.has(s))return[s];let i=this.pre_tokenizer!==null?this.pre_tokenizer(s,{section_index:a}):[s];return this.model(i)})})}tokenize_helper(e,{text_pair:t=null,add_special_tokens:r=!0}){let a=this.encode_text(e),n=this.encode_text(t||null);return this.post_processor?this.post_processor(a,n,r):{tokens:mr(a??[],n??[])}}token_to_id(e){return this.model.tokens_to_ids.get(e)}id_to_token(e){return this.model.vocab[e]}get_added_tokens_decoder(){let e=new Map;for(let t of this.added_tokens)e.set(t.id,t);return e}get_vocab(e=!0){let t=new Map;for(let r=0;r<this.model.vocab.length;++r){let a=this.model.vocab[r];(e||!this.added_tokens_map.has(a))&&t.set(a,r)}return t}},OG=RG,Z=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",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",Comment:"Comment"}),cr=class{constructor(e,t){this.value=e,this.type=t}};GG=[["{%",Z.OpenStatement],["%}",Z.CloseStatement],["{{",Z.OpenExpression],["}}",Z.CloseExpression],["(",Z.OpenParen],[")",Z.CloseParen],["{",Z.OpenCurlyBracket],["}",Z.CloseCurlyBracket],["[",Z.OpenSquareBracket],["]",Z.CloseSquareBracket],[",",Z.Comma],[".",Z.Dot],[":",Z.Colon],["|",Z.Pipe],["<=",Z.ComparisonBinaryOperator],[">=",Z.ComparisonBinaryOperator],["==",Z.ComparisonBinaryOperator],["!=",Z.ComparisonBinaryOperator],["<",Z.ComparisonBinaryOperator],[">",Z.ComparisonBinaryOperator],["+",Z.AdditiveBinaryOperator],["-",Z.AdditiveBinaryOperator],["~",Z.AdditiveBinaryOperator],["*",Z.MultiplicativeBinaryOperator],["/",Z.MultiplicativeBinaryOperator],["%",Z.MultiplicativeBinaryOperator],["=",Z.Equals]],FG=new Map([["n",`
16
- `],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);Ar=class{type="Statement"},WG=class extends Ar{constructor(e){super(),this.body=e}type="Program"},KG=class extends Ar{constructor(e,t,r){super(),this.test=e,this.body=t,this.alternate=r}type="If"},VG=class extends Ar{constructor(e,t,r,a){super(),this.loopvar=e,this.iterable=t,this.body=r,this.defaultBlock=a}type="For"},jG=class extends Ar{type="Break"},qG=class extends Ar{type="Continue"},XG=class extends Ar{constructor(e,t,r){super(),this.assignee=e,this.value=t,this.body=r}type="Set"},zG=class extends Ar{constructor(e,t,r){super(),this.name=e,this.args=t,this.body=r}type="Macro"},JG=class extends Ar{constructor(e){super(),this.value=e}type="Comment"},nr=class extends Ar{type="Expression"},QG=class extends nr{constructor(e,t,r){super(),this.object=e,this.property=t,this.computed=r}type="MemberExpression"},gI=class extends nr{constructor(e,t){super(),this.callee=e,this.args=t}type="CallExpression"},zn=class extends nr{constructor(e){super(),this.value=e}type="Identifier"},ds=class extends nr{constructor(e){super(),this.value=e}type="Literal"},YG=class extends ds{type="IntegerLiteral"},e6=class extends ds{type="FloatLiteral"},bI=class extends ds{type="StringLiteral"},t6=class extends ds{type="ArrayLiteral"},TI=class extends ds{type="TupleLiteral"},r6=class extends ds{type="ObjectLiteral"},js=class extends nr{constructor(e,t,r){super(),this.operator=e,this.left=t,this.right=r}type="BinaryExpression"},a6=class extends nr{constructor(e,t){super(),this.operand=e,this.filter=t}type="FilterExpression"},n6=class extends Ar{constructor(e,t){super(),this.filter=e,this.body=t}type="FilterStatement"},s6=class extends nr{constructor(e,t){super(),this.lhs=e,this.test=t}type="SelectExpression"},i6=class extends nr{constructor(e,t,r){super(),this.operand=e,this.negate=t,this.test=r}type="TestExpression"},o6=class extends nr{constructor(e,t){super(),this.operator=e,this.argument=t}type="UnaryExpression"},H6=class extends nr{constructor(e=void 0,t=void 0,r=void 0){super(),this.start=e,this.stop=t,this.step=r}type="SliceExpression"},_6=class extends nr{constructor(e,t){super(),this.key=e,this.value=t}type="KeywordArgumentExpression"},c6=class extends nr{constructor(e){super(),this.argument=e}type="SpreadExpression"},l6=class extends Ar{constructor(e,t,r){super(),this.call=e,this.callerArgs=t,this.body=r}type="CallStatement"},u6=class extends nr{constructor(e,t,r){super(),this.condition=e,this.trueExpr=t,this.falseExpr=r}type="Ternary"};vI=class extends Error{},yI=class extends Error{},Vr=class{type="RuntimeValue";value;builtins=new Map;constructor(e=void 0){this.value=e}__bool__(){return new pe(!!this.value)}toString(){return String(this.value)}},me=class extends Vr{type="IntegerValue"},tt=class extends Vr{type="FloatValue";toString(){return this.value%1===0?this.value.toFixed(1):this.value.toString()}},ie=class extends Vr{type="StringValue";builtins=new Map([["upper",new qe(()=>new ie(this.value.toUpperCase()))],["lower",new qe(()=>new ie(this.value.toLowerCase()))],["strip",new qe(()=>new ie(this.value.trim()))],["title",new qe(()=>new ie(h6(this.value)))],["capitalize",new qe(()=>new ie(this.value.charAt(0).toUpperCase()+this.value.slice(1)))],["length",new me(this.value.length)],["rstrip",new qe(()=>new ie(this.value.trimEnd()))],["lstrip",new qe(()=>new ie(this.value.trimStart()))],["startswith",new qe(e=>{if(e.length===0)throw new Error("startswith() requires at least one argument");let t=e[0];if(t instanceof ie)return new pe(this.value.startsWith(t.value));if(t instanceof Ae){for(let r of t.value){if(!(r instanceof ie))throw new Error("startswith() tuple elements must be strings");if(this.value.startsWith(r.value))return new pe(!0)}return new pe(!1)}throw new Error("startswith() argument must be a string or tuple of strings")})],["endswith",new qe(e=>{if(e.length===0)throw new Error("endswith() requires at least one argument");let t=e[0];if(t instanceof ie)return new pe(this.value.endsWith(t.value));if(t instanceof Ae){for(let r of t.value){if(!(r instanceof ie))throw new Error("endswith() tuple elements must be strings");if(this.value.endsWith(r.value))return new pe(!0)}return new pe(!1)}throw new Error("endswith() argument must be a string or tuple of strings")})],["split",new qe(e=>{let t=e[0]??new ze;if(!(t instanceof ie||t instanceof ze))throw new Error("sep argument must be a string or null");let r=e[1]??new me(-1);if(!(r instanceof me))throw new Error("maxsplit argument must be a number");let a=[];if(t instanceof ze){let n=this.value.trimStart();for(let{0:s,index:i}of n.matchAll(/\S+/g)){if(r.value!==-1&&a.length>=r.value&&i!==void 0){a.push(s+n.slice(i+s.length));break}a.push(s)}}else{if(t.value==="")throw new Error("empty separator");a=this.value.split(t.value),r.value!==-1&&a.length>r.value&&a.push(a.splice(r.value).join(t.value))}return new Ae(a.map(n=>new ie(n)))})],["replace",new qe(e=>{if(e.length<2)throw new Error("replace() requires at least two arguments");let t=e[0],r=e[1];if(!(t instanceof ie&&r instanceof ie))throw new Error("replace() arguments must be strings");let a;if(e.length>2?e[2].type==="KeywordArgumentsValue"?a=e[2].value.get("count")??new ze:a=e[2]:a=new ze,!(a instanceof me||a instanceof ze))throw new Error("replace() count argument must be a number or null");return new ie(m6(this.value,t.value,r.value,a.value))})]])},pe=class extends Vr{type="BooleanValue"},I6=/[\x7f-\uffff]/g;mt=class extends Vr{type="ObjectValue";__bool__(){return new pe(this.value.size>0)}builtins=new Map([["get",new qe(([e,t])=>{if(!(e instanceof ie))throw new Error(`Object key must be a string: got ${e.type}`);return this.value.get(e.value)??t??new ze})],["items",new qe(()=>this.items())],["keys",new qe(()=>this.keys())],["values",new qe(()=>this.values())],["dictsort",new qe(e=>{let t=new Map,r=e.filter(o=>o instanceof Ys?(t=o.value,!1):!0),a=r.at(0)??t.get("case_sensitive")??new pe(!1);if(!(a instanceof pe))throw new Error("case_sensitive must be a boolean");let n=r.at(1)??t.get("by")??new ie("key");if(!(n instanceof ie))throw new Error("by must be a string");if(!["key","value"].includes(n.value))throw new Error("by must be either 'key' or 'value'");let s=r.at(2)??t.get("reverse")??new pe(!1);if(!(s instanceof pe))throw new Error("reverse must be a boolean");let i=Array.from(this.value.entries()).map(([o,H])=>new Ae([new ie(o),H])).sort((o,H)=>{let _=n.value==="key"?0:1,c=o.value[_],l=H.value[_],d=Yu(c,l,a.value);return s.value?-d:d});return new Ae(i)})]]);items(){return new Ae(Array.from(this.value.entries()).map(([e,t])=>new Ae([new ie(e),t])))}keys(){return new Ae(Array.from(this.value.keys()).map(e=>new ie(e)))}values(){return new Ae(Array.from(this.value.values()))}toString(){return tn(this,{},0,!1)}},Ys=class extends mt{type="KeywordArgumentsValue"},Ae=class extends Vr{type="ArrayValue";builtins=new Map([["length",new me(this.value.length)]]);__bool__(){return new pe(this.value.length>0)}toString(){return tn(this,{},0,!1)}},CI=class extends Ae{type="TupleValue"},qe=class extends Vr{type="FunctionValue"},ze=class extends Vr{type="NullValue"},je=class extends Vr{type="UndefinedValue"},qa=class{constructor(e){this.parent=e}variables=new Map([["namespace",new qe(e=>{if(e.length===0)return new mt(new Map);if(e.length!==1||!(e[0]instanceof mt))throw new Error("`namespace` expects either zero arguments or a single object argument");return e[0]})]]);tests=new Map([["boolean",e=>e.type==="BooleanValue"],["callable",e=>e instanceof qe],["odd",e=>{if(!(e instanceof me))throw new Error(`cannot odd on ${e.type}`);return e.value%2!==0}],["even",e=>{if(!(e instanceof me))throw new Error(`cannot even on ${e.type}`);return e.value%2===0}],["false",e=>e.type==="BooleanValue"&&!e.value],["true",e=>e.type==="BooleanValue"&&e.value],["none",e=>e.type==="NullValue"],["string",e=>e.type==="StringValue"],["number",e=>e instanceof me||e instanceof tt],["integer",e=>e instanceof me],["iterable",e=>e.type==="ArrayValue"||e.type==="StringValue"],["mapping",e=>e instanceof mt],["sequence",e=>e instanceof Ae||e instanceof mt||e instanceof ie],["lower",e=>{let t=e.value;return e.type==="StringValue"&&t===t.toLowerCase()}],["upper",e=>{let t=e.value;return e.type==="StringValue"&&t===t.toUpperCase()}],["none",e=>e.type==="NullValue"],["defined",e=>e.type!=="UndefinedValue"],["undefined",e=>e.type==="UndefinedValue"],["equalto",(e,t)=>e.value===t.value],["eq",(e,t)=>e.value===t.value]]);set(e,t){return this.declareVariable(e,Jo(t))}declareVariable(e,t){if(this.variables.has(e))throw new SyntaxError(`Variable already declared: ${e}`);return this.variables.set(e,t),t}setVariable(e,t){return this.variables.set(e,t),t}resolve(e){if(this.variables.has(e))return this;if(this.parent)return this.parent.resolve(e);throw new Error(`Unknown variable: ${e}`)}lookupVariable(e){try{return this.resolve(e).variables.get(e)??new je}catch{return new je}}};L6=class{global;constructor(e){this.global=e??new qa}run(e){return this.evaluate(e,this.global)}evaluateBinaryExpression(e,t){let r=this.evaluate(e.left,t);switch(e.operator.value){case"and":return r.__bool__().value?this.evaluate(e.right,t):r;case"or":return r.__bool__().value?r:this.evaluate(e.right,t)}let a=this.evaluate(e.right,t);switch(e.operator.value){case"==":return new pe(r.value==a.value);case"!=":return new pe(r.value!=a.value)}if(r instanceof je||a instanceof je){if(a instanceof je&&["in","not in"].includes(e.operator.value))return new pe(e.operator.value==="not in");throw new Error(`Cannot perform operation ${e.operator.value} on undefined values`)}else{if(r instanceof ze||a instanceof ze)throw new Error("Cannot perform operation on null values");if(e.operator.value==="~")return new ie(r.value.toString()+a.value.toString());if((r instanceof me||r instanceof tt)&&(a instanceof me||a instanceof tt)){let n=r.value,s=a.value;switch(e.operator.value){case"+":case"-":case"*":{let i=e.operator.value==="+"?n+s:e.operator.value==="-"?n-s:n*s;return r instanceof tt||a instanceof tt?new tt(i):new me(i)}case"/":return new tt(n/s);case"%":{let i=n%s;return r instanceof tt||a instanceof tt?new tt(i):new me(i)}case"<":return new pe(n<s);case">":return new pe(n>s);case">=":return new pe(n>=s);case"<=":return new pe(n<=s)}}else if(r instanceof Ae&&a instanceof Ae){if(e.operator.value==="+")return new Ae(r.value.concat(a.value))}else if(a instanceof Ae){let n=a.value.find(s=>s.value===r.value)!==void 0;switch(e.operator.value){case"in":return new pe(n);case"not in":return new pe(!n)}}}if((r instanceof ie||a instanceof ie)&&e.operator.value==="+")return new ie(r.value.toString()+a.value.toString());if(r instanceof ie&&a instanceof ie)switch(e.operator.value){case"in":return new pe(a.value.includes(r.value));case"not in":return new pe(!a.value.includes(r.value))}if(r instanceof ie&&a instanceof mt)switch(e.operator.value){case"in":return new pe(a.value.has(r.value));case"not in":return new pe(!a.value.has(r.value))}throw new SyntaxError(`Unknown operator "${e.operator.value}" between ${r.type} and ${a.type}`)}evaluateArguments(e,t){let r=[],a=new Map;for(let n of e)if(n.type==="SpreadExpression"){let s=n,i=this.evaluate(s.argument,t);if(!(i instanceof Ae))throw new Error(`Cannot unpack non-iterable type: ${i.type}`);for(let o of i.value)r.push(o)}else if(n.type==="KeywordArgumentExpression"){let s=n;a.set(s.key.value,this.evaluate(s.value,t))}else{if(a.size>0)throw new Error("Positional arguments must come before keyword arguments");r.push(this.evaluate(n,t))}return[r,a]}applyFilter(e,t,r){if(t.type==="Identifier"){let a=t;if(a.value==="safe")return e;if(a.value==="tojson")return new ie(tn(e,{}));if(e instanceof Ae)switch(a.value){case"list":return e;case"first":return e.value[0];case"last":return e.value[e.value.length-1];case"length":return new me(e.value.length);case"reverse":return new Ae(e.value.slice().reverse());case"sort":return new Ae(e.value.slice().sort((n,s)=>Yu(n,s,!1)));case"join":return new ie(e.value.map(n=>n.value).join(""));case"string":return new ie(tn(e,{},0,!1));case"unique":{let n=new Set,s=[];for(let i of e.value)n.has(i.value)||(n.add(i.value),s.push(i));return new Ae(s)}default:throw new Error(`Unknown ArrayValue filter: ${a.value}`)}else if(e instanceof ie)switch(a.value){case"length":case"upper":case"lower":case"title":case"capitalize":{let n=e.builtins.get(a.value);if(n instanceof qe)return n.value([],r);if(n instanceof me)return n;throw new Error(`Unknown StringValue filter: ${a.value}`)}case"trim":return new ie(e.value.trim());case"indent":return new ie(e.value.split(`
17
- `).map((n,s)=>s===0||n.length===0?n:" "+n).join(`
18
- `));case"join":case"string":return e;case"int":{let n=parseInt(e.value,10);return new me(isNaN(n)?0:n)}case"float":{let n=parseFloat(e.value);return new tt(isNaN(n)?0:n)}default:throw new Error(`Unknown StringValue filter: ${a.value}`)}else if(e instanceof me||e instanceof tt)switch(a.value){case"abs":return e instanceof me?new me(Math.abs(e.value)):new tt(Math.abs(e.value));case"int":return new me(Math.floor(e.value));case"float":return new tt(e.value);case"string":return new ie(e.toString());default:throw new Error(`Unknown NumericValue filter: ${a.value}`)}else if(e instanceof mt)switch(a.value){case"items":return new Ae(Array.from(e.value.entries()).map(([n,s])=>new Ae([new ie(n),s])));case"length":return new me(e.value.size);default:{let n=e.builtins.get(a.value);if(n)return n instanceof qe?n.value([],r):n;throw new Error(`Unknown ObjectValue filter: ${a.value}`)}}else if(e instanceof pe)switch(a.value){case"bool":return new pe(e.value);case"int":return new me(e.value?1:0);case"float":return new tt(e.value?1:0);case"string":return new ie(e.value?"true":"false");default:throw new Error(`Unknown BooleanValue filter: ${a.value}`)}throw new Error(`Cannot apply filter "${a.value}" to type: ${e.type}`)}else if(t.type==="CallExpression"){let a=t;if(a.callee.type!=="Identifier")throw new Error(`Unknown filter: ${a.callee.type}`);let n=a.callee.value;if(n==="tojson"){let[,s]=this.evaluateArguments(a.args,r),i=s.get("indent")??new ze;if(!(i instanceof me||i instanceof ze))throw new Error("If set, indent must be a number");let o=s.get("ensure_ascii")??new pe(!1);if(!(o instanceof pe))throw new Error("If set, ensure_ascii must be a boolean");let H=s.get("sort_keys")??new pe(!1);if(!(H instanceof pe))throw new Error("If set, sort_keys must be a boolean");let _=s.get("separators")??new ze,c=null;if(_ instanceof Ae||_ instanceof CI){if(_.value.length!==2)throw new Error("separators must be a tuple of two strings");let[l,d]=_.value;if(!(l instanceof ie)||!(d instanceof ie))throw new Error("separators must be a tuple of two strings");c=[l.value,d.value]}else if(!(_ instanceof ze))throw new Error("If set, separators must be a tuple of two strings");return new ie(tn(e,{indent:i.value,ensureAscii:o.value,sortKeys:H.value,separators:c}))}else if(n==="join"){let s;if(e instanceof ie)s=Array.from(e.value);else if(e instanceof Ae)s=e.value.map(_=>_.value);else throw new Error(`Cannot apply filter "${n}" to type: ${e.type}`);let[i,o]=this.evaluateArguments(a.args,r),H=i.at(0)??o.get("separator")??new ie("");if(!(H instanceof ie))throw new Error("separator must be a string");return new ie(s.join(H.value))}else if(n==="int"||n==="float"){let[s,i]=this.evaluateArguments(a.args,r),o=s.at(0)??i.get("default")??(n==="int"?new me(0):new tt(0));if(e instanceof ie){let H=n==="int"?parseInt(e.value,10):parseFloat(e.value);return isNaN(H)?o:n==="int"?new me(H):new tt(H)}else{if(e instanceof me||e instanceof tt)return e;if(e instanceof pe)return n==="int"?new me(e.value?1:0):new tt(e.value?1:0);throw new Error(`Cannot apply filter "${n}" to type: ${e.type}`)}}else if(n==="default"){let[s,i]=this.evaluateArguments(a.args,r),o=s[0]??new ie(""),H=s[1]??i.get("boolean")??new pe(!1);if(!(H instanceof pe))throw new Error("`default` filter flag must be a boolean");return e instanceof je||H.value&&!e.__bool__().value?o:e}if(e instanceof Ae){switch(n){case"sort":{let[s,i]=this.evaluateArguments(a.args,r),o=s.at(0)??i.get("reverse")??new pe(!1);if(!(o instanceof pe))throw new Error("reverse must be a boolean");let H=s.at(1)??i.get("case_sensitive")??new pe(!1);if(!(H instanceof pe))throw new Error("case_sensitive must be a boolean");let _=s.at(2)??i.get("attribute")??new ze;if(!(_ instanceof ie||_ instanceof me||_ instanceof ze))throw new Error("attribute must be a string, integer, or null");let c=l=>{if(_ instanceof ze)return l;let d=_ instanceof me?String(_.value):_.value;return wI(l,d)};return new Ae(e.value.slice().sort((l,d)=>{let h=c(l),$=c(d),m=Yu(h,$,H.value);return o.value?-m:m}))}case"selectattr":case"rejectattr":{let s=n==="selectattr";if(e.value.some(l=>!(l instanceof mt)))throw new Error(`\`${n}\` can only be applied to array of objects`);if(a.args.some(l=>l.type!=="StringLiteral"))throw new Error(`arguments of \`${n}\` must be strings`);let[i,o,H]=a.args.map(l=>this.evaluate(l,r)),_;if(o){let l=r.tests.get(o.value);if(!l)throw new Error(`Unknown test: ${o.value}`);_=l}else _=(...l)=>l[0].__bool__().value;let c=e.value.filter(l=>{let d=l.value.get(i.value),h=d?_(d,H):!1;return s?h:!h});return new Ae(c)}case"map":{let[,s]=this.evaluateArguments(a.args,r);if(s.has("attribute")){let i=s.get("attribute");if(!(i instanceof ie))throw new Error("attribute must be a string");let o=s.get("default"),H=e.value.map(_=>{if(!(_ instanceof mt))throw new Error("items in map must be an object");let c=wI(_,i.value);return c instanceof je?o??new je:c});return new Ae(H)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${n}`)}else if(e instanceof ie){switch(n){case"indent":{let[s,i]=this.evaluateArguments(a.args,r),o=s.at(0)??i.get("width")??new me(4);if(!(o instanceof me))throw new Error("width must be a number");let H=s.at(1)??i.get("first")??new pe(!1),_=s.at(2)??i.get("blank")??new pe(!1),c=e.value.split(`
19
- `),l=" ".repeat(o.value),d=c.map((h,$)=>!H.value&&$===0||!_.value&&h.length===0?h:l+h);return new ie(d.join(`
20
- `))}case"replace":{let s=e.builtins.get("replace");if(!(s instanceof qe))throw new Error("replace filter not available");let[i,o]=this.evaluateArguments(a.args,r);return s.value([...i,new Ys(o)],r)}}throw new Error(`Unknown StringValue filter: ${n}`)}else if(e instanceof mt){let s=e.builtins.get(n);if(s&&s instanceof qe){let[i,o]=this.evaluateArguments(a.args,r);return o.size>0&&i.push(new Ys(o)),s.value(i,r)}throw new Error(`Unknown ObjectValue filter: ${n}`)}else throw new Error(`Cannot apply filter "${n}" to type: ${e.type}`)}throw new Error(`Unknown filter: ${t.type}`)}evaluateFilterExpression(e,t){let r=this.evaluate(e.operand,t);return this.applyFilter(r,e.filter,t)}evaluateTestExpression(e,t){let r=this.evaluate(e.operand,t),a=t.tests.get(e.test.value);if(!a)throw new Error(`Unknown test: ${e.test.value}`);let n=a(r);return new pe(e.negate?!n:n)}evaluateSelectExpression(e,t){return this.evaluate(e.test,t).__bool__().value?this.evaluate(e.lhs,t):new je}evaluateUnaryExpression(e,t){let r=this.evaluate(e.argument,t);if(e.operator.value==="not")return new pe(!r.value);throw new SyntaxError(`Unknown operator: ${e.operator.value}`)}evaluateTernaryExpression(e,t){return this.evaluate(e.condition,t).__bool__().value?this.evaluate(e.trueExpr,t):this.evaluate(e.falseExpr,t)}evalProgram(e,t){return this.evaluateBlock(e.body,t)}evaluateBlock(e,t){let r="";for(let a of e){let n=this.evaluate(a,t);n.type!=="NullValue"&&n.type!=="UndefinedValue"&&(r+=n.toString())}return new ie(r)}evaluateIdentifier(e,t){return t.lookupVariable(e.value)}evaluateCallExpression(e,t){let[r,a]=this.evaluateArguments(e.args,t);a.size>0&&r.push(new Ys(a));let n=this.evaluate(e.callee,t);if(n.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${n.type}`);return n.value(r,t)}evaluateSliceExpression(e,t,r){if(!(e instanceof Ae||e instanceof ie))throw new Error("Slice object must be an array or string");let a=this.evaluate(t.start,r),n=this.evaluate(t.stop,r),s=this.evaluate(t.step,r);if(!(a instanceof me||a instanceof je))throw new Error("Slice start must be numeric or undefined");if(!(n instanceof me||n instanceof je))throw new Error("Slice stop must be numeric or undefined");if(!(s instanceof me||s instanceof je))throw new Error("Slice step must be numeric or undefined");return e instanceof Ae?new Ae(xI(e.value,a.value,n.value,s.value)):new ie(xI(Array.from(e.value),a.value,n.value,s.value).join(""))}evaluateMemberExpression(e,t){let r=this.evaluate(e.object,t),a;if(e.computed){if(e.property.type==="SliceExpression")return this.evaluateSliceExpression(r,e.property,t);a=this.evaluate(e.property,t)}else a=new ie(e.property.value);let n;if(r instanceof mt){if(!(a instanceof ie))throw new Error(`Cannot access property with non-string: got ${a.type}`);n=r.value.get(a.value)??r.builtins.get(a.value)}else if(r instanceof Ae||r instanceof ie)if(a instanceof me)n=r.value.at(a.value),r instanceof ie&&(n=new ie(r.value.at(a.value)));else if(a instanceof ie)n=r.builtins.get(a.value);else throw new Error(`Cannot access property with non-string/non-number: got ${a.type}`);else{if(!(a instanceof ie))throw new Error(`Cannot access property with non-string: got ${a.type}`);n=r.builtins.get(a.value)}return n instanceof Vr?n:new je}evaluateSet(e,t){let r=e.value?this.evaluate(e.value,t):this.evaluateBlock(e.body,t);if(e.assignee.type==="Identifier"){let a=e.assignee.value;t.setVariable(a,r)}else if(e.assignee.type==="TupleLiteral"){let a=e.assignee;if(!(r instanceof Ae))throw new Error(`Cannot unpack non-iterable type in set: ${r.type}`);let n=r.value;if(n.length!==a.value.length)throw new Error(`Too ${a.value.length>n.length?"few":"many"} items to unpack in set`);for(let s=0;s<a.value.length;++s){let i=a.value[s];if(i.type!=="Identifier")throw new Error(`Cannot unpack to non-identifier in set: ${i.type}`);t.setVariable(i.value,n[s])}}else if(e.assignee.type==="MemberExpression"){let a=e.assignee,n=this.evaluate(a.object,t);if(!(n instanceof mt))throw new Error("Cannot assign to member of non-object");if(a.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");n.value.set(a.property.value,r)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(e.assignee)}`);return new ze}evaluateIf(e,t){let r=this.evaluate(e.test,t);return this.evaluateBlock(r.__bool__().value?e.body:e.alternate,t)}evaluateFor(e,t){let r=new qa(t),a,n;if(e.iterable.type==="SelectExpression"){let _=e.iterable;n=this.evaluate(_.lhs,r),a=_.test}else n=this.evaluate(e.iterable,r);if(!(n instanceof Ae||n instanceof mt))throw new Error(`Expected iterable or object type in for loop: got ${n.type}`);n instanceof mt&&(n=n.keys());let s=[],i=[];for(let _=0;_<n.value.length;++_){let c=new qa(r),l=n.value[_],d;if(e.loopvar.type==="Identifier")d=h=>h.setVariable(e.loopvar.value,l);else if(e.loopvar.type==="TupleLiteral"){let h=e.loopvar;if(l.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${l.type}`);let $=l;if(h.value.length!==$.value.length)throw new Error(`Too ${h.value.length>$.value.length?"few":"many"} items to unpack`);d=m=>{for(let S=0;S<h.value.length;++S){if(h.value[S].type!=="Identifier")throw new Error(`Cannot unpack non-identifier type: ${h.value[S].type}`);m.setVariable(h.value[S].value,$.value[S])}}}else throw new Error(`Invalid loop variable(s): ${e.loopvar.type}`);a&&(d(c),!this.evaluate(a,c).__bool__().value)||(s.push(l),i.push(d))}let o="",H=!0;for(let _=0;_<s.length;++_){let c=new Map([["index",new me(_+1)],["index0",new me(_)],["revindex",new me(s.length-_)],["revindex0",new me(s.length-_-1)],["first",new pe(_===0)],["last",new pe(_===s.length-1)],["length",new me(s.length)],["previtem",_>0?s[_-1]:new je],["nextitem",_<s.length-1?s[_+1]:new je]]);r.setVariable("loop",new mt(c)),i[_](r);try{let l=this.evaluateBlock(e.body,r);o+=l.value}catch(l){if(l instanceof yI)continue;if(l instanceof vI)break;throw l}H=!1}if(H){let _=this.evaluateBlock(e.defaultBlock,r);o+=_.value}return new ie(o)}evaluateMacro(e,t){return t.setVariable(e.name.value,new qe((r,a)=>{let n=new qa(a);r=r.slice();let s;r.at(-1)?.type==="KeywordArgumentsValue"&&(s=r.pop());for(let i=0;i<e.args.length;++i){let o=e.args[i],H=r[i];if(o.type==="Identifier"){let _=o;if(!H)throw new Error(`Missing positional argument: ${_.value}`);n.setVariable(_.value,H)}else if(o.type==="KeywordArgumentExpression"){let _=o,c=H??s?.value.get(_.key.value)??this.evaluate(_.value,n);n.setVariable(_.key.value,c)}else throw new Error(`Unknown argument type: ${o.type}`)}return this.evaluateBlock(e.body,n)})),new ze}evaluateCallStatement(e,t){let r=new qe((o,H)=>{let _=new qa(H);if(e.callerArgs)for(let c=0;c<e.callerArgs.length;++c){let l=e.callerArgs[c];if(l.type!=="Identifier")throw new Error(`Caller parameter must be an identifier, got ${l.type}`);_.setVariable(l.value,o[c]??new je)}return this.evaluateBlock(e.body,_)}),[a,n]=this.evaluateArguments(e.call.args,t);a.push(new Ys(n));let s=this.evaluate(e.call.callee,t);if(s.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${s.type}`);let i=new qa(t);return i.setVariable("caller",r),s.value(a,i)}evaluateFilterStatement(e,t){let r=this.evaluateBlock(e.body,t);return this.applyFilter(r,e.filter,t)}evaluate(e,t){if(!e)return new je;switch(e.type){case"Program":return this.evalProgram(e,t);case"Set":return this.evaluateSet(e,t);case"If":return this.evaluateIf(e,t);case"For":return this.evaluateFor(e,t);case"Macro":return this.evaluateMacro(e,t);case"CallStatement":return this.evaluateCallStatement(e,t);case"Break":throw new vI;case"Continue":throw new yI;case"IntegerLiteral":return new me(e.value);case"FloatLiteral":return new tt(e.value);case"StringLiteral":return new ie(e.value);case"ArrayLiteral":return new Ae(e.value.map(r=>this.evaluate(r,t)));case"TupleLiteral":return new CI(e.value.map(r=>this.evaluate(r,t)));case"ObjectLiteral":{let r=new Map;for(let[a,n]of e.value){let s=this.evaluate(a,t);if(!(s instanceof ie))throw new Error(`Object keys must be strings: got ${s.type}`);r.set(s.value,this.evaluate(n,t))}return new mt(r)}case"Identifier":return this.evaluateIdentifier(e,t);case"CallExpression":return this.evaluateCallExpression(e,t);case"MemberExpression":return this.evaluateMemberExpression(e,t);case"UnaryExpression":return this.evaluateUnaryExpression(e,t);case"BinaryExpression":return this.evaluateBinaryExpression(e,t);case"FilterExpression":return this.evaluateFilterExpression(e,t);case"FilterStatement":return this.evaluateFilterStatement(e,t);case"TestExpression":return this.evaluateTestExpression(e,t);case"SelectExpression":return this.evaluateSelectExpression(e,t);case"Ternary":return this.evaluateTernaryExpression(e,t);case"Comment":return new ze;default:throw new SyntaxError(`Unknown node type: ${e.type}`)}}};ut=`
21
- `,A6="{%- ",g6=" -%}";B6=class{parsed;constructor(e){let t=UG(e,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=d6(t)}render(e){let t=new qa;if(S6(t),e)for(let[n,s]of Object.entries(e))t.set(n,s);return new L6(t).run(this.parsed).value}format(e){return T6(this.parsed,e?.indent||" ")}},M6={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"},iH=class XS{constructor(t){if(this.filePath=t,this.headers=new Headers,this.exists=Xa.default.existsSync(t),this.exists){this.status=200,this.statusText="OK";let r=Xa.default.statSync(t);this.headers.set("content-length",r.size.toString()),this.updateContentType();let a=Xa.default.createReadStream(t);this.body=new ReadableStream({start(n){a.on("data",s=>n.enqueue(s)),a.on("end",()=>n.close()),a.on("error",s=>n.error(s))},cancel(){a.destroy()}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){let t=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",M6[t]??"application/octet-stream")}clone(){let t=new XS(this.filePath);return t.exists=this.exists,t.status=this.status,t.statusText=this.statusText,t.headers=new Headers(this.headers),t}async arrayBuffer(){return(await Xa.default.promises.readFile(this.filePath)).buffer}async blob(){let t=await Xa.default.promises.readFile(this.filePath);return new Blob([t],{type:this.headers.get("content-type")})}async text(){return await Xa.default.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}},gH=class{constructor(e){this._mt=new Uint32Array(624),this._idx=625,this._gauss_next=null,this._random_fn=this.random.bind(this),this.seed(e)}seed(e){if(e==null)if(Ie.IS_CRYPTO_AVAILABLE){let i=new Uint32Array(1);crypto.getRandomValues(i),e=i[0]}else e=Date.now()>>>0;let t=this._mt,r=(i,o)=>Math.imul(i,o)>>>0,a=[];for(let i=e||0;i>0;i=Math.floor(i/4294967296))a.push(i&4294967295);a.length||a.push(0),t[0]=19650218;for(let i=1;i<624;++i)t[i]=r(1812433253,t[i-1]^t[i-1]>>>30)+i>>>0;let n=1,s=0;for(let i=Math.max(624,a.length);i>0;--i,++n,++s)n>=624&&(t[0]=t[623],n=1),s>=a.length&&(s=0),t[n]=(t[n]^r(t[n-1]^t[n-1]>>>30,1664525))+a[s]+s>>>0;for(let i=623;i>0;--i,++n)n>=624&&(t[0]=t[623],n=1),t[n]=(t[n]^r(t[n-1]^t[n-1]>>>30,1566083941))-n>>>0;t[0]=2147483648,this._idx=624,this._gauss_next=null}_int32(){let e=this._mt;if(this._idx>=624){for(let r=0;r<624;++r){let a=e[r]&2147483648|e[(r+1)%624]&2147483647;e[r]=(e[(r+397)%624]^a>>>1^(a&1?2567483615:0))>>>0}this._idx=0}let t=e[this._idx++];return t^=t>>>11,t^=t<<7&2636928640,t^=t<<15&4022730752,t^=t>>>18,t>>>0}random(){return((this._int32()>>>5)*67108864+(this._int32()>>>6))/9007199254740992}gauss(e=0,t=1){let r=this._gauss_next;if(this._gauss_next=null,r===null){let a=this.random()*2*Math.PI,n=Math.sqrt(-2*Math.log(1-this.random()));r=Math.cos(a)*n,this._gauss_next=Math.sin(a)*n}return e+r*t}shuffle(e){for(let t=e.length-1;t>0;--t){let r=32-Math.clz32(t+1),a=this._int32()>>>32-r;for(;a>t;)a=this._int32()>>>32-r;let n=e[t];e[t]=e[a],e[a]=n}}choices(e,t){return e[zS(this._random_fn,t)]}};Gr=new gH,ui=Object.freeze({Random:gH,seed:Gr.seed.bind(Gr),random:Gr.random.bind(Gr),gauss:Gr.gauss.bind(Gr),shuffle:Gr.shuffle.bind(Gr),choices:Gr.choices.bind(Gr)}),P6=e=>zS(ui.random,e),k6=new gH,JS=class{constructor(e){this.path=e}async match(e){let t=ei.default.join(this.path,e),r=new iH(t);if(r.exists)return r}async put(e,t,r=void 0){let a=ei.default.join(this.path,e),n=Ie.IS_PROCESS_AVAILABLE?process.pid:Date.now(),s=k6._int32().toString(36),i=a+`.tmp.${n}.${s}`;try{let o=t.headers.get("Content-Length"),H=parseInt(o??"0"),_=0;await ts.default.promises.mkdir(ei.default.dirname(a),{recursive:!0});let c=ts.default.createWriteStream(i),l=t.body.getReader();for(;;){let{done:d,value:h}=await l.read();if(d)break;await new Promise((m,S)=>{c.write(h,I=>{if(I){S(I);return}m()})}),_+=h.length;let $=H?_/H*100:0;r?.({progress:$,loaded:_,total:H})}await new Promise((d,h)=>{c.close($=>$?h($):d())}),await ts.default.promises.rename(i,a)}catch(o){try{await ts.default.promises.unlink(i)}catch{}throw o}}async delete(e){let t=ei.default.join(this.path,e);try{return await ts.default.promises.unlink(t),!0}catch{return!1}}},R6={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"},NI=100,O6=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;QS="SHA-256",U6="experimental_transformers-hash-cache",PI=e=>({algorithm:QS,value:e}),kI=class{#t=null;_getHashCache=()=>(this.#t??=caches.open(U6),this.#t);static isAvailable=()=>typeof navigator<"u"&&"crossOriginStorage"in navigator;match=async e=>{let t=await this._getFileHash(e);if(t)try{let[r]=await navigator.crossOriginStorage.requestFileHandles([PI(t)]),a=await r.getFile();return new Response(a,{headers:{"Content-Length":String(a.size)}})}catch{return}};put=async(e,t)=>{let r=await this._getFileHash(e);if(r){let a=await t.blob();await this._storeBlobInCOS(a,r)}else this._processAndStore(e,t.body)};_storeBlobInCOS=async(e,t)=>{let[r]=await navigator.crossOriginStorage.requestFileHandles([PI(t)],{create:!0}),a=await r.createWritable();await a.write(e),await a.close()};_processAndStore=async(e,t)=>{try{let r=[];for await(let s of t)r.push(s);let a=new Blob(r),n=await this._getBlobHash(a);await this._storeBlobInCOS(a,n);try{await(await this._getHashCache()).put(e,new Response(n))}catch{}}catch{}};delete=async e=>{try{return await(await this._getHashCache()).delete(e)}catch{return!1}};_getFileHash=async e=>{try{let t=await this._getHashCache(),r=await t.match(e);if(r)return r.text();let a=await this._getLfsFileHash(e);return a?(await t.put(e,new Response(a)),a):null}catch{return null}};_getLfsFileHash=async e=>{if(!e.includes("/resolve/"))return null;let t=e.replace("/resolve/","/raw/");try{let a=(await fetch(t).then(n=>n.text())).match(/^oid sha256:([0-9a-f]+)$/m);return a?a[1]:null}catch{return null}};_getBlobHash=async e=>{let t=await e.arrayBuffer(),r=await crypto.subtle.digest(QS,t);return Array.from(new Uint8Array(r)).map(n=>n.toString(16).padStart(2,"0")).join("")}};K6=class{#t;#e;constructor(e){this.#t=e,this.#e=new Map}get(e){if(!this.#e.has(e))return;let t=this.#e.get(e);return this.#e.delete(e),this.#e.set(e,t),t}put(e,t){this.#e.has(e)&&this.#e.delete(e),this.#e.set(e,t),this.#e.size>this.#t&&this.#e.delete(this.#e.keys().next().value)}delete(e){return this.#e.delete(e)}clear(){this.#e.clear()}},V6=100,Au=new K6(V6);Ro=new Map;nL=class{constructor(e){if(this.size=e|0,this.size<=1||!aL(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=e<<1,this.table=new Float64Array(this.size*2);for(let r=0;r<this.table.length;r+=2){let a=Math.PI*r/this.size;this.table[r]=Math.cos(a),this.table[r+1]=-Math.sin(a)}let t=0;for(let r=1;this.size>r;r<<=1)++t;this._width=t%2===0?t-1:t,this._bitrev=new Int32Array(1<<this._width);for(let r=0;r<this._bitrev.length;++r){this._bitrev[r]=0;for(let a=0;a<this._width;a+=2){let n=this._width-a-2;this._bitrev[r]|=(r>>>a&3)<<n}}}createComplexArray(){return new Float64Array(this._csize)}fromComplexArray(e,t){let r=t||new Array(e.length>>>1);for(let a=0;a<e.length;a+=2)r[a>>>1]=e[a];return r}toComplexArray(e,t){let r=t||this.createComplexArray();for(let a=0;a<r.length;a+=2)r[a]=e[a>>>1],r[a+1]=0;return r}transform(e,t){if(e===t)throw new Error("Input and output buffers must be different");this._transform4(e,t,1)}realTransform(e,t){if(e===t)throw new Error("Input and output buffers must be different");this._realTransform4(e,t,1)}inverseTransform(e,t){if(e===t)throw new Error("Input and output buffers must be different");this._transform4(e,t,-1);for(let r=0;r<e.length;++r)e[r]/=this.size}_transform4(e,t,r){let a=this._csize,s=1<<this._width,i=a/s<<1,o,H,_=this._bitrev;if(i===4)for(o=0,H=0;o<a;o+=i,++H){let l=_[H];this._singleTransform2(t,e,o,l,s)}else for(o=0,H=0;o<a;o+=i,++H){let l=_[H];this._singleTransform4(t,e,o,l,s,r)}let c=this.table;for(s>>=2;s>=2;s>>=2){i=a/s<<1;let l=i>>>2;for(o=0;o<a;o+=i){let d=o+l-1;for(let h=o,$=0;h<d;h+=2,$+=s){let m=h,S=m+l,I=S+l,g=I+l,T=e[m],x=e[m+1],v=e[S],k=e[S+1],L=e[I],V=e[I+1],K=e[g],X=e[g+1],Q=c[$],z=r*c[$+1],M=v*Q-k*z,F=v*z+k*Q,N=c[2*$],G=r*c[2*$+1],te=L*N-V*G,B=L*G+V*N,O=c[3*$],U=r*c[3*$+1],Y=K*O-X*U,Se=K*U+X*O,We=T+te,ce=x+B,Bt=T-te,Ke=x-B,Ht=M+Y,Mt=F+Se,Fe=r*(M-Y),ve=r*(F-Se);e[m]=We+Ht,e[m+1]=ce+Mt,e[S]=Bt+ve,e[S+1]=Ke-Fe,e[I]=We-Ht,e[I+1]=ce-Mt,e[g]=Bt-ve,e[g+1]=Ke+Fe}}}}_singleTransform2(e,t,r,a,n){let s=e[a],i=e[a+1],o=e[a+n],H=e[a+n+1];t[r]=s+o,t[r+1]=i+H,t[r+2]=s-o,t[r+3]=i-H}_singleTransform4(e,t,r,a,n,s){let i=n*2,o=n*3,H=e[a],_=e[a+1],c=e[a+n],l=e[a+n+1],d=e[a+i],h=e[a+i+1],$=e[a+o],m=e[a+o+1],S=H+d,I=_+h,g=H-d,T=_-h,x=c+$,v=l+m,k=s*(c-$),L=s*(l-m);t[r]=S+x,t[r+1]=I+v,t[r+2]=g+L,t[r+3]=T-k,t[r+4]=S-x,t[r+5]=I-v,t[r+6]=g-L,t[r+7]=T+k}_realTransform4(e,t,r){let a=this._csize,s=1<<this._width,i=a/s<<1,o,H,_=this._bitrev;if(i===4)for(o=0,H=0;o<a;o+=i,++H){let d=_[H];this._singleRealTransform2(t,e,o,d>>>1,s>>>1)}else for(o=0,H=0;o<a;o+=i,++H){let d=_[H];this._singleRealTransform4(t,e,o,d>>>1,s>>>1,r)}let c=this.table;for(s>>=2;s>=2;s>>=2){i=a/s<<1;let d=i>>>1,h=d>>>1,$=h>>>1;for(o=0;o<a;o+=i)for(let m=0,S=0;m<=$;m+=2,S+=s){let I=o+m,g=I+h,T=g+h,x=T+h,v=e[I],k=e[I+1],L=e[g],V=e[g+1],K=e[T],X=e[T+1],Q=e[x],z=e[x+1],M=v,F=k,N=c[S],G=r*c[S+1],te=L*N-V*G,B=L*G+V*N,O=c[2*S],U=r*c[2*S+1],Y=K*O-X*U,Se=K*U+X*O,We=c[3*S],ce=r*c[3*S+1],Bt=Q*We-z*ce,Ke=Q*ce+z*We,Ht=M+Y,Mt=F+Se,Fe=M-Y,ve=F-Se,_t=te+Bt,Tr=B+Ke,De=r*(te-Bt),Re=r*(B-Ke);if(e[I]=Ht+_t,e[I+1]=Mt+Tr,e[g]=Fe+Re,e[g+1]=ve-De,m===0){e[T]=Ht-_t,e[T+1]=Mt-Tr;continue}if(m===$)continue;let bn=o+h-m,Ds=o+d-m;e[bn]=Fe-r*Re,e[bn+1]=-ve-r*De,e[Ds]=Ht-r*_t,e[Ds+1]=-Mt+r*Tr}}let l=a>>>1;for(let d=2;d<l;d+=2)e[a-d]=e[d],e[a-d+1]=-e[d+1]}_singleRealTransform2(e,t,r,a,n){let s=e[a],i=e[a+n];t[r]=s+i,t[r+1]=0,t[r+2]=s-i,t[r+3]=0}_singleRealTransform4(e,t,r,a,n,s){let i=n*2,o=n*3,H=e[a],_=e[a+n],c=e[a+i],l=e[a+o],d=H+c,h=H-c,$=_+l,m=s*(_-l);t[r]=d+$,t[r+1]=0,t[r+2]=h,t[r+3]=-m,t[r+4]=d-$,t[r+5]=0,t[r+6]=h,t[r+7]=m}},eF=class{constructor(e){let t=2*(e-1),r=2*(2*e-1),a=2**Math.ceil(Math.log2(r));this.bufferSize=a,this._a=t;let n=new Float64Array(r),s=new Float64Array(a);this._chirpBuffer=new Float64Array(a),this._buffer1=new Float64Array(a),this._buffer2=new Float64Array(a),this._outBuffer1=new Float64Array(a),this._outBuffer2=new Float64Array(a);let i=-2*Math.PI/e,o=Math.cos(i),H=Math.sin(i);for(let _=0;_<r>>1;++_){let c=(_+1-e)**2/2,l=Math.sqrt(o**2+H**2)**c,d=c*Math.atan2(H,o),h=2*_;n[h]=l*Math.cos(d),n[h+1]=l*Math.sin(d),s[h]=n[h],s[h+1]=-n[h+1]}this._slicedChirpBuffer=n.subarray(t,r),this._f=new nL(a>>1),this._f.transform(this._chirpBuffer,s)}_transform(e,t,r){let a=this._buffer1,n=this._buffer2,s=this._outBuffer1,i=this._outBuffer2,o=this._chirpBuffer,H=this._slicedChirpBuffer,_=this._a;if(r)for(let c=0;c<H.length;c+=2){let l=c+1,d=c>>1,h=t[d];a[c]=h*H[c],a[l]=h*H[l]}else for(let c=0;c<H.length;c+=2){let l=c+1;a[c]=t[c]*H[c]-t[l]*H[l],a[l]=t[c]*H[l]+t[l]*H[c]}this._f.transform(s,a);for(let c=0;c<o.length;c+=2){let l=c+1;n[c]=s[c]*o[c]-s[l]*o[l],n[l]=s[c]*o[l]+s[l]*o[c]}this._f.inverseTransform(i,n);for(let c=0;c<i.length;c+=2){let l=i[c+_],d=i[c+_+1],h=H[c],$=H[c+1];e[c]=l*h-d*$,e[c+1]=l*$+d*h}}transform(e,t){this._transform(e,t,!1)}realTransform(e,t){this._transform(e,t,!0)}},tF=class{constructor(e){this.fft_length=e,this.isPowerOfTwo=aL(e),this.isPowerOfTwo?(this.fft=new nL(e),this.outputBufferSize=2*e):(this.fft=new eF(e),this.outputBufferSize=this.fft.bufferSize)}realTransform(e,t){this.fft.realTransform(e,t)}transform(e,t){this.fft.transform(e,t)}};sF=(function(){let e=null;return function(t){if(!e){e=new Float32Array(65536);let s=new ArrayBuffer(4),i=new Uint32Array(s),o=new Float32Array(s);for(let H=0;H<e.length;++H){let _=0,c=(H&32768)<<16,l=(H&31744)>>10,d=H&1023;if(l===31)_=c|2139095040|d<<13;else if(l===0)if(d===0)_=c;else{let h=113;for(;(d&1024)===0;)d<<=1,--h;d&=-1025,_=c|h<<23|d<<13}else _=c|l+112<<23|d<<13;i[0]=_,e[H]=o[0]}}let r=t.length,a=e,n=new Float32Array(r);for(let s=0;s<r;++s)n[s]=a[t[s]];return n}})(),sL={};us(sL,{InferenceSession:()=>xd,TRACE:()=>_H,TRACE_EVENT_BEGIN:()=>va,TRACE_EVENT_END:()=>ya,TRACE_FUNC_BEGIN:()=>an,TRACE_FUNC_END:()=>nn,Tensor:()=>Er,default:()=>MF,env:()=>Xe,registerBackend:()=>Ya});bd=Object.defineProperty,oF=Object.getOwnPropertyDescriptor,HF=Object.getOwnPropertyNames,_F=Object.prototype.hasOwnProperty,cF=(e=>typeof Xn<"u"?Xn:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof Xn<"u"?Xn:t)[r]}):e)(function(e){if(typeof Xn<"u")return Xn.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),be=(e,t)=>()=>(e&&(t=e(e=0)),t),hi=(e,t)=>{for(var r in t)bd(e,r,{get:t[r],enumerable:!0})},lF=(e,t,r,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of HF(t))!_F.call(e,n)&&n!==r&&bd(e,n,{get:()=>t[n],enumerable:!(a=oF(t,n))||a.enumerable});return e},HH=e=>lF(bd({},"__esModule",{value:!0}),e),oL=be(()=>{"use strict";qs=new Map,Sa=[],Ya=(e,t,r)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let a=qs.get(e);if(a===void 0)qs.set(e,{backend:t,priority:r});else{if(a.priority>r)return;if(a.priority===r&&a.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${r}`)}if(r>=0){let n=Sa.indexOf(e);n!==-1&&Sa.splice(n,1);for(let s=0;s<Sa.length;s++)if(qs.get(Sa[s]).priority<=r){Sa.splice(s,0,e);return}Sa.push(e)}return}throw new TypeError("not a valid backend")},OI=async e=>{let t=qs.get(e);if(!t)return"backend not found.";if(t.initialized)return t.backend;if(t.aborted)return t.error;{let r=!!t.initPromise;try{return r||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(a){return r||(t.error=`${a}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},iL=async e=>{let t=e.executionProviders||[],r=t.map(H=>typeof H=="string"?H:H.name),a=r.length===0?Sa:r,n,s=[],i=new Set;for(let H of a){let _=await OI(H);typeof _=="string"?s.push({name:H,err:_}):(n||(n=_),n===_&&i.add(H))}if(!n)throw new Error(`no available backend found. ERR: ${s.map(H=>`[${H.name}] ${H.err}`).join(", ")}`);for(let{name:H,err:_}of s)r.includes(H)&&console.warn(`removing requested execution provider "${H}" from session options because it is not available: ${_}`);let o=t.filter(H=>i.has(typeof H=="string"?H:H.name));return[n,new Proxy(e,{get:(H,_)=>_==="executionProviders"?o:Reflect.get(H,_)})]}}),uF=be(()=>{"use strict";oL()}),dF=be(()=>{"use strict";HL="1.24.0-dev.20251116-b39e144322"}),_L=be(()=>{"use strict";dF(),gu="warning",$t={wasm:{},webgl:{},webgpu:{},versions:{common:HL},set logLevel(e){if(e!==void 0){if(typeof e!="string"||["verbose","info","warning","error","fatal"].indexOf(e)===-1)throw new Error(`Unsupported logging level: ${e}`);gu=e}},get logLevel(){return gu}},Object.defineProperty($t,"logLevel",{enumerable:!0})}),pF=be(()=>{"use strict";_L(),Xe=$t}),hF=be(()=>{"use strict";cL=(e,t)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=e.dims[3],r.height=e.dims[2];let a=r.getContext("2d");if(a!=null){let n,s;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(n=e.dims[2],s=e.dims[3]):(n=e.dims[3],s=e.dims[2]);let i=t?.format!==void 0?t.format:"RGB",o=t?.norm,H,_;o===void 0||o.mean===void 0?H=[255,255,255,255]:typeof o.mean=="number"?H=[o.mean,o.mean,o.mean,o.mean]:(H=[o.mean[0],o.mean[1],o.mean[2],0],o.mean[3]!==void 0&&(H[3]=o.mean[3])),o===void 0||o.bias===void 0?_=[0,0,0,0]:typeof o.bias=="number"?_=[o.bias,o.bias,o.bias,o.bias]:(_=[o.bias[0],o.bias[1],o.bias[2],0],o.bias[3]!==void 0&&(_[3]=o.bias[3]));let c=s*n,l=0,d=c,h=c*2,$=-1;i==="RGBA"?(l=0,d=c,h=c*2,$=c*3):i==="RGB"?(l=0,d=c,h=c*2):i==="RBG"&&(l=0,h=c,d=c*2);for(let m=0;m<s;m++)for(let S=0;S<n;S++){let I=(e.data[l++]-_[0])*H[0],g=(e.data[d++]-_[1])*H[1],T=(e.data[h++]-_[2])*H[2],x=$===-1?255:(e.data[$++]-_[3])*H[3];a.fillStyle="rgba("+I+","+g+","+T+","+x+")",a.fillRect(S,m,1,1)}if("toDataURL"in r)return r.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},lL=(e,t)=>{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),a;if(r!=null){let n,s,i;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(n=e.dims[2],s=e.dims[1],i=e.dims[3]):(n=e.dims[3],s=e.dims[2],i=e.dims[1]);let o=t!==void 0&&t.format!==void 0?t.format:"RGB",H=t?.norm,_,c;H===void 0||H.mean===void 0?_=[255,255,255,255]:typeof H.mean=="number"?_=[H.mean,H.mean,H.mean,H.mean]:(_=[H.mean[0],H.mean[1],H.mean[2],255],H.mean[3]!==void 0&&(_[3]=H.mean[3])),H===void 0||H.bias===void 0?c=[0,0,0,0]:typeof H.bias=="number"?c=[H.bias,H.bias,H.bias,H.bias]:(c=[H.bias[0],H.bias[1],H.bias[2],0],H.bias[3]!==void 0&&(c[3]=H.bias[3]));let l=s*n;if(t!==void 0&&(t.format!==void 0&&i===4&&t.format!=="RGBA"||i===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let d=4,h=0,$=1,m=2,S=3,I=0,g=l,T=l*2,x=-1;o==="RGBA"?(I=0,g=l,T=l*2,x=l*3):o==="RGB"?(I=0,g=l,T=l*2):o==="RBG"&&(I=0,T=l,g=l*2),a=r.createImageData(n,s);for(let v=0;v<s*n;h+=d,$+=d,m+=d,S+=d,v++)a.data[h]=(e.data[I++]-c[0])*_[0],a.data[$]=(e.data[g++]-c[1])*_[1],a.data[m]=(e.data[T++]-c[2])*_[2],a.data[S]=x===-1?255:(e.data[x++]-c[3])*_[3]}else throw new Error("Can not access image data");return a}}),fF=be(()=>{"use strict";Td(),Oo=(e,t)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:a}=t,n=t.norm??{mean:255,bias:0},s,i;typeof n.mean=="number"?s=[n.mean,n.mean,n.mean,n.mean]:s=[n.mean[0],n.mean[1],n.mean[2],n.mean[3]??255],typeof n.bias=="number"?i=[n.bias,n.bias,n.bias,n.bias]:i=[n.bias[0],n.bias[1],n.bias[2],n.bias[3]??0];let o=t.format!==void 0?t.format:"RGBA",H=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",_=r*a,c=H==="RGBA"?new Float32Array(_*4):new Float32Array(_*3),l=4,d=0,h=1,$=2,m=3,S=0,I=_,g=_*2,T=-1;o==="RGB"&&(l=3,d=0,h=1,$=2,m=-1),H==="RGBA"?T=_*3:H==="RBG"?(S=0,g=_,I=_*2):H==="BGR"&&(g=0,I=_,S=_*2);for(let x=0;x<_;x++,d+=l,$+=l,h+=l,m+=l)c[S++]=(e[d]+i[0])/s[0],c[I++]=(e[h]+i[1])/s[1],c[g++]=(e[$]+i[2])/s[2],T!==-1&&m!==-1&&(c[T++]=(e[m]+i[3])/s[3]);return H==="RGBA"?new ar("float32",c,[1,4,r,a]):new ar("float32",c,[1,3,r,a])},uL=async(e,t)=>{let r=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,a=typeof ImageData<"u"&&e instanceof ImageData,n=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,s=typeof e=="string",i,o=t??{},H=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},_=c=>typeof HTMLCanvasElement<"u"&&c instanceof HTMLCanvasElement||c instanceof OffscreenCanvas?c.getContext("2d"):null;if(r){let c=H();c.width=e.width,c.height=e.height;let l=_(c);if(l!=null){let d=e.height,h=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(d=t.resizedHeight,h=t.resizedWidth),t!==void 0){if(o=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");o.tensorFormat="RGBA",o.height=d,o.width=h}else o.tensorFormat="RGBA",o.height=d,o.width=h;l.drawImage(e,0,0),i=l.getImageData(0,0,h,d).data}else throw new Error("Can not access image data")}else if(a){let c,l;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(c=t.resizedHeight,l=t.resizedWidth):(c=e.height,l=e.width),t!==void 0&&(o=t),o.format="RGBA",o.height=c,o.width=l,t!==void 0){let d=H();d.width=l,d.height=c;let h=_(d);if(h!=null)h.putImageData(e,0,0),i=h.getImageData(0,0,l,c).data;else throw new Error("Can not access image data")}else i=e.data}else if(n){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let c=H();c.width=e.width,c.height=e.height;let l=_(c);if(l!=null){let d=e.height,h=e.width;return l.drawImage(e,0,0,h,d),i=l.getImageData(0,0,h,d).data,o.height=d,o.width=h,Oo(i,o)}else throw new Error("Can not access image data")}else{if(s)return new Promise((c,l)=>{let d=H(),h=_(d);if(!e||!h)return l();let $=new Image;$.crossOrigin="Anonymous",$.src=e,$.onload=()=>{d.width=$.width,d.height=$.height,h.drawImage($,0,0,d.width,d.height);let m=h.getImageData(0,0,d.width,d.height);o.height=d.height,o.width=d.width,c(Oo(m.data,o))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(i!==void 0)return Oo(i,o);throw new Error("Input data provided is not supported - aborted tensor creation")},dL=(e,t)=>{let{width:r,height:a,download:n,dispose:s}=t,i=[1,a,r,4];return new ar({location:"texture",type:"float32",texture:e,dims:i,download:n,dispose:s})},pL=(e,t)=>{let{dataType:r,dims:a,download:n,dispose:s}=t;return new ar({location:"gpu-buffer",type:r??"float32",gpuBuffer:e,dims:a,download:n,dispose:s})},hL=(e,t)=>{let{dataType:r,dims:a,download:n,dispose:s}=t;return new ar({location:"ml-tensor",type:r??"float32",mlTensor:e,dims:a,download:n,dispose:s})},fL=(e,t,r)=>new ar({location:"cpu-pinned",type:e,data:t,dims:r??[t.length]})}),EF=be(()=>{"use strict";Ja=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),ri=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),bu=!1,EL=()=>{if(!bu){bu=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,a=typeof r<"u"&&r.from;e&&(Ja.set("int64",BigInt64Array),ri.set(BigInt64Array,"int64")),t&&(Ja.set("uint64",BigUint64Array),ri.set(BigUint64Array,"uint64")),a?(Ja.set("float16",r),ri.set(r,"float16")):Ja.set("float16",Uint16Array)}}}),$F=be(()=>{"use strict";Td(),$L=e=>{let t=1;for(let r=0;r<e.length;r++){let a=e[r];if(typeof a!="number"||!Number.isSafeInteger(a))throw new TypeError(`dims[${r}] must be an integer, got: ${a}`);if(a<0)throw new RangeError(`dims[${r}] must be a non-negative integer, got: ${a}`);t*=a}return t},mL=(e,t)=>{switch(e.location){case"cpu":return new ar(e.type,e.data,t);case"cpu-pinned":return new ar({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new ar({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new ar({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new ar({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),Td=be(()=>{"use strict";hF(),fF(),EF(),$F(),ar=class{constructor(e,t,r){EL();let a,n;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,a=e.type,n=e.dims,e.location){case"cpu-pinned":{let i=Ja.get(a);if(!i)throw new TypeError(`unsupported type "${a}" to create tensor from pinned buffer`);if(!(e.data instanceof i))throw new TypeError(`buffer should be of type ${i.name}`);this.cpuData=e.data;break}case"texture":{if(a!=="float32")throw new TypeError(`unsupported type "${a}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(a!=="float32"&&a!=="float16"&&a!=="int32"&&a!=="int64"&&a!=="uint32"&&a!=="uint8"&&a!=="bool"&&a!=="uint4"&&a!=="int4")throw new TypeError(`unsupported type "${a}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}case"ml-tensor":{if(a!=="float32"&&a!=="float16"&&a!=="int32"&&a!=="int64"&&a!=="uint32"&&a!=="uint64"&&a!=="int8"&&a!=="uint8"&&a!=="bool"&&a!=="uint4"&&a!=="int4")throw new TypeError(`unsupported type "${a}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let i,o;if(typeof e=="string")if(a=e,o=r,e==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");i=t}else{let H=Ja.get(e);if(H===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e==="float16"&&H===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${H.name} as data.`);e==="uint64"||e==="int64"?i=H.from(t,BigInt):i=H.from(t)}else if(t instanceof H)i=t;else if(t instanceof Uint8ClampedArray)if(e==="uint8")i=Uint8Array.from(t);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(e==="float16"&&t instanceof Uint16Array&&H!==Uint16Array)i=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw new TypeError(`A ${a} tensor's data must be type of ${H}`)}else if(o=t,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let H=typeof e[0];if(H==="string")a="string",i=e;else if(H==="boolean")a="bool",i=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${H}.`)}else if(e instanceof Uint8ClampedArray)a="uint8",i=Uint8Array.from(e);else{let H=ri.get(e.constructor);if(H===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);a=H,i=e}if(o===void 0)o=[i.length];else if(!Array.isArray(o))throw new TypeError("A tensor's dims must be a number array");n=o,this.cpuData=i,this.dataLocation="cpu"}let s=$L(n);if(this.cpuData&&s!==this.cpuData.length&&!((a==="uint4"||a==="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=a,this.dims=n,this.size=s}static async fromImage(e,t){return uL(e,t)}static fromTexture(e,t){return dL(e,t)}static fromGpuBuffer(e,t){return pL(e,t)}static fromMLTensor(e,t){return hL(e,t)}static fromPinnedBuffer(e,t,r){return fL(e,t,r)}toDataURL(e){return cL(this,e)}toImageData(e){return lL(this,e)}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(e){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 t=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}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(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return mL(this,e)}}}),IL=be(()=>{"use strict";Td(),Er=ar}),SL=be(()=>{"use strict";_L(),_H=(e,t)=>{(typeof $t.trace>"u"?!$t.wasm.trace:!$t.trace)||console.timeStamp(`${e}::ORT::${t}`)},Tu=(e,t)=>{let r=new Error().stack?.split(/\r\n|\r|\n/g)||[],a=!1;for(let n=0;n<r.length;n++){if(a&&!r[n].includes("TRACE_FUNC")){let s=`FUNC_${e}::${r[n].trim().split(" ")[1]}`;t&&(s+=`::${t}`),_H("CPU",s);return}r[n].includes("TRACE_FUNC")&&(a=!0)}},an=e=>{(typeof $t.trace>"u"?!$t.wasm.trace:!$t.trace)||Tu("BEGIN",e)},nn=e=>{(typeof $t.trace>"u"?!$t.wasm.trace:!$t.trace)||Tu("END",e)},va=e=>{(typeof $t.trace>"u"?!$t.wasm.trace:!$t.trace)||console.time(`ORT::${e}`)},ya=e=>{(typeof $t.trace>"u"?!$t.wasm.trace:!$t.trace)||console.timeEnd(`ORT::${e}`)}}),mF=be(()=>{"use strict";oL(),IL(),SL(),LL=class AL{constructor(t){this.handler=t}async run(t,r,a){an(),va("InferenceSession.run");let n={},s={};if(typeof t!="object"||t===null||t instanceof Er||Array.isArray(t))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let i=!0;if(typeof r=="object"){if(r===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof Er)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(r)){if(r.length===0)throw new TypeError("'fetches' cannot be an empty array.");i=!1;for(let _ of r){if(typeof _!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(_)===-1)throw new RangeError(`'fetches' contains invalid output name: ${_}.`);n[_]=null}if(typeof a=="object"&&a!==null)s=a;else if(typeof a<"u")throw new TypeError("'options' must be an object.")}else{let _=!1,c=Object.getOwnPropertyNames(r);for(let l of this.outputNames)if(c.indexOf(l)!==-1){let d=r[l];(d===null||d instanceof Er)&&(_=!0,i=!1,n[l]=d)}if(_){if(typeof a=="object"&&a!==null)s=a;else if(typeof a<"u")throw new TypeError("'options' must be an object.")}else s=r}}else if(typeof r<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let _ of this.inputNames)if(typeof t[_]>"u")throw new Error(`input '${_}' is missing in 'feeds'.`);if(i)for(let _ of this.outputNames)n[_]=null;let o=await this.handler.run(t,n,s),H={};for(let _ in o)if(Object.hasOwnProperty.call(o,_)){let c=o[_];c instanceof Er?H[_]=c:H[_]=new Er(c.type,c.data,c.dims)}return ya("InferenceSession.run"),nn(),H}async release(){return this.handler.dispose()}static async create(t,r,a,n){an(),va("InferenceSession.create");let s,i={};if(typeof t=="string"){if(s=t,typeof r=="object"&&r!==null)i=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(s=t,typeof r=="object"&&r!==null)i=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer){let c=t,l=0,d=t.byteLength;if(typeof r=="object"&&r!==null)i=r;else if(typeof r=="number"){if(l=r,!Number.isSafeInteger(l))throw new RangeError("'byteOffset' must be an integer.");if(l<0||l>=c.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${c.byteLength}).`);if(d=t.byteLength-l,typeof a=="number"){if(d=a,!Number.isSafeInteger(d))throw new RangeError("'byteLength' must be an integer.");if(d<=0||l+d>c.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${c.byteLength-l}].`);if(typeof n=="object"&&n!==null)i=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(typeof a<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof r<"u")throw new TypeError("'options' must be an object.");s=new Uint8Array(c,l,d)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[o,H]=await iL(i),_=await o.createInferenceSessionHandler(s,H);return ya("InferenceSession.create"),nn(),new AL(_)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),IF=be(()=>{"use strict";mF(),xd=LL}),SF=be(()=>{"use strict"}),LF=be(()=>{"use strict"}),AF=be(()=>{"use strict"}),gF=be(()=>{"use strict"}),gL={};hi(gL,{InferenceSession:()=>xd,TRACE:()=>_H,TRACE_EVENT_BEGIN:()=>va,TRACE_EVENT_END:()=>ya,TRACE_FUNC_BEGIN:()=>an,TRACE_FUNC_END:()=>nn,Tensor:()=>Er,env:()=>Xe,registerBackend:()=>Ya});on=be(()=>{"use strict";uF(),pF(),IF(),IL(),SF(),LF(),SL(),AF(),gF()}),vd=be(()=>{"use strict"}),bL={};hi(bL,{default:()=>TL});bF=be(()=>{"use strict";FL(),Hn(),yd(),xu="ort-wasm-proxy-worker",vu=globalThis.self?.name===xu,vu&&(self.onmessage=e=>{let{type:t,in:r}=e.data;try{switch(t){case"init-wasm":Dd(r.wasm).then(()=>{Md(r).then(()=>{postMessage({type:t})},a=>{postMessage({type:t,err:a})})},a=>{postMessage({type:t,err:a})});break;case"init-ep":{let{epName:a,env:n}=r;Pd(n,a).then(()=>{postMessage({type:t})},s=>{postMessage({type:t,err:s})});break}case"copy-from":{let{buffer:a}=r,n=uH(a);postMessage({type:t,out:n});break}case"create":{let{model:a,options:n}=r;kd(a,n).then(s=>{postMessage({type:t,out:s})},s=>{postMessage({type:t,err:s})});break}case"release":Rd(r),postMessage({type:t});break;case"run":{let{sessionId:a,inputIndices:n,inputs:s,outputIndices:i,options:o}=r;Od(a,n,s,i,new Array(i.length).fill(null),o).then(H=>{H.some(_=>_[3]!=="cpu")?postMessage({type:t,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:t,out:H},Fd([...s,...H]))},H=>{postMessage({type:t,err:H})});break}case"end-profiling":Gd(r),postMessage({type:t});break;default:}}catch(a){postMessage({type:t,err:a})}}),TL=vu?null:e=>new Worker(e??tr,{type:"module",name:xu})}),xL={};hi(xL,{default:()=>vL});TF=be(()=>{"use strict";vL=GI,FI=globalThis.self?.name?.startsWith("em-pthread"),FI&&GI()}),yd=be(()=>{"use strict";vd(),yu=typeof location>"u"?void 0:location.origin,td=Wt.url>"file:"&&Wt.url<"file;",ZI=()=>{if(td){let e=URL;return new URL(new e("ort.webgpu.bundle.min.mjs",Wt.url).href,yu).href}return Wt.url},tr=ZI(),yL=()=>{if(tr&&!tr.startsWith("blob:"))return tr.substring(0,tr.lastIndexOf("/")+1)},Go=(e,t)=>{try{let r=t??tr;return(r?new URL(e,r):new URL(e)).origin===yu}catch{return!1}},UI=(e,t)=>{let r=t??tr;try{return(r?new URL(e,r):new URL(e)).href}catch{return}},WI=(e,t)=>`${t??"./"}${e}`,Du=async e=>{let t=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(t)},KI=async e=>(await import(e)).default,Cu=(bF(),HH(bL)).default,DL=async()=>{if(!tr)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Go(tr))return[void 0,Cu()];let e=await Du(tr);return[e,Cu(e)]},wu=(TF(),HH(xL)).default,CL=async(e,t,r,a)=>{let n=wu&&!(e||t);if(n)if(tr)n=Go(tr)||a&&!r;else if(a&&!r)n=!0;else throw new Error("cannot determine the script source URL.");if(n)return[void 0,wu];{let s="ort-wasm-simd-threaded.asyncify.mjs",i=e??UI(s,t),o=r&&i&&!Go(i,t),H=o?await Du(i):i??WI(s,t);return[o?H:void 0,await KI(H)]}}}),Hn=be(()=>{"use strict";yd(),Fo=!1,Xs=!1,Bu=!1,VI=()=>{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}},jI=()=>{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}},qI=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},Dd=async e=>{if(Fo)return Promise.resolve();if(Xs)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Bu)throw new Error("previous call to 'initializeWebAssembly()' failed.");Xs=!0;let t=e.initTimeout,r=e.numThreads;if(e.simd!==!1){if(e.simd==="relaxed"){if(!qI())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!jI())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let a=VI();r>1&&!a&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+r+", 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."),e.numThreads=r=1);let n=e.wasmPaths,s=typeof n=="string"?n:void 0,i=n?.mjs,o=i?.href??i,H=n?.wasm,_=H?.href??H,c=e.wasmBinary,[l,d]=await CL(o,s,r>1,!!c||!!_),h=!1,$=[];if(t>0&&$.push(new Promise(m=>{setTimeout(()=>{h=!0,m()},t)})),$.push(new Promise((m,S)=>{let I={numThreads:r};if(c)I.wasmBinary=c,I.locateFile=g=>g;else if(_||s)I.locateFile=g=>_??s+g;else if(o&&o.indexOf("blob:")!==0)I.locateFile=g=>new URL(g,o).href;else if(l){let g=yL();g&&(I.locateFile=T=>g+T)}d(I).then(g=>{Xs=!1,Fo=!0,Nu=g,m(),l&&URL.revokeObjectURL(l)},g=>{Xs=!1,Bu=!0,S(g)})})),await Promise.race($),h)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},ke=()=>{if(Fo&&Nu)return Nu;throw new Error("WebAssembly is not initialized yet.")}}),Cd=be(()=>{"use strict";Hn(),rr=(e,t)=>{let r=ke(),a=r.lengthBytesUTF8(e)+1,n=r._malloc(a);return r.stringToUTF8(e,n,a),t.push(n),n},cH=(e,t,r,a)=>{if(typeof e=="object"&&e!==null){if(r.has(e))throw new Error("Circular reference in options");r.add(e)}Object.entries(e).forEach(([n,s])=>{let i=t?t+n:n;if(typeof s=="object")cH(s,i+".",r,a);else if(typeof s=="string"||typeof s=="number")a(i,s.toString());else if(typeof s=="boolean")a(i,s?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof s}`)})},Ce=e=>{let t=ke(),r=t.stackSave();try{let a=t.PTR_SIZE,n=t.stackAlloc(2*a);t._OrtGetLastError(n,n+a);let s=Number(t.getValue(n,a===4?"i32":"i64")),i=t.getValue(n+a,"*"),o=i?t.UTF8ToString(i):"";throw new Error(`${e} ERROR_CODE: ${s}, ERROR_MESSAGE: ${o}`)}finally{t.stackRestore(r)}}}),xF=be(()=>{"use strict";Hn(),Cd(),wL=e=>{let t=ke(),r=0,a=[],n=e||{};try{if(e?.logSeverityLevel===void 0)n.logSeverityLevel=2;else if(typeof e.logSeverityLevel!="number"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${e.logSeverityLevel}`);if(e?.logVerbosityLevel===void 0)n.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!="number"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(n.terminate=!1);let s=0;return e?.tag!==void 0&&(s=rr(e.tag,a)),r=t._OrtCreateRunOptions(n.logSeverityLevel,n.logVerbosityLevel,!!n.terminate,s),r===0&&Ce("Can't create run options."),e?.extra!==void 0&&cH(e.extra,"",new WeakSet,(i,o)=>{let H=rr(i,a),_=rr(o,a);t._OrtAddRunConfigEntry(r,H,_)!==0&&Ce(`Can't set a run config entry: ${i} - ${o}.`)}),[r,a]}catch(s){throw r!==0&&t._OrtReleaseRunOptions(r),a.forEach(i=>t._free(i)),s}}}),vF=be(()=>{"use strict";Hn(),Cd(),XI=e=>{switch(e){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"layout":return 3;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${e}`)}},zI=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},JI=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some(r=>(typeof r=="string"?r:r.name)==="webgpu")&&(e.enableMemPattern=!1)},Zo=(e,t,r,a)=>{let n=rr(t,a),s=rr(r,a);ke()._OrtAddSessionConfigEntry(e,n,s)!==0&&Ce(`Can't set a session config entry: ${t} - ${r}.`)},La=(e,t,r,a)=>{let n=rr(t,a),s=rr(r,a);e.push([n,s])},QI=async(e,t,r)=>{let a=t.executionProviders;for(let n of a){let s=typeof n=="string"?n:n.name,i=[];switch(s){case"webnn":if(s="WEBNN",typeof n!="string"){let l=n?.deviceType;l&&Zo(e,"deviceType",l,r)}break;case"webgpu":{s="WebGPU";let l;if(typeof n!="string"){let h=n;if(h.device)if(typeof GPUDevice<"u"&&h.device instanceof GPUDevice)l=h.device;else throw new Error("Invalid GPU device set in WebGPU EP options.");let{enableGraphCapture:$}=t;if(typeof $=="boolean"&&$&&La(i,"enableGraphCapture","1",r),typeof h.preferredLayout=="string"&&La(i,"preferredLayout",h.preferredLayout,r),h.forceCpuNodeNames){let m=Array.isArray(h.forceCpuNodeNames)?h.forceCpuNodeNames:[h.forceCpuNodeNames];La(i,"forceCpuNodeNames",m.join(`
22
- `),r)}h.validationMode&&La(i,"validationMode",h.validationMode,r)}let d=ke().webgpuRegisterDevice(l);if(d){let[h,$,m]=d;La(i,"deviceId",h.toString(),r),La(i,"webgpuInstance",$.toString(),r),La(i,"webgpuDevice",m.toString(),r)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${s}`)}let o=rr(s,r),H=i.length,_=0,c=0;if(H>0){_=ke()._malloc(H*ke().PTR_SIZE),r.push(_),c=ke()._malloc(H*ke().PTR_SIZE),r.push(c);for(let l=0;l<H;l++)ke().setValue(_+l*ke().PTR_SIZE,i[l][0],"*"),ke().setValue(c+l*ke().PTR_SIZE,i[l][1],"*")}await ke()._OrtAppendExecutionProvider(e,o,_,c,H)!==0&&Ce(`Can't append execution provider: ${s}.`)}},NL=async e=>{let t=ke(),r=0,a=[],n=e||{};JI(n);try{let s=XI(n.graphOptimizationLevel??"all"),i=zI(n.executionMode??"sequential"),o=typeof n.logId=="string"?rr(n.logId,a):0,H=n.logSeverityLevel??2;if(!Number.isInteger(H)||H<0||H>4)throw new Error(`log severity level is not valid: ${H}`);let _=n.logVerbosityLevel??0;if(!Number.isInteger(_)||_<0||_>4)throw new Error(`log verbosity level is not valid: ${_}`);let c=typeof n.optimizedModelFilePath=="string"?rr(n.optimizedModelFilePath,a):0;if(r=t._OrtCreateSessionOptions(s,!!n.enableCpuMemArena,!!n.enableMemPattern,i,!!n.enableProfiling,0,o,H,_,c),r===0&&Ce("Can't create session options."),n.executionProviders&&await QI(r,n,a),n.enableGraphCapture!==void 0){if(typeof n.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${n.enableGraphCapture}`);Zo(r,"enableGraphCapture",n.enableGraphCapture.toString(),a)}if(n.freeDimensionOverrides)for(let[l,d]of Object.entries(n.freeDimensionOverrides)){if(typeof l!="string")throw new Error(`free dimension override name must be a string: ${l}`);if(typeof d!="number"||!Number.isInteger(d)||d<0)throw new Error(`free dimension override value must be a non-negative integer: ${d}`);let h=rr(l,a);t._OrtAddFreeDimensionOverride(r,h,d)!==0&&Ce(`Can't set a free dimension override: ${l} - ${d}.`)}return n.extra!==void 0&&cH(n.extra,"",new WeakSet,(l,d)=>{Zo(r,l,d,a)}),[r,a]}catch(s){throw r!==0&&t._OrtReleaseSessionOptions(r)!==0&&Ce("Can't release session options."),a.forEach(i=>t._free(i)),s}}}),fs=be(()=>{"use strict";Qa=e=>{switch(e){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: ${e}`)}},Qo=e=>{switch(e){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: ${e}`)}},rs=(e,t)=>{let r=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],a=typeof t=="number"?t:t.reduce((n,s)=>n*s,1);return r>0?Math.ceil(a*r):void 0},ii=e=>{switch(e){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: ${e}`)}},lH=e=>{switch(e){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: ${e}`)}},wd=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Nd=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",rd=e=>{switch(e){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: ${e}`)}}}),BL=be(()=>{"use strict";vd(),Bd=async e=>{if(typeof e=="string"){let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let r=t.headers.get("Content-Length"),a=r?parseInt(r,10):0;if(a<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let n=t.body.getReader(),s;try{s=new ArrayBuffer(a)}catch(o){if(o instanceof RangeError){let H=Math.ceil(a/65536);s=new WebAssembly.Memory({initial:H,maximum:H}).buffer}else throw o}let i=0;for(;;){let{done:o,value:H}=await n.read();if(o)break;let _=H.byteLength;new Uint8Array(s,i,_).set(H),i+=_}return new Uint8Array(s,0,a)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),yF=be(()=>{"use strict";fs(),ML=(e,t)=>new(ii(t))(e)}),kL=be(()=>{"use strict";fs(),YI=["V","I","W","E","F"],eS=(e,t)=>{console.log(`[${YI[e]},${new Date().toISOString()}]${t}`)},PL=(e,t)=>{tS=e,rS=t},aS=(e,t)=>{let r=lH(e),a=lH(tS);r>=a&&eS(r,typeof t=="function"?t():t)},wt=(...e)=>{rS&&aS(...e)}}),DF=be(()=>{"use strict";fs(),kL(),Mu=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),ad=(e,t)=>{if(t==="int32")return e;let r=Mu.get(t);if(!r)throw new Error(`WebNN backend does not support data type: ${t}`);let a=r/8;if(e.byteLength%a!==0)throw new Error(`Invalid Uint8Array length - must be a multiple of ${a}.`);let n=e.byteLength/a,s=new(ii(t))(e.buffer,e.byteOffset,n);switch(t){case"int64":case"uint64":{let i=new Int32Array(n);for(let o=0;o<n;o++){let H=s[o];if(H>2147483647n||H<-2147483648n)throw new Error("Can not convert int64 data to int32 - value out of range.");i[o]=Number(H)}return new Uint8Array(i.buffer)}case"int8":case"uint8":case"uint32":{if(t==="uint32"&&s.some(o=>o>2147483647))throw new Error("Can not convert uint32 data to int32 - value out of range.");let i=Int32Array.from(s,Number);return new Uint8Array(i.buffer)}default:throw new Error(`Unsupported data conversion from ${t} to 'int32'`)}},Pu=(e,t)=>{if(t==="int32")return e;if(e.byteLength%4!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 4 (int32).");let r=e.byteLength/4,a=new Int32Array(e.buffer,e.byteOffset,r);switch(t){case"int64":{let n=BigInt64Array.from(a,BigInt);return new Uint8Array(n.buffer)}case"uint64":{if(a.some(s=>s<0))throw new Error("Can not convert int32 data to uin64 - negative value found.");let n=BigUint64Array.from(a,BigInt);return new Uint8Array(n.buffer)}case"int8":{if(a.some(s=>s<-128||s>127))throw new Error("Can not convert int32 data to int8 - value out of range.");let n=Int8Array.from(a,Number);return new Uint8Array(n.buffer)}case"uint8":{if(a.some(n=>n<0||n>255))throw new Error("Can not convert int32 data to uint8 - value out of range.");return Uint8Array.from(a,Number)}case"uint32":{if(a.some(s=>s<0))throw new Error("Can not convert int32 data to uint32 - negative value found.");let n=Uint32Array.from(a,Number);return new Uint8Array(n.buffer)}default:throw new Error(`Unsupported data conversion from 'int32' to ${t}`)}},nS=1,ku=()=>nS++,sS=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),Ru=(e,t)=>{let r=Mu.get(e);if(!r)throw new Error(`WebNN backend does not support data type: ${e}`);return t.length>0?Math.ceil(t.reduce((a,n)=>a*n)*r/8):0},Ou=class{constructor(e){this.isDataConverted=!1;let{sessionId:t,context:r,tensor:a,dataType:n,shape:s,fallbackDataType:i}=e;this.sessionId=t,this.mlContext=r,this.mlTensor=a,this.dataType=n,this.tensorShape=s,this.fallbackDataType=i}get tensor(){return this.mlTensor}get type(){return this.dataType}get fallbackType(){return this.fallbackDataType}get shape(){return this.tensorShape}get byteLength(){return Ru(this.dataType,this.tensorShape)}destroy(){wt("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e){if(this.fallbackDataType){let t=await this.mlContext.readTensor(this.mlTensor),r=Pu(new Uint8Array(t),this.dataType);if(e){(e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)).set(r);return}else return r.buffer}else return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(e,t,r){return this.mlContext===e&&this.dataType===t&&this.tensorShape.length===r.length&&this.tensorShape.every((a,n)=>a===r[n])}setIsDataConverted(e){this.isDataConverted=e}},Gu=class{constructor(e,t){this.tensorManager=e,this.wrapper=t}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(e,t,r,a){let n=this.tensorManager.getMLContext(e),s=this.tensorManager.getMLOpSupportLimits(e),i;if(!s?.input.dataTypes.includes(t)){if(i=sS.get(t),!i||s?.input.dataTypes.includes(i))throw new Error(`WebNN backend does not support data type: ${t}`);wt("verbose",()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${t} to ${i}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(n,t,r))return this.wrapper.tensor;if(a){if(this.wrapper.byteLength!==Ru(t,r))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 o=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,t,r,o,!0,!0,i),a&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){let t=e;if(this.wrapper){if(this.wrapper.fallbackType)if(this.wrapper.fallbackType==="int32")t=ad(e,this.wrapper.type),this.wrapper.setIsDataConverted(!0);else throw new Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`);if(e.byteLength===this.wrapper.byteLength){this.wrapper.write(t);return}else wt("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor()}this.activeUpload?this.activeUpload.set(t):this.activeUpload=new Uint8Array(t)}async download(e){if(this.activeUpload){let t=this.wrapper?.isDataConverted?Pu(this.activeUpload,this.wrapper?.type):this.activeUpload;if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(t):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(t);return}else return t.buffer}if(!this.wrapper)throw new Error("Tensor has not been created.");return e?this.wrapper.read(e):this.wrapper.read()}},iS=class{constructor(e){this.backend=e,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(e){let t=this.backend.getMLContext(e);if(!t)throw new Error("MLContext not found for session.");return t}getMLOpSupportLimits(e){return this.backend.getMLOpSupportLimits(e)}reserveTensorId(){let e=ku();return this.tensorTrackersById.set(e,new Gu(this)),e}releaseTensorId(e){let t=this.tensorTrackersById.get(e);t&&(this.tensorTrackersById.delete(e),t.tensorWrapper&&this.releaseTensor(t.tensorWrapper))}async ensureTensor(e,t,r,a,n){wt("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${t}, dataType: ${r}, shape: ${a}, copyOld: ${n}}`);let s=this.tensorTrackersById.get(t);if(!s)throw new Error("Tensor not found.");return s.ensureTensor(e,r,a,n)}upload(e,t){let r=this.tensorTrackersById.get(e);if(!r)throw new Error("Tensor not found.");r.upload(t)}async download(e,t){wt("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t?.byteLength}}`);let r=this.tensorTrackersById.get(e);if(!r)throw new Error("Tensor not found.");return r.download(t)}releaseTensorsForSession(e){for(let t of this.freeTensors)t.sessionId===e&&t.destroy();this.freeTensors=this.freeTensors.filter(t=>t.sessionId!==e)}registerTensor(e,t,r,a){let n=this.getMLContext(e),s=ku(),i=new Ou({sessionId:e,context:n,tensor:t,dataType:r,shape:a});return this.tensorTrackersById.set(s,new Gu(this,i)),this.externalTensors.add(i),s}async getCachedTensor(e,t,r,a,n,s,i){let o=this.getMLContext(e);for(let[_,c]of this.freeTensors.entries())if(c.canReuseTensor(o,t,r)){wt("verbose",()=>`[WebNN] Reusing tensor {dataType: ${t}, ${i?`fallbackDataType: ${i},`:""} shape: ${r}`);let l=this.freeTensors.splice(_,1)[0];return l.sessionId=e,l}wt("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${t}, ${i?`fallbackDataType: ${i},`:""} shape: ${r}}`);let H=await o.createTensor({dataType:i??t,shape:r,dimensions:r,usage:a,writable:n,readable:s});return new Ou({sessionId:e,context:o,tensor:H,dataType:t,shape:r,fallbackDataType:i})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},RL=(...e)=>new iS(...e)}),OL={};hi(OL,{WebNNBackend:()=>GL});CF=be(()=>{"use strict";fs(),Hn(),yF(),DF(),kL(),zs=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),oS=(e,t)=>{if(e===t)return!0;if(e===void 0||t===void 0)return!1;let r=Object.keys(e).sort(),a=Object.keys(t).sort();return r.length===a.length&&r.every((n,s)=>n===a[s]&&e[n]===t[n])},GL=class{constructor(e){this.tensorManager=RL(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],this.sessionGraphInputs=new Map,this.sessionGraphOutputs=new Map,this.temporaryGraphInputs=[],this.temporaryGraphOutputs=[],this.temporarySessionTensorIds=new Map,this.mlOpSupportLimitsBySessionId=new Map,PL(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){wt("verbose",()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){wt("verbose",()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let t=this.temporarySessionTensorIds.get(e);if(t){for(let r of t)wt("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${r}}`),this.tensorManager.releaseTensorId(r);this.temporarySessionTensorIds.delete(e),this.activeSessionId=void 0}}async createMLContext(e){if(e instanceof GPUDevice){let r=this.mlContextCache.findIndex(a=>a.gpuDevice===e);if(r!==-1)return this.mlContextCache[r].mlContext;{let a=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:a}),a}}else if(e===void 0){let r=this.mlContextCache.findIndex(a=>a.options===void 0&&a.gpuDevice===void 0);if(r!==-1)return this.mlContextCache[r].mlContext;{let a=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:a}),a}}let t=this.mlContextCache.findIndex(r=>oS(r.options,e));if(t!==-1)return this.mlContextCache[t].mlContext;{let r=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:r}),r}}registerMLContext(e,t){this.mlContextBySessionId.set(e,t);let r=this.sessionIdsByMLContext.get(t);r||(r=new Set,this.sessionIdsByMLContext.set(t,r)),r.add(e),this.mlOpSupportLimitsBySessionId.has(e)||this.mlOpSupportLimitsBySessionId.set(e,t.opSupportLimits()),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(e,this.temporaryGraphInputs),this.temporaryGraphInputs=[]),this.temporaryGraphOutputs.length>0&&(this.sessionGraphOutputs.set(e,this.temporaryGraphOutputs),this.temporaryGraphOutputs=[])}onReleaseSession(e){this.sessionGraphInputs.delete(e),this.sessionGraphOutputs.delete(e);let t=this.mlContextBySessionId.get(e);if(!t)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e),this.mlOpSupportLimitsBySessionId.delete(e);let r=this.sessionIdsByMLContext.get(t);if(r.delete(e),r.size===0){this.sessionIdsByMLContext.delete(t);let a=this.mlContextCache.findIndex(n=>n.mlContext===t);a!==-1&&this.mlContextCache.splice(a,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}getMLOpSupportLimits(e){return this.mlOpSupportLimitsBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){wt("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,r,a,n){let s=zs.get(r);if(!s)throw new Error(`Unsupported ONNX data type: ${r}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,t,s,a,n)}async createTemporaryTensor(e,t,r){wt("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${t}, shape: ${r}}`);let a=zs.get(t);if(!a)throw new Error(`Unsupported ONNX data type: ${t}`);let n=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,n,a,r,!1);let s=this.temporarySessionTensorIds.get(e);return s?s.push(n):this.temporarySessionTensorIds.set(e,[n]),n}uploadTensor(e,t){if(!ke().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");wt("verbose",()=>`[WebNN] uploadTensor {tensorId: ${e}, data: ${t.byteLength}}`),this.tensorManager.upload(e,t)}async downloadTensor(e,t){return this.tensorManager.download(e,t)}createMLTensorDownloader(e,t){return async()=>{let r=await this.tensorManager.download(e);return ML(r,t)}}registerMLTensor(e,t,r,a){let n=zs.get(r);if(!n)throw new Error(`Unsupported ONNX data type: ${r}`);let s=this.tensorManager.registerTensor(e,t,n,a);return wt("verbose",()=>`[WebNN] registerMLTensor {tensor: ${t}, dataType: ${n}, dimensions: ${a}} -> {tensorId: ${s}}`),s}registerMLConstant(e,t,r,a,n,s,i=!1){if(!s)throw new Error("External mounted files are not available.");let o=e;e.startsWith("./")&&(o=e.substring(2));let H=s.get(o);if(!H)throw new Error(`File with name ${o} not found in preloaded files.`);if(t+r>H.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let _=H.slice(t,t+r).buffer,c;switch(n.dataType){case"float32":c=new Float32Array(_);break;case"float16":c=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(_):new Uint16Array(_);break;case"int32":c=new Int32Array(_);break;case"uint32":c=new Uint32Array(_);break;case"int64":if(i){let l=ad(new Uint8Array(_),"int64");c=new Int32Array(l.buffer),n.dataType="int32"}else c=new BigInt64Array(_);break;case"uint64":c=new BigUint64Array(_);break;case"int8":c=new Int8Array(_);break;case"int4":case"uint4":case"uint8":c=new Uint8Array(_);break;default:throw new Error(`Unsupported data type: ${n.dataType} in creating WebNN Constant from external data.`)}return wt("verbose",()=>`[WebNN] registerMLConstant {dataType: ${n.dataType}, shape: ${n.shape}}} ${i?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),a.constant(n,c)}registerGraphInput(e){this.temporaryGraphInputs.push(e)}registerGraphOutput(e){this.temporaryGraphOutputs.push(e)}isGraphInput(e,t){let r=this.sessionGraphInputs.get(e);return r?r.includes(t):!1}isGraphOutput(e,t){let r=this.sessionGraphOutputs.get(e);return r?r.includes(t):!1}isGraphInputOutputTypeSupported(e,t,r=!0){let a=zs.get(Qa(t)),n=this.mlOpSupportLimitsBySessionId.get(e);return typeof a>"u"?!1:r?!!n?.input.dataTypes.includes(a):!!n?.output.dataTypes.includes(a)}flush(){}}}),FL=be(()=>{"use strict";on(),xF(),vF(),fs(),Hn(),Cd(),BL(),HS=(e,t)=>{ke()._OrtInit(e,t)!==0&&Ce("Can't initialize onnxruntime.")},Md=async e=>{HS(e.wasm.numThreads,lH(e.logLevel))},Pd=async(e,t)=>{ke().asyncInit?.();let r=e.webgpu.adapter;if(t==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(r){if(typeof r.limits!="object"||typeof r.features!="object"||typeof r.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let a=e.webgpu.powerPreference;if(a!==void 0&&a!=="low-power"&&a!=="high-performance")throw new Error(`Invalid powerPreference setting: "${a}"`);let n=e.webgpu.forceFallbackAdapter;if(n!==void 0&&typeof n!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${n}"`);if(r=await navigator.gpu.requestAdapter({powerPreference:a,forceFallbackAdapter:n}),!r)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(t==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment");if(t==="webgpu"&&ke().webgpuInit(a=>{e.webgpu.device=a}),t==="webnn"){let a=new(CF(),HH(OL)).WebNNBackend(e);ke().webnnInit([a,()=>a.reserveTensorId(),n=>a.releaseTensorId(n),async(n,s,i,o,H)=>a.ensureTensor(n,s,i,o,H),(n,s)=>{a.uploadTensor(n,s)},async(n,s)=>a.downloadTensor(n,s),(n,s)=>a.registerMLContext(n,s),!!e.trace])}},Aa=new Map,_S=e=>{let t=ke(),r=t.stackSave();try{let a=t.PTR_SIZE,n=t.stackAlloc(2*a);t._OrtGetInputOutputCount(e,n,n+a)!==0&&Ce("Can't get session input/output count.");let s=a===4?"i32":"i64";return[Number(t.getValue(n,s)),Number(t.getValue(n+a,s))]}finally{t.stackRestore(r)}},Fu=(e,t)=>{let r=ke(),a=r.stackSave(),n=0;try{let s=r.PTR_SIZE,i=r.stackAlloc(2*s);r._OrtGetInputOutputMetadata(e,t,i,i+s)!==0&&Ce("Can't get session input/output metadata.");let o=Number(r.getValue(i,"*"));n=Number(r.getValue(i+s,"*"));let H=r.HEAP32[n/4];if(H===0)return[o,0];let _=r.HEAPU32[n/4+1],c=[];for(let l=0;l<_;l++){let d=Number(r.getValue(n+8+l*s,"*"));c.push(d!==0?r.UTF8ToString(d):Number(r.getValue(n+8+(l+_)*s,"*")))}return[o,H,c]}finally{r.stackRestore(a),n!==0&&r._OrtFree(n)}},uH=e=>{let t=ke(),r=t._malloc(e.byteLength);if(r===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,r),[r,e.byteLength]},kd=async(e,t)=>{let r,a,n=ke();Array.isArray(e)?[r,a]=e:e.buffer===n.HEAPU8.buffer?[r,a]=[e.byteOffset,e.byteLength]:[r,a]=uH(e);let s=0,i=0,o=0,H=[],_=[],c=[];try{if([i,H]=await NL(t),t?.externalData&&n.mountExternalData){let x=[];for(let v of t.externalData){let k=typeof v=="string"?v:v.path;x.push(Bd(typeof v=="string"?v:v.data).then(L=>{n.mountExternalData(k,L)}))}await Promise.all(x)}for(let x of t?.executionProviders??[])if((typeof x=="string"?x:x.name)==="webnn"){if(n.shouldTransferToMLTensor=!1,typeof x!="string"){let v=x,k=v?.context,L=v?.gpuDevice,V=v?.deviceType,K=v?.powerPreference;k?n.currentContext=k:L?n.currentContext=await n.webnnCreateMLContext(L):n.currentContext=await n.webnnCreateMLContext({deviceType:V,powerPreference:K})}else n.currentContext=await n.webnnCreateMLContext();break}s=await n._OrtCreateSession(r,a,i),n.webgpuOnCreateSession?.(s),s===0&&Ce("Can't create a session."),n.jsepOnCreateSession?.(),n.currentContext&&(n.webnnRegisterMLContext(s,n.currentContext),n.currentContext=void 0,n.shouldTransferToMLTensor=!0);let[l,d]=_S(s),h=!!t?.enableGraphCapture,$=[],m=[],S=[],I=[],g=[];for(let x=0;x<l;x++){let[v,k,L]=Fu(s,x);v===0&&Ce("Can't get an input name."),_.push(v);let V=n.UTF8ToString(v);$.push(V),S.push(k===0?{name:V,isTensor:!1}:{name:V,isTensor:!0,type:Qo(k),shape:L})}for(let x=0;x<d;x++){let[v,k,L]=Fu(s,x+l);v===0&&Ce("Can't get an output name."),c.push(v);let V=n.UTF8ToString(v);m.push(V),I.push(k===0?{name:V,isTensor:!1}:{name:V,isTensor:!0,type:Qo(k),shape:L});{if(h&&t?.preferredOutputLocation===void 0){g.push("gpu-buffer");continue}let K=typeof t?.preferredOutputLocation=="string"?t.preferredOutputLocation:t?.preferredOutputLocation?.[V]??"cpu",X=n.webnnIsGraphOutput;if(K==="cpu"&&X&&X(s,V)){g.push("ml-tensor-cpu-output");continue}if(K!=="cpu"&&K!=="cpu-pinned"&&K!=="gpu-buffer"&&K!=="ml-tensor")throw new Error(`Not supported preferred output location: ${K}.`);if(h&&K!=="gpu-buffer")throw new Error(`Not supported preferred output location: ${K}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);g.push(K)}}let T=null;return g.some(x=>x==="gpu-buffer"||x==="ml-tensor"||x==="ml-tensor-cpu-output")&&(o=n._OrtCreateBinding(s),o===0&&Ce("Can't create IO binding."),T={handle:o,outputPreferredLocations:g,outputPreferredLocationsEncoded:g.map(x=>x==="ml-tensor-cpu-output"?"ml-tensor":x).map(x=>rd(x))}),Aa.set(s,[s,_,c,T,h,!1]),[s,$,m,S,I]}catch(l){throw _.forEach(d=>n._OrtFree(d)),c.forEach(d=>n._OrtFree(d)),o!==0&&n._OrtReleaseBinding(o)!==0&&Ce("Can't release IO binding."),s!==0&&n._OrtReleaseSession(s)!==0&&Ce("Can't release session."),l}finally{n._free(r),i!==0&&n._OrtReleaseSessionOptions(i)!==0&&Ce("Can't release session options."),H.forEach(l=>n._free(l)),n.unmountExternalData?.()}},Rd=e=>{let t=ke(),r=Aa.get(e);if(!r)throw new Error(`cannot release session. invalid session id: ${e}`);let[a,n,s,i,o]=r;i&&(o&&t._OrtClearBoundOutputs(i.handle)!==0&&Ce("Can't clear bound outputs."),t._OrtReleaseBinding(i.handle)!==0&&Ce("Can't release IO binding.")),t.jsepOnReleaseSession?.(e),t.webnnOnReleaseSession?.(e),t.webgpuOnReleaseSession?.(e),n.forEach(H=>t._OrtFree(H)),s.forEach(H=>t._OrtFree(H)),t._OrtReleaseSession(a)!==0&&Ce("Can't release session."),Aa.delete(e)},Zu=async(e,t,r,a,n,s,i=!1)=>{if(!e){t.push(0);return}let o=ke(),H=o.PTR_SIZE,_=e[0],c=e[1],l=e[3],d=l,h,$;if(_==="string"&&(l==="gpu-buffer"||l==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(i&&l!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${s} when enableGraphCapture is true.`);if(l==="gpu-buffer"){let I=e[2].gpuBuffer;$=rs(Qa(_),c);{let g=o.webgpuRegisterBuffer;if(!g)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');h=g(I,a)}}else if(l==="ml-tensor"){let I=e[2].mlTensor;$=rs(Qa(_),c);let g=o.webnnRegisterMLTensor;if(!g)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');h=g(a,I,Qa(_),c)}else{let I=e[2];if(Array.isArray(I)){$=H*I.length,h=o._malloc($),r.push(h);for(let g=0;g<I.length;g++){if(typeof I[g]!="string")throw new TypeError(`tensor data at index ${g} is not a string`);o.setValue(h+g*H,rr(I[g],r),"*")}}else{let g=o.webnnIsGraphInput,T=o.webnnIsGraphOutput;if(_!=="string"&&g&&T){let x=o.UTF8ToString(n);if(g(a,x)||T(a,x)){let v=Qa(_);$=rs(v,c),d="ml-tensor";let k=o.webnnCreateTemporaryTensor,L=o.webnnUploadTensor;if(!k||!L)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let V=await k(a,v,c);L(V,new Uint8Array(I.buffer,I.byteOffset,I.byteLength)),h=V}else $=I.byteLength,h=o._malloc($),r.push(h),o.HEAPU8.set(new Uint8Array(I.buffer,I.byteOffset,$),h)}else $=I.byteLength,h=o._malloc($),r.push(h),o.HEAPU8.set(new Uint8Array(I.buffer,I.byteOffset,$),h)}}let m=o.stackSave(),S=o.stackAlloc(4*c.length);try{c.forEach((g,T)=>o.setValue(S+T*H,g,H===4?"i32":"i64"));let I=o._OrtCreateTensor(Qa(_),h,$,S,c.length,rd(d));I===0&&Ce(`Can't create tensor for input/output. session=${a}, index=${s}.`),t.push(I)}finally{o.stackRestore(m)}},Od=async(e,t,r,a,n,s)=>{let i=ke(),o=i.PTR_SIZE,H=Aa.get(e);if(!H)throw new Error(`cannot run inference. invalid session id: ${e}`);let _=H[0],c=H[1],l=H[2],d=H[3],h=H[4],$=H[5],m=t.length,S=a.length,I=0,g=[],T=[],x=[],v=[],k=[],L=i.stackSave(),V=i.stackAlloc(m*o),K=i.stackAlloc(m*o),X=i.stackAlloc(S*o),Q=i.stackAlloc(S*o);try{[I,g]=wL(s),va("wasm prepareInputOutputTensor");for(let N=0;N<m;N++)await Zu(r[N],T,v,e,c[t[N]],t[N],h);for(let N=0;N<S;N++)await Zu(n[N],x,v,e,l[a[N]],m+a[N],h);ya("wasm prepareInputOutputTensor");for(let N=0;N<m;N++)i.setValue(V+N*o,T[N],"*"),i.setValue(K+N*o,c[t[N]],"*");for(let N=0;N<S;N++)i.setValue(X+N*o,x[N],"*"),i.setValue(Q+N*o,l[a[N]],"*");if(d&&!$){let{handle:N,outputPreferredLocations:G,outputPreferredLocationsEncoded:te}=d;if(c.length!==m)throw new Error(`input count from feeds (${m}) is expected to be always equal to model's input count (${c.length}).`);va("wasm bindInputsOutputs");for(let B=0;B<m;B++){let O=t[B];await i._OrtBindInput(N,c[O],T[B])!==0&&Ce(`Can't bind input[${B}] for session=${e}.`)}for(let B=0;B<S;B++){let O=a[B];n[B]?.[3]?(k.push(x[B]),i._OrtBindOutput(N,l[O],x[B],0)!==0&&Ce(`Can't bind pre-allocated output[${B}] for session=${e}.`)):i._OrtBindOutput(N,l[O],0,te[O])!==0&&Ce(`Can't bind output[${B}] to ${G[B]} for session=${e}.`)}ya("wasm bindInputsOutputs"),Aa.set(e,[_,c,l,d,h,!0])}i.jsepOnRunStart?.(_),i.webnnOnRunStart?.(_);let z;d?z=await i._OrtRunWithBinding(_,d.handle,S,X,I):z=await i._OrtRun(_,K,V,m,Q,S,X,I),z!==0&&Ce("failed to call OrtRun().");let M=[],F=[];va("wasm ProcessOutputTensor");for(let N=0;N<S;N++){let G=Number(i.getValue(X+N*o,"*"));if(G===x[N]||k.includes(x[N])){M.push(n[N]),G!==x[N]&&i._OrtReleaseTensor(G)!==0&&Ce("Can't release tensor.");continue}let te=i.stackSave(),B=i.stackAlloc(4*o),O=!1,U,Y=0;try{i._OrtGetTensorData(G,B,B+o,B+2*o,B+3*o)!==0&&Ce(`Can't access output tensor data on index ${N}.`);let Se=o===4?"i32":"i64",We=Number(i.getValue(B,Se));Y=i.getValue(B+o,"*");let ce=i.getValue(B+o*2,"*"),Bt=Number(i.getValue(B+o*3,Se)),Ke=[];for(let Fe=0;Fe<Bt;Fe++)Ke.push(Number(i.getValue(ce+Fe*o,Se)));i._OrtFree(ce)!==0&&Ce("Can't free memory for tensor dims.");let Ht=Ke.reduce((Fe,ve)=>Fe*ve,1);U=Qo(We);let Mt=d?.outputPreferredLocations[a[N]];if(U==="string"){if(Mt==="gpu-buffer"||Mt==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Fe=[];for(let ve=0;ve<Ht;ve++){let _t=i.getValue(Y+ve*o,"*"),Tr=i.getValue(Y+(ve+1)*o,"*"),De=ve===Ht-1?void 0:Tr-_t;Fe.push(i.UTF8ToString(_t,De))}M.push([U,Ke,Fe,"cpu"])}else if(Mt==="gpu-buffer"&&Ht>0){let Fe=i.webgpuGetBuffer;if(!Fe)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let ve=Fe(Y),_t=rs(We,Ht);if(_t===void 0||!wd(U))throw new Error(`Unsupported data type: ${U}`);O=!0;{i.webgpuRegisterBuffer(ve,e,Y);let Tr=i.webgpuCreateDownloader(ve,_t,e);M.push([U,Ke,{gpuBuffer:ve,download:async()=>{let De=await Tr();return new(ii(U))(De)},dispose:()=>{i._OrtReleaseTensor(G)!==0&&Ce("Can't release tensor.")}},"gpu-buffer"])}}else if(Mt==="ml-tensor"&&Ht>0){let Fe=i.webnnEnsureTensor,ve=i.webnnIsGraphInputOutputTypeSupported;if(!Fe||!ve)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(rs(We,Ht)===void 0||!Nd(U))throw new Error(`Unsupported data type: ${U}`);if(!ve(e,U,!1))throw new Error(`preferredLocation "ml-tensor" for ${U} output is not supported by current WebNN Context.`);let _t=await Fe(e,Y,We,Ke,!1);O=!0,M.push([U,Ke,{mlTensor:_t,download:i.webnnCreateMLTensorDownloader(Y,U),dispose:()=>{i.webnnReleaseTensorId(Y),i._OrtReleaseTensor(G)}},"ml-tensor"])}else if(Mt==="ml-tensor-cpu-output"&&Ht>0){let Fe=i.webnnCreateMLTensorDownloader(Y,U)(),ve=M.length;O=!0,F.push((async()=>{let _t=[ve,await Fe];return i.webnnReleaseTensorId(Y),i._OrtReleaseTensor(G),_t})()),M.push([U,Ke,[],"cpu"])}else{let Fe=ii(U),ve=new Fe(Ht);new Uint8Array(ve.buffer,ve.byteOffset,ve.byteLength).set(i.HEAPU8.subarray(Y,Y+ve.byteLength)),M.push([U,Ke,ve,"cpu"])}}finally{i.stackRestore(te),U==="string"&&Y&&i._free(Y),O||i._OrtReleaseTensor(G)}}d&&!h&&(i._OrtClearBoundOutputs(d.handle)!==0&&Ce("Can't clear bound outputs."),Aa.set(e,[_,c,l,d,h,!1]));for(let[N,G]of await Promise.all(F))M[N][2]=G;return ya("wasm ProcessOutputTensor"),M}finally{i.webnnOnRunEnd?.(_),i.stackRestore(L),r.forEach(z=>{z&&z[3]==="gpu-buffer"&&i.webgpuUnregisterBuffer(z[2].gpuBuffer)}),n.forEach(z=>{z&&z[3]==="gpu-buffer"&&i.webgpuUnregisterBuffer(z[2].gpuBuffer)}),T.forEach(z=>i._OrtReleaseTensor(z)),x.forEach(z=>i._OrtReleaseTensor(z)),v.forEach(z=>i._free(z)),I!==0&&i._OrtReleaseRunOptions(I),g.forEach(z=>i._free(z))}},Gd=e=>{let t=ke(),r=Aa.get(e);if(!r)throw new Error("invalid session id");let a=r[0],n=t._OrtEndProfiling(a);n===0&&Ce("Can't get an profile file name."),t._OrtFree(n)},Fd=e=>{let t=[];for(let r of e){let a=r[2];!Array.isArray(a)&&"buffer"in a&&t.push(a.buffer)}return t}}),XL=be(()=>{"use strict";on(),FL(),Hn(),yd(),ga=()=>!!Xe.wasm.proxy&&typeof document<"u",Jn=!1,Js=!1,Qs=!1,Wo=new Map,Ka=(e,t)=>{let r=Wo.get(e);r?r.push(t):Wo.set(e,[t])},Va=()=>{if(Jn||!Js||Qs||!_r)throw new Error("worker not ready")},cS=e=>{switch(e.data.type){case"init-wasm":Jn=!1,e.data.err?(Qs=!0,Uu[1](e.data.err)):(Js=!0,Uu[0]()),Uo&&(URL.revokeObjectURL(Uo),Uo=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=Wo.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}default:}},ZL=async()=>{if(!Js){if(Jn)throw new Error("multiple calls to 'initWasm()' detected.");if(Qs)throw new Error("previous call to 'initWasm()' failed.");if(Jn=!0,ga())return new Promise((e,t)=>{_r?.terminate(),DL().then(([r,a])=>{try{_r=a,_r.onerror=s=>t(s),_r.onmessage=cS,Uu=[e,t];let n={type:"init-wasm",in:Xe};!n.in.wasm.wasmPaths&&(r||td)&&(n.in.wasm.wasmPaths={wasm:new URL("ort-wasm-simd-threaded.asyncify.wasm",Wt.url).href}),_r.postMessage(n),Uo=r}catch(n){t(n)}},t)});try{await Dd(Xe.wasm),await Md(Xe),Js=!0}catch(e){throw Qs=!0,e}finally{Jn=!1}}},UL=async e=>{if(ga())return Va(),new Promise((t,r)=>{Ka("init-ep",[t,r]);let a={type:"init-ep",in:{epName:e,env:Xe}};_r.postMessage(a)});await Pd(Xe,e)},WL=async e=>ga()?(Va(),new Promise((t,r)=>{Ka("copy-from",[t,r]);let a={type:"copy-from",in:{buffer:e}};_r.postMessage(a,[e.buffer])})):uH(e),KL=async(e,t)=>{if(ga()){if(t?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Va(),new Promise((r,a)=>{Ka("create",[r,a]);let n={type:"create",in:{model:e,options:{...t}}},s=[];e instanceof Uint8Array&&s.push(e.buffer),_r.postMessage(n,s)})}else return kd(e,t)},VL=async e=>{if(ga())return Va(),new Promise((t,r)=>{Ka("release",[t,r]);let a={type:"release",in:e};_r.postMessage(a)});Rd(e)},jL=async(e,t,r,a,n,s)=>{if(ga()){if(r.some(i=>i[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(n.some(i=>i))throw new Error("pre-allocated output tensor is not supported for proxy.");return Va(),new Promise((i,o)=>{Ka("run",[i,o]);let H=r,_={type:"run",in:{sessionId:e,inputIndices:t,inputs:H,outputIndices:a,options:s}};_r.postMessage(_,Fd(H))})}else return Od(e,t,r,a,n,s)},qL=async e=>{if(ga())return Va(),new Promise((t,r)=>{Ka("end-profiling",[t,r]);let a={type:"end-profiling",in:e};_r.postMessage(a)});Gd(e)}}),wF=be(()=>{"use strict";on(),XL(),fs(),vd(),BL(),Wu=(e,t)=>{switch(e.location){case"cpu":return[e.type,e.dims,e.data,"cpu"];case"gpu-buffer":return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[e.type,e.dims,{mlTensor:e.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${e.location} for ${t()}`)}},lS=e=>{switch(e[3]){case"cpu":return new Er(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!wd(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:r,download:a,dispose:n}=e[2];return Er.fromGpuBuffer(r,{dataType:t,dims:e[1],download:a,dispose:n})}case"ml-tensor":{let t=e[0];if(!Nd(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:r,download:a,dispose:n}=e[2];return Er.fromMLTensor(r,{dataType:t,dims:e[1],download:a,dispose:n})}default:throw new Error(`invalid data location: ${e[3]}`)}},zL=class{async fetchModelAndCopyToWasmMemory(e){return WL(await Bd(e))}async loadModel(e,t){an();let r;typeof e=="string"?r=await this.fetchModelAndCopyToWasmMemory(e):r=e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await KL(r,t),nn()}async dispose(){return VL(this.sessionId)}async run(e,t,r){an();let a=[],n=[];Object.entries(e).forEach(l=>{let d=l[0],h=l[1],$=this.inputNames.indexOf(d);if($===-1)throw new Error(`invalid input '${d}'`);a.push(h),n.push($)});let s=[],i=[];Object.entries(t).forEach(l=>{let d=l[0],h=l[1],$=this.outputNames.indexOf(d);if($===-1)throw new Error(`invalid output '${d}'`);s.push(h),i.push($)});let o=a.map((l,d)=>Wu(l,()=>`input "${this.inputNames[n[d]]}"`)),H=s.map((l,d)=>l?Wu(l,()=>`output "${this.outputNames[i[d]]}"`):null),_=await jL(this.sessionId,n,o,i,H,r),c={};for(let l=0;l<_.length;l++)c[this.outputNames[i[l]]]=s[l]??lS(_[l]);return nn(),c}startProfiling(){}endProfiling(){qL(this.sessionId)}}}),JL={};hi(JL,{OnnxruntimeWebAssemblyBackend:()=>sd,initializeFlags:()=>nd,wasmBackend:()=>QL});NF=be(()=>{"use strict";on(),XL(),wF(),nd=()=>{(typeof Xe.wasm.initTimeout!="number"||Xe.wasm.initTimeout<0)&&(Xe.wasm.initTimeout=0);let e=Xe.wasm.simd;if(typeof e!="boolean"&&e!==void 0&&e!=="fixed"&&e!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${e}". Reset it to \`false\` and ignore SIMD feature checking.`),Xe.wasm.simd=!1),typeof Xe.wasm.proxy!="boolean"&&(Xe.wasm.proxy=!1),typeof Xe.wasm.trace!="boolean"&&(Xe.wasm.trace=!1),typeof Xe.wasm.numThreads!="number"||!Number.isInteger(Xe.wasm.numThreads)||Xe.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)Xe.wasm.numThreads=1;else{let t=typeof navigator>"u"?cF("node:os").cpus().length:navigator.hardwareConcurrency;Xe.wasm.numThreads=Math.min(4,Math.ceil((t||1)/2))}},sd=class{async init(e){nd(),await ZL(),await UL(e)}async createInferenceSessionHandler(e,t){let r=new zL;return await r.loadModel(e,t),r}},QL=new sd});on();on();on();BF="1.26.0-dev.20260416-b7804b056c",MF=gL;{let e=(NF(),HH(JL)).wasmBackend;Ya("webgpu",e,5),Ya("webnn",e,5),Ya("cpu",e,10),Ya("wasm",e,10)}Object.defineProperty(Xe.versions,"web",{value:BF,enumerable:!0});RF=Object.freeze({auto:null,gpu:null,cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",coreml:"coreml",webnn:{name:"webnn",deviceType:"cpu"},"webnn-npu":{name:"webnn",deviceType:"npu"},"webnn-gpu":{name:"webnn",deviceType:"gpu"},"webnn-cpu":{name:"webnn",deviceType:"cpu"}});OF={0:"verbose",1:"info",2:"warning",3:"error",4:"fatal"},lr=[],uS=Symbol.for("onnxruntime");if(uS in globalThis)_s=globalThis[uS];else if(Ie.IS_NODE_ENV){switch(_s=iF,process.platform){case"win32":lr.push("dml");break;case"linux":process.arch==="x64"&&lr.push("cuda");break;case"darwin":lr.push("coreml");break}lr.push("webgpu"),lr.push("cpu"),id=["cpu"]}else _s=sL,Ie.IS_WEBNN_AVAILABLE&&lr.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),Ie.IS_WEBGPU_AVAILABLE&&lr.push("webgpu"),lr.push("wasm"),id=["wasm"];GF=_s.InferenceSession;dS=Promise.resolve(),Qn=null;pS=Promise.resolve();lt=_s?.env;if(lt){let e=function(t){let r=eA(t);lt.logLevel=OF[r]};if(lt.wasm){if(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&lt.versions?.web&&!lt.wasm.wasmPaths){let t=`https://cdn.jsdelivr.net/npm/onnxruntime-web@${lt.versions.web}/dist/`;lt.wasm.wasmPaths=Ie.IS_SAFARI?{mjs:`${t}ort-wasm-simd-threaded.mjs`,wasm:`${t}ort-wasm-simd-threaded.wasm`}:{mjs:`${t}ort-wasm-simd-threaded.asyncify.mjs`,wasm:`${t}ort-wasm-simd-threaded.asyncify.wasm`}}lt.wasm.proxy=!1}lt.webgpu&&(lt.webgpu.powerPreference="high-performance"),e(ge.logLevel??ur.WARNING),ge.backends.onnx={...lt,setLogLevel:e}}ba=async(e,t,r)=>{let a=await tA(new Uint8Array(e),t);return(async n=>{let s=Zd(),i=Object.fromEntries(Object.entries(n).map(([H,_])=>[H,(s?_.clone():_).ort_tensor])),o=await rA(a,i);return Array.isArray(r)?r.map(H=>new j(o[H])):new j(o[r])})},rn=class{static session_options={};static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=ba([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=ba([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=ba([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=ba([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=ba([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=ba([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=ba([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=ba([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}},UF=Object.freeze({auto:"auto",gpu:"gpu",cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",coreml:"coreml",webnn:"webnn","webnn-npu":"webnn-npu","webnn-gpu":"webnn-gpu","webnn-cpu":"webnn-cpu"}),Ku=Ie.IS_NODE_ENV?"cpu":"wasm";WF=(function(){let e;return async function(){if(e===void 0)if(!Ie.IS_WEBGPU_AVAILABLE)e=!1;else try{e=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{e=!1}return e}})(),it=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16",q2:"q2",q2f16:"q2f16",q1:"q1",q1f16:"q1f16"}),hS=it.fp32,fS=Object.freeze({[UF.wasm]:it.q8}),oi=Object.freeze({[it.fp32]:"",[it.fp16]:"_fp16",[it.int8]:"_int8",[it.uint8]:"_uint8",[it.q8]:"_quantized",[it.q4]:"_q4",[it.q2]:"_q2",[it.q1]:"_q1",[it.q4f16]:"_q4f16",[it.q2f16]:"_q2f16",[it.q1f16]:"_q1f16",[it.bnb4]:"_bnb4"});Hi=Object.freeze({float32:Float32Array,float16:typeof Float16Array<"u"?Float16Array: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}),j=class et{get dims(){return this.ort_tensor.dims}set dims(t){this.ort_tensor.dims=t}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}ort_tensor;constructor(...t){return aA(t[0])?this.ort_tensor=t[0]:this.ort_tensor=new Ul(t[0],t[1],t[2]),new Proxy(this,{get:(r,a)=>{if(typeof a=="string"){let n=Number(a);if(Number.isInteger(n))return r._getitem(n)}return r[a]},set:(r,a,n)=>r[a]=n})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){let[t,...r]=this.dims;if(r.length>0){let a=r.reduce((n,s)=>n*s);for(let n=0;n<t;++n)yield this._subarray(n,a,r)}else yield*this.data}_getitem(t){let[r,...a]=this.dims;if(t=Zr(t,r),a.length>0){let n=a.reduce((s,i)=>s*i);return this._subarray(t,n,a)}else return new et(this.type,[this.data[t]],a)}indexOf(t){let r=this.data;for(let a=0;a<r.length;++a)if(r[a]==t)return a;return-1}_subarray(t,r,a){let n=t*r,s=(t+1)*r,i="subarray"in this.data?this.data.subarray(n,s):this.data.slice(n,s);return new et(this.type,i,a)}item(){let t=this.data;if(t.length!==1)throw new Error(`a Tensor with ${t.length} elements cannot be converted to Scalar`);return t[0]}tolist(){return KF(this.data,this.dims)}sigmoid(){return this.clone().sigmoid_()}sigmoid_(){let t=this.data;for(let r=0;r<t.length;++r)t[r]=1/(1+Math.exp(-t[r]));return this}map(t){return this.clone().map_(t)}map_(t){let r=this.data;for(let a=0;a<r.length;++a)r[a]=t(r[a],a,r);return this}mul(t){return this.clone().mul_(t)}mul_(t){let r=this.data;for(let a=0;a<r.length;++a)r[a]*=t;return this}div(t){return this.clone().div_(t)}div_(t){let r=this.data;for(let a=0;a<r.length;++a)r[a]/=t;return this}add(t){return this.clone().add_(t)}add_(t){let r=this.data;for(let a=0;a<r.length;++a)r[a]+=t;return this}sub(t){return this.clone().sub_(t)}sub_(t){let r=this.data;for(let a=0;a<r.length;++a)r[a]-=t;return this}clone(){return new et(this.type,this.data.slice(),this.dims.slice())}slice(...t){let r=[],a=[];for(let c=0;c<this.dims.length;++c){let l=t[c];if(l==null)a.push([0,this.dims[c]]),r.push(this.dims[c]);else if(typeof l=="number")l=Zr(l,this.dims[c],c),a.push([l,l+1]);else if(Array.isArray(l)&&l.length===2){let[d,h]=l;if(d=d===null?0:Zr(d,this.dims[c],c,!1),h=h===null?this.dims[c]:Zr(h,this.dims[c],c,!1),d>h)throw new Error(`Invalid slice: ${l}`);let $=[Math.max(d,0),Math.min(h,this.dims[c])];a.push($),r.push($[1]-$[0])}else throw new Error(`Invalid slice: ${l}`)}let n=a.map(([c,l])=>l-c),s=n.reduce((c,l)=>c*l),i=this.data,o=new i.constructor(s),H=this.stride(),_=!0;for(let c=1;c<n.length;++c)if(a[c][0]!==0||a[c][1]!==this.dims[c]){_=!1;break}if(_){let c=a[0][0]*H[0],l=a[0][1]*H[0];if(ArrayBuffer.isView(i))o.set(i.subarray(c,l));else if(Array.isArray(i)){let d=i.slice(c,l);for(let h=0;h<d.length;++h)o[h]=d[h]}else throw new Error("Unsupported data type for slicing")}else for(let c=0;c<s;++c){let l=0;for(let d=n.length-1,h=c;d>=0;--d){let $=n[d];l+=(h%$+a[d][0])*H[d],h=Math.floor(h/$)}o[c]=i[l]}return new et(this.type,o,r)}permute(...t){return iA(this,t)}transpose(...t){return this.permute(...t)}sum(t=null,r=!1){return this.norm(1,t,r)}norm(t="fro",r=null,a=!1){if(t==="fro")t=2;else if(typeof t=="string")throw Error(`Unsupported norm: ${t}`);let n=this.data,s=n instanceof BigInt64Array||n instanceof BigUint64Array;if(s&&t!==1)throw Error(`Expected a floating point tensor as input. Got ${this.type}`);let i,o;if(s?(i=(l,d)=>l+d,o=0n):(i=(l,d)=>l+d**t,o=0),r===null){let l=n.reduce(i,o);return t!==1&&(l=l**(1/t)),new et(this.type,[l],[])}let[H,_,c]=ai(i,this,r,a);if(t!==1)for(let l=0;l<_.length;++l)_[l]=_[l]**(1/t);return new et(H,_,c)}normalize_(t=2,r=1){r=Zr(r,this.dims.length);let a=this.norm(t,r,!0),n=this.data,s=a.data;for(let i=0;i<n.length;++i){let o=0;for(let H=this.dims.length-1,_=i,c=1;H>=0;--H){let l=this.dims[H];if(H!==r){let d=_%l;o+=d*c,c*=this.dims[H]}_=Math.floor(_/l)}n[i]/=s[o]}return this}normalize(t=2,r=1){return this.clone().normalize_(t,r)}stride(){return Vu(this.dims)}squeeze(t=null){return new et(this.type,this.data,ES(this.dims,t))}squeeze_(t=null){return this.dims=ES(this.dims,t),this}unsqueeze(t){return new et(this.type,this.data,$S(this.dims,t))}unsqueeze_(t){return this.dims=$S(this.dims,t),this}flatten_(t=0,r=-1){r=(r+this.dims.length)%this.dims.length;let a=this.dims.slice(0,t),n=this.dims.slice(t,r+1),s=this.dims.slice(r+1);return this.dims=[...a,n.reduce((i,o)=>i*o,1),...s],this}flatten(t=0,r=-1){return this.clone().flatten_(t,r)}view(...t){let r=-1;for(let n=0;n<t.length;++n)if(t[n]===-1){if(r!==-1)throw new Error("Only one dimension can be inferred");r=n}let a=this.data;if(r!==-1){let n=t.reduce((s,i,o)=>o!==r?s*i:s,1);t[r]=a.length/n}return new et(this.type,a,t)}neg_(){let t=this.data;for(let r=0;r<t.length;++r)t[r]=-t[r];return this}neg(){return this.clone().neg_()}gt(t){let r=new Uint8Array(this.data.length),a=this.data;for(let n=0;n<a.length;++n)r[n]=a[n]>t?1:0;return new et("bool",r,this.dims)}lt(t){let r=new Uint8Array(this.data.length),a=this.data;for(let n=0;n<a.length;++n)r[n]=a[n]<t?1:0;return new et("bool",r,this.dims)}clamp_(t,r){let a=this.data;for(let n=0;n<a.length;++n)a[n]=Math.min(Math.max(a[n],t),r);return this}clamp(t,r){return this.clone().clamp_(t,r)}round_(){let t=this.data;for(let r=0;r<t.length;++r)t[r]=Math.round(t[r]);return this}round(){return this.clone().round_()}mean(t=null,r=!1){return bH(this,t,r)}min(t=null,r=!1){if(t===null){let i=ed(this.data)[0];return new et(this.type,[i],[])}let[a,n,s]=ai((i,o)=>Math.min(i,o),this,t,r,1/0);return new et(a,n,s)}max(t=null,r=!1){if(t===null){let i=nt(this.data)[0];return new et(this.type,[i],[])}let[a,n,s]=ai((i,o)=>Math.max(i,o),this,t,r,-1/0);return new et(a,n,s)}argmin(t=null,r=!1){if(t!==null)throw new Error("`dim !== null` not yet implemented.");let a=ed(this.data)[1];return new et("int64",[BigInt(a)],[])}argmax(t=null,r=!1){if(t!==null)throw new Error("`dim !== null` not yet implemented.");let a=nt(this.data)[1];return new et("int64",[BigInt(a)],[])}repeat(...t){if(t.length<this.dims.length)throw new Error(`Number of dimensions of repeat dims (${t.length}) cannot be smaller than number of dimensions of tensor (${this.dims.length})`);if(t.every(c=>c===1)){if(t.length===this.dims.length)return this.clone();let c=t.length-this.dims.length,l=Array(c).fill(1).concat(this.dims);return new et(this.type,this.data.slice(),l)}let r=t.length-this.dims.length,a=Array(r).fill(1).concat(this.dims),n=a.map((c,l)=>c*t[l]),s=n.reduce((c,l)=>c*l,1),i=this.data,o=new i.constructor(s),H=Vu(a),_=Vu(n);for(let c=0;c<s;++c){let l=c,d=0;for(let h=0;h<n.length;++h){let $=Math.floor(l/_[h]);l=l%_[h];let m=$%a[h];d+=m*H[h]}o[c]=i[d]}return new et(this.type,o,n)}tile(...t){if(t.length<this.dims.length){let r=this.dims.length-t.length;t=Array(r).fill(1).concat(t)}return this.repeat(...t)}to(t){if(this.type===t)return this;if(!Hi.hasOwnProperty(t))throw new Error(`Unsupported type: ${t}`);let r,a=["int64","uint64"].includes(this.type),n=["int64","uint64"].includes(t);if(a&&!n)r=Number;else if(!a&&n)["float16","float32","float64"].includes(this.type)?r=s=>BigInt(Math.floor(s)):r=BigInt;else if(this.type==="float16"&&t=="float32"&&this.data instanceof Uint16Array)return new et(t,sF(this.data),this.dims);return new et(t,Hi[t].from(this.data,r),this.dims)}};Ko=e=>new j("int64",e,[e.length]);XF=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];he=class extends zt{return_token_type_ids=!1;padding_side="right";constructor(e,t){if(super(),this._tokenizerJSON=e,this._tokenizerConfig=t,this._tokenizer=new OG(e,t),this.config=t,this.padding_side=t.padding_side??this.padding_side,this.mask_token=ja(t,"mask_token"),this.mask_token_id=this._tokenizer.token_to_id(this.mask_token),this.pad_token=ja(t,"pad_token","eos_token"),this.pad_token_id=this._tokenizer.token_to_id(this.pad_token),this.sep_token=ja(t,"sep_token"),this.sep_token_id=this._tokenizer.token_to_id(this.sep_token),this.unk_token=ja(t,"unk_token"),this.unk_token_id=this._tokenizer.token_to_id(this.unk_token),this.bos_token=ja(t,"bos_token"),this.bos_token_id=this._tokenizer.token_to_id(this.bos_token),this.eos_token=ja(t,"eos_token"),this.eos_token_id=this._tokenizer.token_to_id(this.eos_token),this.chat_template=t.chat_template??null,Array.isArray(this.chat_template)){let a=Object.create(null);for(let{name:n,template:s}of this.chat_template){if(typeof n!="string"||typeof s!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');a[n]=s}this.chat_template=a}this._compiled_template_cache=new Map;let r=QF(this._tokenizer);this.all_special_ids=r.map(a=>a.id),this.all_special_tokens=r.map(a=>a.content)}static async from_pretrained(e,{progress_callback:t=null,config:r=null,cache_dir:a=null,local_files_only:n=!1,revision:s="main"}={}){let i=await lA(e,{progress_callback:t,config:r,cache_dir:a,local_files_only:n,revision:s});return new this(...i)}get_vocab(){return this._tokenizer.get_vocab()}get model_max_length(){return this._tokenizerConfig.model_max_length??1/0}get add_eos_token(){return this._tokenizerConfig.add_eos_token}get add_bos_token(){return this._tokenizerConfig.add_bos_token}convert_tokens_to_ids(e){return typeof e=="string"?this._tokenizer.token_to_id(e):e.map(t=>this._tokenizer.token_to_id(t))}_call(e,t={}){let{text_pair:r=null,add_special_tokens:a=!0,padding:n=!1,return_token_type_ids:s=null}=t,{truncation:i=null,max_length:o=null}=t,H=t.return_tensor??!0,_=Array.isArray(e),c;if(_){if(e.length===0)throw Error("text array must be non-empty");if(r!==null){if(Array.isArray(r)){if(e.length!==r.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");c=e.map((d,h)=>this._encode_plus(d,{text_pair:r[h],add_special_tokens:a,return_token_type_ids:s}))}else c=e.map(d=>this._encode_plus(d,{add_special_tokens:a,return_token_type_ids:s}))}else{if(e==null)throw Error("text may not be null or undefined");if(Array.isArray(r))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");c=[this._encode_plus(e,{text_pair:r,add_special_tokens:a,return_token_type_ids:s})]}if(o===null?o=this.model_max_length:i===null&&(n===!0?(fe.warn("`max_length` is ignored when `padding: true` and there is no truncation strategy. To pad to max length, use `padding: 'max_length'`."),o=this.model_max_length):n===!1&&(fe.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."),i=!0)),n===!0&&(o=Math.min(nt(c.map(d=>d.input_ids.length))[0],o??1/0)),o=Math.min(o,this.model_max_length??1/0),n||i)for(let d=0;d<c.length;++d)c[d].input_ids.length!==o&&(c[d].input_ids.length>o?i&&JF(c[d],o):n&&zF(c[d],o,h=>h==="input_ids"?this.pad_token_id:0,this.padding_side));let l={};if(H){if(!(n&&i)&&c.some(h=>{for(let $ of Object.keys(h))if(h[$].length!==c[0][$]?.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.");let d=[c.length,c[0].input_ids.length];for(let h of Object.keys(c[0]))l[h]=new j("int64",BigInt64Array.from(c.flatMap($=>$[h]).map(BigInt)),d)}else{for(let d of Object.keys(c[0]))l[d]=c.map(h=>h[d]);if(!_)for(let d of Object.keys(l))l[d]=l[d][0]}return l}_encode_text(e){return e===null?null:this._tokenizer.encode(e).tokens}_encode_plus(e,{text_pair:t=null,add_special_tokens:r=!0,return_token_type_ids:a=null}={}){let{ids:n,attention_mask:s,token_type_ids:i}=this._tokenizer.encode(e,{text_pair:t,add_special_tokens:r,return_token_type_ids:a??this.return_token_type_ids});return{input_ids:n,attention_mask:s,...i?{token_type_ids:i}:{}}}tokenize(e,{pair:t=null,add_special_tokens:r=!1}={}){return this._tokenizer.tokenize(e,{text_pair:t,add_special_tokens:r})}encode(e,{text_pair:t=null,add_special_tokens:r=!0,return_token_type_ids:a=null}={}){return this._tokenizer.encode(e,{text_pair:t,add_special_tokens:r,return_token_type_ids:a}).ids}batch_decode(e,t={}){return e instanceof j&&(e=e.tolist()),e.map(r=>this.decode(r,t))}decode(e,t={}){if(e instanceof j&&(e=Jd(e)),!Array.isArray(e)||e.length===0||!TO(e[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(e,t)}decode_single(e,{skip_special_tokens:t=!1,clean_up_tokenization_spaces:r=null}){return this._tokenizer.decode(e,{skip_special_tokens:t,clean_up_tokenization_spaces:r})}get_chat_template({chat_template:e=null,tools:t=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){let r=this.chat_template;if(e!==null&&Object.hasOwn(r,e))e=r[e];else if(e===null)if(t!==null&&"tool_use"in r)e=r.tool_use;else if("default"in r)e=r.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(r).sort()}.`)}else if(e===null)if(this.chat_template)e=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 e}apply_chat_template(e,t={}){let{tools:r=null,documents:a=null,chat_template:n=null,add_generation_prompt:s=!1,tokenize:i=!0,padding:o=!1,truncation:H=!1,max_length:_=null,return_tensor:c=!0,return_dict:l=!0,tokenizer_kwargs:d={},...h}=t;if(n=this.get_chat_template({chat_template:n,tools:r}),typeof n!="string")throw Error(`chat_template must be a string, but got ${typeof n}`);let $=this._compiled_template_cache.get(n);$===void 0&&($=new B6(n),this._compiled_template_cache.set(n,$));let m=Object.create(null);for(let I of XF){let g=ja(this.config,I);g&&(m[I]=g)}let S=$.render({messages:e,add_generation_prompt:s,tools:r,documents:a,...m,...h});if(i){let I=this._call(S,{add_special_tokens:!1,padding:o,truncation:H,max_length:_,return_tensor:c,...d});return l?I:I.input_ids}return S}};uA={};us(uA,{AlbertTokenizer:()=>dA,AutoTokenizer:()=>we,BartTokenizer:()=>pA,BertTokenizer:()=>hA,BlenderbotSmallTokenizer:()=>fA,BlenderbotTokenizer:()=>EA,BloomTokenizer:()=>$A,CLIPTokenizer:()=>IA,CamembertTokenizer:()=>mA,CodeGenTokenizer:()=>LA,CodeLlamaTokenizer:()=>SA,CohereAsrTokenizer:()=>gA,CohereTokenizer:()=>AA,ConvBertTokenizer:()=>bA,DebertaTokenizer:()=>xA,DebertaV2Tokenizer:()=>TA,DistilBertTokenizer:()=>vA,ElectraTokenizer:()=>yA,EsmTokenizer:()=>DA,FalconTokenizer:()=>CA,GPT2Tokenizer:()=>BA,GPTNeoXTokenizer:()=>NA,GemmaTokenizer:()=>wA,HerbertTokenizer:()=>MA,LlamaTokenizer:()=>PA,M2M100Tokenizer:()=>kA,MBart50Tokenizer:()=>OA,MBartTokenizer:()=>Yd,MPNetTokenizer:()=>ZA,MarianTokenizer:()=>RA,MgpstrTokenizer:()=>GA,MobileBertTokenizer:()=>FA,NllbTokenizer:()=>UA,NougatTokenizer:()=>WA,PreTrainedTokenizer:()=>he,Qwen2Tokenizer:()=>KA,RoFormerTokenizer:()=>jA,RobertaTokenizer:()=>VA,SiglipTokenizer:()=>qA,SpeechT5Tokenizer:()=>XA,SqueezeBertTokenizer:()=>zA,T5Tokenizer:()=>JA,TokenizersBackend:()=>he,VitsTokenizer:()=>QA,Wav2Vec2CTCTokenizer:()=>YA,WhisperTokenizer:()=>tg,XLMRobertaTokenizer:()=>rg,XLMTokenizer:()=>ag});dA=class extends he{return_token_type_ids=!0},pA=class extends he{},hA=class extends he{return_token_type_ids=!0},fA=class extends he{},EA=class extends he{},$A=class extends he{},mA=class extends he{},IA=class extends he{},SA=class extends he{},LA=class extends he{},AA=class extends he{},gA=class extends he{},bA=class extends he{return_token_type_ids=!0},TA=class extends he{return_token_type_ids=!0},xA=class extends he{return_token_type_ids=!0},vA=class extends he{},yA=class extends he{return_token_type_ids=!0},DA=class extends he{},CA=class extends he{},wA=class extends he{},NA=class extends he{},BA=class extends he{},MA=class extends he{return_token_type_ids=!0},PA=class extends he{padding_side="left"},kA=class extends he{constructor(e,t){super(e,t),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.all_special_tokens.filter(r=>this.languageRegex.test(r)).map(r=>r.slice(2,-2)),this.lang_to_token=r=>`__${r}__`}_build_translation_inputs(e,t,r){return Qd(this,e,t,r)}},RA=class extends he{constructor(e,t){super(e,t),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=Array.from(this.get_vocab().keys()).filter(r=>this.languageRegex.test(r)),fe.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(e){if(e===null)return null;let[t,...r]=e.trim().split(this.languageRegex);if(r.length===0)return super._encode_text(t);if(r.length===2){let[a,n]=r;return this.supported_language_codes.includes(a)||fe.warn(`Unsupported language code "${a}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),$r([a],super._encode_text(n))}}},Yd=class extends he{constructor(e,t){super(e,t),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.all_special_tokens.filter(r=>this.languageRegex.test(r)).map(r=>r),this.lang_to_token=r=>r}_build_translation_inputs(e,t,r){return Qd(this,e,t,r)}},OA=class extends Yd{},GA=class extends he{},FA=class extends he{return_token_type_ids=!0},ZA=class extends he{},UA=class extends he{constructor(e,t){super(e,t),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.all_special_tokens.filter(r=>this.languageRegex.test(r)),this.lang_to_token=r=>r}_build_translation_inputs(e,t,r){return Qd(this,e,t,r)}},WA=class extends he{},KA=class extends he{},VA=class extends he{},jA=class extends he{return_token_type_ids=!0},qA=class extends he{},XA=class extends he{},zA=class extends he{return_token_type_ids=!0},JA=class extends he{},YF=class extends Lr{decode_chain(e){let t="";for(let r=1;r<e.length;r+=2)t+=e[r];return[t]}},QA=class extends he{constructor(e,t){super(e,t),this._tokenizer.decoder=new YF({type:"VitsDecoder"})}},YA=class extends he{},eg=[["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"]],Yo=new Map(eg),eZ=new Map([...eg.map(([e,t])=>[t,e]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);rZ="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",mS=new RegExp(`^[${rZ}]+$`,"gu"),aZ=.1,tg=class extends he{get timestamp_begin(){return this._tokenizer.token_to_id("<|notimestamps|>")+1}_decode_asr(e,{return_timestamps:t=!1,return_language:r=!1,time_precision:a=null,force_full_sequences:n=!0}={}){if(a===null)throw Error("Must specify time_precision");let s=null,i=t==="word";function o(){return{language:s,timestamp:[null,null],text:""}}let H=[],_=o(),c=0,l=this.timestamp_begin,h=l+1500,$=[],m=[],S=!1,I=null,g=new Set(this.all_special_ids);for(let v of e){let k=v.tokens,L=i?v.token_timestamps:null,V=null,K=l;if("stride"in v){let[z,M,F]=v.stride;if(c-=M,I=z-F,M&&(K=M/a+l),F)for(let N=k.length-1;N>=0;--N){let G=Number(k[N]);if(G>=l){if(V!==null&&(G-l)*a<I)break;V=G}}}let X=[],Q=[];for(let z=0;z<k.length;++z){let M=Number(k[z]);if(g.has(M)){let F=this.decode([M]),N=Yo.get(F.slice(2,-2));if(N!==void 0){if(s!==null&&N!==s&&!t){$.push(X);let G=this.findLongestCommonSequence($)[0],te=this.decode(G);_.text=te,H.push(_),$=[],X=[],_=o()}s=_.language=N}}else if(M>=l&&M<=h){let F=(M-l)*a+c,N=ti(F,2);if(V!==null&&M>=V)S=!0;else if(S||$.length>0&&M<K)S=!1;else if(_.timestamp[0]===null)_.timestamp[0]=N;else if(N!==_.timestamp[0]){_.timestamp[1]=N,$.push(X),i&&m.push(Q);let[G,te]=this.findLongestCommonSequence($,m),B=this.decode(G);if(_.text=B,i&&(_.words=this.collateWordTimestamps(G,te,s),_.words.length>0&&_.timestamp[1]!==null))for(let O of _.words)O.timestamp[1]>_.timestamp[1]&&_.timestamp[1]>=O.timestamp[0]&&(O.timestamp[1]=_.timestamp[1]);H.push(_),$=[],X=[],m=[],Q=[],_=o()}}else if(X.push(M),i){let F=ti(L[z]+c,2),N;if(z+1<L.length){N=ti(L[z+1]+c,2);let G=this.decode([M]);mS.test(G)&&(N=ti(Math.min(F+a,N),2))}else N=null;Q.push([F,N])}}if("stride"in v){let[z,M,F]=v.stride;c+=z-F}X.length>0?($.push(X),i&&m.push(Q)):$.every(z=>z.length===0)&&(_=o(),$=[],X=[],m=[],Q=[])}if($.length>0){if(n&&t)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.");let[v,k]=this.findLongestCommonSequence($,m),L=this.decode(v);_.text=L,i&&(_.words=this.collateWordTimestamps(v,k,s)),H.push(_)}let T=Object.create(null),x=H.map(v=>v.text).join("");if(t||r){for(let v=0;v<H.length;++v){let k=H[v];t||delete k.timestamp,r||delete k.language}if(i){let v=[];for(let k of H)for(let L of k.words)v.push(L);T={chunks:v}}else T={chunks:H}}return[x,T]}findLongestCommonSequence(e,t=null){let r=e[0],a=r.length,n=[],s=Array.isArray(t)&&t.length>0,i=s?[]:null,o=s?t[0]:null;for(let H=1;H<e.length;++H){let _=e[H],c=0,l=[a,a,0,0],d=_.length;for(let T=1;T<a+d;++T){let x=Math.max(0,a-T),v=Math.min(a,a+d-T),k=r.slice(x,v),L=Math.max(0,T-a),V=Math.min(d,T),K=_.slice(L,V);if(k.length!==K.length)throw new Error("There is a bug within whisper `decode_asr` function, please report it. Dropping to prevent bad inference.");let X;s?X=k.filter((M,F)=>M===K[F]&&o[x+F][0]-aZ<=t[H][L+F][0]).length:X=k.filter((M,F)=>M===K[F]).length;let Q=T/1e4,z=X/T+Q;X>1&&z>c&&(c=z,l=[x,v,L,V])}let[h,$,m,S]=l,I=Math.floor(($+h)/2),g=Math.floor((S+m)/2);if(s&&c===0&&a>0){let T=o[a-1][0],x=t[H].findIndex(v=>v[0]>=T);g=x===-1?_.length:x}n.push(...r.slice(0,I)),r=_.slice(g),a=r.length,s&&(i.push(...o.slice(0,I)),o=t[H].slice(g))}return n.push(...r),s?(i.push(...o),[n,i]):[n,[]]}collateWordTimestamps(e,t,r){let[a,n,s]=this.combineTokensIntoWords(e,r),i=[];for(let o=0;o<a.length;++o){let H=s[o];i.push({text:a[o],timestamp:[t[H.at(0)][0],t[H.at(-1)][1]]})}return i}combineTokensIntoWords(e,t,r=`"'\u201C\xA1\xBF([{-`,a=`"'.\u3002,\uFF0C!\uFF01?\uFF1F:\uFF1A\u201D)]}\u3001`){t=t??"english";let n,s,i;return["chinese","japanese","thai","lao","myanmar"].includes(t)?[n,s,i]=this.splitTokensOnUnicode(e):[n,s,i]=this.splitTokensOnSpaces(e),this.mergePunctuations(n,s,i,r,a)}decode(e,t){let r;return t?.decode_with_timestamps?(e instanceof j&&(e=Jd(e)),r=this.decodeWithTimestamps(e,t)):r=super.decode(e,t),r}decodeWithTimestamps(e,t){let r=t?.time_precision??.02,a=this.all_special_ids.at(-1)+1,n=[[]];for(let s of e)if(s=Number(s),s>=a){let i=((s-a)*r).toFixed(2);n.push(`<|${i}|>`),n.push([])}else n[n.length-1].push(s);return n=n.map(s=>typeof s=="string"?s:super.decode(s,t)),n.join("")}splitTokensOnUnicode(e){let t=this.decode(e,{decode_with_timestamps:!0}),r="\uFFFD",a=[],n=[],s=[],i=[],o=[],H=0;for(let _=0;_<e.length;++_){let c=e[_];i.push(c),o.push(_);let l=this.decode(i,{decode_with_timestamps:!0});(!l.includes(r)||t[H+l.indexOf(r)]===r)&&(a.push(l),n.push(i),s.push(o),i=[],o=[],H+=l.length)}return[a,n,s]}splitTokensOnSpaces(e){let[t,r,a]=this.splitTokensOnUnicode(e),n=[],s=[],i=[];for(let o=0;o<t.length;++o){let H=t[o],_=r[o],c=a[o],l=_[0]>=this._tokenizer.token_to_id("<|endoftext|>"),d=H.startsWith(" "),h=H.trim(),$=mS.test(h);if(l||d||$||n.length===0)n.push(H),s.push(_),i.push(c);else{let m=n.length-1;n[m]+=H,s[m].push(..._),i[m].push(...c)}}return[n,s,i]}mergePunctuations(e,t,r,a,n){let s=structuredClone(e),i=structuredClone(t),o=structuredClone(r),H=s.length-2,_=s.length-1;for(;H>=0;)s[H].startsWith(" ")&&a.includes(s[H].trim())?(s[_]=s[H]+s[_],i[_]=$r(i[H],i[_]),o[_]=$r(o[H],o[_]),s[H]="",i[H]=[],o[H]=[]):_=H,--H;for(H=0,_=1;_<s.length;)!s[H].endsWith(" ")&&n.includes(s[_])?(s[H]+=s[_],i[H]=$r(i[H],i[_]),o[H]=$r(o[H],o[_]),s[_]="",i[_]=[],o[_]=[]):H=_,++_;return[s.filter(c=>c),i.filter(c=>c.length>0),o.filter(c=>c.length>0)]}},rg=class extends he{},ag=class extends he{return_token_type_ids=!0;constructor(e,t){super(e,t),fe.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}},we=class{static async from_pretrained(e,{progress_callback:t=null,config:r=null,cache_dir:a=null,local_files_only:n=!1,revision:s="main"}={}){let[i,o]=await lA(e,{progress_callback:t,config:r,cache_dir:a,local_files_only:n,revision:s}),H=o.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer",_=uA[H];return _||(fe.warn(`Unknown tokenizer class "${H}", attempting to construct from base class.`),_=he),new _(i,o)}},TH="https://github.com/huggingface/transformers.js/issues/new/choose",ep="preprocessor_config.json",_i=ep,ng="processor_config.json",sg="chat_template.jinja",Ne=class extends zt{static classes=["image_processor_class","tokenizer_class","feature_extractor_class"];static uses_processor_config=!1;static uses_chat_template_file=!1;constructor(e,t,r){super(),this.config=e,this.components=t,this.chat_template=r}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(e,t={}){if(!this.tokenizer)throw new Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(e,{tokenize:!1,chat_template:this.chat_template??void 0,...t})}batch_decode(...e){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.batch_decode(...e)}decode(...e){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.decode(...e)}async _call(e,...t){for(let r of[this.image_processor,this.feature_extractor,this.tokenizer])if(r)return r(e,...t);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(e,t={}){let[r,a,n]=await Promise.all([this.uses_processor_config?jr(e,ng,!0,t):{},Promise.all(this.classes.filter(s=>s in this).map(async s=>{let i=await this[s].from_pretrained(e,t);return[s.replace(/_class$/,""),i]})).then(Object.fromEntries),this.uses_chat_template_file?gd(e,sg,!0,t):null]);return new this(r,a,n)}},od={};us(od,{ChatterboxProcessor:()=>vg,CohereAsrProcessor:()=>yg,Florence2Processor:()=>Ab,Gemma3Processor:()=>gb,Gemma3nProcessor:()=>bb,Gemma4Processor:()=>Tb,Glm46VProcessor:()=>xb,GraniteSpeechProcessor:()=>vb,GroundingDinoProcessor:()=>yb,Idefics3Processor:()=>_d,JinaCLIPProcessor:()=>Cb,Lfm2VlProcessor:()=>wb,LlavaProcessor:()=>Nb,MgpstrProcessor:()=>Bb,MoonshineProcessor:()=>Mb,OwlViTProcessor:()=>Pb,PaliGemmaProcessor:()=>kb,Phi3VProcessor:()=>Rb,PixtralProcessor:()=>Ob,Processor:()=>Ne,PyAnnoteProcessor:()=>Gb,Qwen2VLProcessor:()=>CH,Qwen2_5_VLProcessor:()=>bp,Qwen3VLProcessor:()=>Fb,Sam2Processor:()=>xp,Sam2VideoProcessor:()=>Zb,SamProcessor:()=>Tp,SmolVLMProcessor:()=>_d,SpeechT5Processor:()=>Ub,UltravoxProcessor:()=>Wb,VLChatProcessor:()=>Db,VoxtralProcessor:()=>Kb,VoxtralRealtimeProcessor:()=>Vb,Wav2Vec2Processor:()=>jb,Wav2Vec2ProcessorWithLM:()=>qb,WhisperProcessor:()=>Xb});vt=class extends zt{constructor(e){super(),this.config=e}static async from_pretrained(e,t={}){let r=await jr(e,ep,!0,t);return new this(r)}};tp={};us(tp,{ASTFeatureExtractor:()=>hg,ChatterboxFeatureExtractor:()=>fg,ClapFeatureExtractor:()=>Eg,CohereAsrFeatureExtractor:()=>$g,DacFeatureExtractor:()=>np,EncodecFeatureExtractor:()=>rp,FeatureExtractor:()=>vt,Gemma3nAudioFeatureExtractor:()=>sp,Gemma4AudioFeatureExtractor:()=>ip,GraniteSpeechFeatureExtractor:()=>mg,MoonshineFeatureExtractor:()=>Ig,ParakeetFeatureExtractor:()=>ap,PyAnnoteFeatureExtractor:()=>op,SeamlessM4TFeatureExtractor:()=>Sg,SnacFeatureExtractor:()=>Lg,SpeechT5FeatureExtractor:()=>Ag,VoxtralRealtimeFeatureExtractor:()=>Tg,Wav2Vec2FeatureExtractor:()=>gg,WeSpeakerFeatureExtractor:()=>bg,WhisperFeatureExtractor:()=>xg});lg=cg;sZ={htk:e=>2595*Math.log10(1+e/700),kaldi:e=>1127*Math.log(1+e/700),slaney:(e,t=1e3,r=15,a=27/Math.log(6.4))=>e>=t?r+Math.log(e/t)*a:3*e/200};iZ={htk:e=>700*(10**(e/2595)-1),kaldi:e=>700*(Math.exp(e/1127)-1),slaney:(e,t=1e3,r=15,a=Math.log(6.4)/27)=>e>=r?t*Math.exp(a*(e-r)):200*e/3};pg=class{constructor(e,t){this.audio=e,this.sampling_rate=t}get data(){if(Array.isArray(this.audio)){if(this.audio.length===0)return new Float32Array(0);if(this.audio.length===1)return this.audio[0];let e=this.audio.reduce((a,n)=>a+n.length,0),t=new Float32Array(e),r=0;for(let a of this.audio)t.set(a,r),r+=a.length;return t}else return this.audio}toBlob(){let e=this.audio;return e instanceof Float32Array&&(e=[e]),uZ(e,this.sampling_rate)}async save(e){return _g(e,this.toBlob())}},hg=class extends vt{constructor(e){super(e);let t=this.config.sampling_rate,r=Wr(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);this.mel_filters=r,this.window=la(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(e,t){return qr(e,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:t,transpose:!0})}async _call(e){yt(e,"ASTFeatureExtractor");let t=await this._extract_fbank_features(e,this.config.max_length);if(this.config.do_normalize){let r=this.std*2,a=t.data;for(let n=0;n<a.length;++n)a[n]=(a[n]-this.mean)/r}return{input_values:t.unsqueeze_(0)}}},rp=class extends vt{async _call(e){yt(e,"EncodecFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let t=this.config.feature_size;if(e.length%t!==0)throw new Error(`The length of the audio data must be a multiple of the number of channels (${t}).`);let r=[1,t,e.length/t];return{input_values:new j("float32",e,r)}}},fg=class extends vt{async _call(e){yt(e,"ChatterboxFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let t=[1,e.length];return{input_values:new j("float32",e,t)}}},Eg=class extends vt{constructor(e){super(e),this.mel_filters=Wr(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=Wr(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=la(this.config.fft_window_size,"hann")}async _get_input_mel(e,t,r,a){let n,s=!1,i=e.length-t;if(i>0)if(r==="rand_trunc"){s=!0;let o=Math.floor(ui.random()*(i+1));e=e.subarray(o,o+t),n=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${r}" not implemented`);else{if(i<0){let o=new Float64Array(t);if(o.set(e),a==="repeat")for(let H=e.length;H<t;H+=e.length)o.set(e.subarray(0,Math.min(e.length,t-H)),H);else if(a==="repeatpad")for(let H=e.length;H<-i;H+=e.length)o.set(e,H);e=o}if(r==="fusion")throw new Error(`Truncation strategy "${r}" not implemented`);n=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}return n.unsqueeze_(0)}async _extract_fbank_features(e,t,r=null){return qr(e,this.window,this.config.fft_window_size,this.config.hop_length,{power:2,mel_filters:t,log_mel:"dB",max_num_frames:r,do_pad:!1,transpose:!0})}async _call(e,{max_length:t=null}={}){return yt(e,"ClapFeatureExtractor"),{input_features:(await this._get_input_mel(e,t??this.config.nb_max_samples,this.config.truncation,this.config.padding)).unsqueeze_(0)}}},dZ=1e-5,ap=class extends vt{constructor(e){super(e),this.config.mel_filters??=Wr(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,this.config.sampling_rate/2,this.config.sampling_rate,"slaney","slaney");let t=la(this.config.win_length,"hann",{periodic:!1});this.window=new Float64Array(this.config.n_fft);let r=Math.floor((this.config.n_fft-this.config.win_length)/2);this.window.set(t,r)}async _extract_fbank_features(e){let t=this.config.preemphasis;e=new Float64Array(e);for(let a=e.length-1;a>=1;--a)e[a]-=t*e[a-1];return await qr(e,this.window,this.window.length,this.config.hop_length,{fft_length:this.config.n_fft,power:2,mel_filters:this.config.mel_filters,log_mel:"log",mel_floor:-1/0,pad_mode:"constant",center:!0,transpose:!0,mel_offset:2**-24})}async _call(e){yt(e,"ParakeetFeatureExtractor");let t=await this._extract_fbank_features(e),r=Math.floor((e.length+Math.floor(this.config.n_fft/2)*2-this.config.n_fft)/this.config.hop_length),a=t.data;a.fill(0,r*t.dims[1]);let[n,s]=t.dims,i=new Float64Array(s),o=new Float64Array(s);for(let c=0;c<r;++c){let l=c*s;for(let d=0;d<s;++d){let h=a[l+d];i[d]+=h,o[d]+=h*h}}let H=r>1?r-1:1;for(let c=0;c<s;++c){let l=i[c]/r,d=(o[c]-r*l*l)/H,$=1/(Math.sqrt(d)+dZ);for(let m=0;m<r;++m){let S=m*s+c;a[S]=(a[S]-l)*$}}let _=new BigInt64Array(n);return _.fill(1n,0,r),{input_features:t.unsqueeze_(0),attention_mask:new j("int64",_,[1,n])}}},$g=class extends ap{_apply_dither(e){let t=this.config.dither??0;if(t<=0)return e;let r=new gH(e.length);for(let a=0;a<e.length;++a)e[a]+=t*r.gauss();return e}split_audio(e){let t=this.config.max_audio_clip_s??35,r=this.config.overlap_chunk_second??5,a=this.config.min_energy_window_samples??1600,n=this.config.sampling_rate,s=Math.max(1,Math.round(t*n)),i=Math.max(1,Math.round(r*n));if(e.length<=s)return[e];let o=[],H=0,_=e.length;for(;H<_;){if(H+s>=_){o.push(e.slice(H,_));break}let c=Math.max(H,H+s-i),l=Math.min(H+s,_),d;l<=c?d=H+s:d=this._find_split_point_energy(e,c,l,a),d=Math.max(H+1,Math.min(d,_)),o.push(e.slice(H,d)),H=d}return o}_find_split_point_energy(e,t,r,a){let n=r-t;if(n<=a)return Math.floor((t+r)/2);let s=1/0,i=t,o=n-a;for(let H=0;H<=o;H+=a){let _=0;for(let c=0;c<a;++c){let l=e[t+H+c];_+=l*l}_=Math.sqrt(_/a),_<s&&(s=_,i=t+H)}return i}async _call(e){yt(e,"CohereAsrFeatureExtractor");let t=new Float64Array(e);return this._apply_dither(t),super._call(t)}},np=class extends rp{},sp=class extends vt{constructor(e){super(e);let{fft_length:t,feature_size:r,min_frequency:a,max_frequency:n,sampling_rate:s,frame_length:i}=this.config,o=Wr(Math.floor(1+t/2),r,a,n,s,null,"htk",!1);this.mel_filters=o,this.window=la(i,"hann")}async _extract_fbank_features(e,t){return qr(e,this.window,this.config.frame_length,this.config.hop_length,{fft_length:this.config.fft_length,center:!1,onesided:!0,preemphasis:this.config.preemphasis,preemphasis_htk_flavor:this.config.preemphasis_htk_flavor,mel_filters:this.mel_filters,log_mel:"log",mel_floor:this.config.mel_floor,remove_dc_offset:!1,transpose:!0})}async _call(e,{max_length:t=48e4,truncation:r=!0,padding:a=!0,pad_to_multiple_of:n=128}={}){if(yt(e,"Gemma3nAudioFeatureExtractor"),r&&e.length>t&&(e=e.slice(0,t)),a&&e.length%n!==0){let o=n-e.length%n,H=new Float64Array(e.length+o);H.set(e),this.config.padding_value!==0&&H.fill(this.config.padding_value,e.length),e=H}let s=await this._extract_fbank_features(e,this.config.max_length),i=xt([1,s.dims[0]],!0);return{input_features:s.unsqueeze_(0),input_features_mask:i}}},ip=class extends sp{async _extract_fbank_features(e,t){let{frame_length:r,hop_length:a,fft_length:n}=this.config,s=Math.floor(r/2),i=Math.floor((e.length+s-(r+1))/a)+1;return qr(e,this.window,r,a,{fft_length:n,center:!0,pad_mode:"semicausal",onesided:!0,preemphasis:this.config.preemphasis,preemphasis_htk_flavor:this.config.preemphasis_htk_flavor,mel_filters:this.mel_filters,log_mel:"log",mel_floor:this.config.mel_floor,mel_floor_mode:"add",remove_dc_offset:!1,transpose:!0,max_num_frames:i})}async _call(e,t={}){yt(e,"Gemma4AudioFeatureExtractor");let r=e.length,a=await super._call(e,t),{input_features:n}=a,[,s,i]=n.dims,{frame_length:o,hop_length:H}=this.config,_=Math.floor(o/2),c=o+1,l=new Uint8Array(r+_+(t.pad_to_multiple_of??128));l.fill(1,_,_+r);let d=new Uint8Array(s);for(let $=0;$<s;++$)d[$]=l[$*H+c-1]?1:0;let h=n.data;for(let $=0;$<s;++$)d[$]||h.fill(0,$*i,($+1)*i);return a.input_features_mask=new j("bool",d,[1,s]),a}},mg=class extends vt{constructor(e){super(e);let{n_fft:t,win_length:r,n_mels:a,sample_rate:n}=e.melspec_kwargs;this.mel_filters=Wr(Math.floor(1+t/2),a,0,n/2,n,null,"htk");let s=la(r,"hann");this.window=new Float64Array(t);let i=Math.floor((t-r)/2);this.window.set(s,i)}async _call(e){yt(e,"GraniteSpeechFeatureExtractor");let{n_fft:t,hop_length:r,n_mels:a}=this.config.melspec_kwargs,n=1+Math.floor((e.length-1)/r),s=n-n%2;return{input_features:(await qr(e,this.window,t,r,{power:2,mel_filters:this.mel_filters,log_mel:"log10_max_norm",transpose:!0,max_num_frames:s,do_pad:!1})).view(-1,2*a).unsqueeze_(0)}}},Ig=class extends vt{async _call(e){yt(e,"MoonshineFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let t=[1,e.length];return{input_values:new j("float32",e,t)}}},op=class extends vt{async _call(e){yt(e,"PyAnnoteFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let t=[1,1,e.length];return{input_values:new j("float32",e,t)}}samples_to_frames(e){return(e-this.config.offset)/this.config.step}post_process_speaker_diarization(e,t){let r=t/this.samples_to_frames(t)/this.config.sampling_rate,a=[];for(let n of e.tolist()){let s=[],i=-1;for(let o=0;o<n.length;++o){let H=St(n[o]),[_,c]=nt(H),[l,d]=[o,o+1];c!==i?(i=c,s.push({id:c,start:l,end:d,score:_})):(s.at(-1).end=d,s.at(-1).score+=_)}a.push(s.map(({id:o,start:H,end:_,score:c})=>({id:o,start:H*r,end:_*r,confidence:c/(_-H)})))}return a}},Sg=class extends vt{constructor(e){super(e);let t=this.config.sampling_rate,r=Wr(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);this.mel_filters=r,this.window=la(400,"povey",{periodic:!1})}async _extract_fbank_features(e,t){return e=e.map(r=>r*32768),qr(e,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:t,transpose:!0})}async _call(e,{padding:t=!0,pad_to_multiple_of:r=2,do_normalize_per_mel_bins:a=!0,return_attention_mask:n=!0}={}){yt(e,"SeamlessM4TFeatureExtractor");let s=await this._extract_fbank_features(e,this.config.max_length);if(a){let[h,$]=s.dims,m=s.data;for(let S=0;S<$;++S){let I=0;for(let v=0;v<h;++v)I+=m[v*$+S];let g=I/h,T=0;for(let v=0;v<h;++v)T+=(m[v*$+S]-g)**2;T/=h-1;let x=Math.sqrt(T+1e-7);for(let v=0;v<h;++v){let k=v*$+S;m[k]=(m[k]-g)/x}}}let i;if(t){let[h,$]=s.dims,m=s.data,S=h%r;if(S>0){let I=new Float32Array($*(h+S));I.set(m),I.fill(this.config.padding_value,m.length);let g=h+S;s=new j(s.type,I,[g,$]),n&&(i=new j("int64",new BigInt64Array(g),[1,g]),i.data.fill(1n,0,h))}}let[o,H]=s.dims,_=this.config.stride;if(o%_!==0)throw new Error(`The number of frames (${o}) must be a multiple of the stride (${_}).`);let l=s.view(1,Math.floor(o/_),H*_),d={input_features:l};if(n){let h=l.dims[1],$=new BigInt64Array(h);if(i){let m=i.data;for(let S=1,I=0;S<o;S+=_,++I)$[I]=m[S]}else $.fill(1n);d.attention_mask=new j("int64",$,[1,h])}return d}},Lg=class extends np{},Ag=class extends vt{},gg=class extends vt{_zero_mean_unit_var_norm(e){let r=e.reduce((n,s)=>n+s,0)/e.length,a=e.reduce((n,s)=>n+(s-r)**2,0)/e.length;return e.map(n=>(n-r)/Math.sqrt(a+1e-7))}async _call(e){yt(e,"Wav2Vec2FeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let t=e;this.config.do_normalize&&(t=this._zero_mean_unit_var_norm(t));let r=[1,t.length];return{input_values:new j("float32",t,r),attention_mask:new j("int64",new BigInt64Array(t.length).fill(1n),r)}}},bg=class extends vt{constructor(e){super(e);let t=this.config.sampling_rate,r=Wr(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);this.mel_filters=r,this.window=la(400,"hamming",{periodic:!1}),this.min_num_frames=this.config.min_num_frames}async _extract_fbank_features(e){return e=e.map(t=>t*32768),qr(e,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(e){yt(e,"WeSpeakerFeatureExtractor");let t=(await this._extract_fbank_features(e)).unsqueeze_(0);if(this.config.fbank_centering_span===null){let r=t.mean(1).data,a=t.data,[n,s,i]=t.dims;for(let o=0;o<n;++o){let H=o*s*i,_=o*i;for(let c=0;c<s;++c){let l=H+c*i;for(let d=0;d<i;++d)a[l+d]-=r[_+d]}}}return{input_features:t}}},Tg=class extends vt{constructor(e){super(e),this.config.mel_filters??=Wr(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney"),this.window=la(this.config.n_fft,"hann")}async _extract_fbank_features(e,{center:t=!0}={}){let{n_fft:r,hop_length:a,mel_filters:n,global_log_mel_max:s}=this.config,i=Math.floor(t?e.length/a:(e.length-r)/a);return await qr(e,this.window,r,a,{power:2,mel_filters:n,log_mel:"log10_max_norm",max_log_mel:s,center:t,max_num_frames:i,do_pad:!1})}async _call(e,{center:t=!0}={}){return yt(e,"VoxtralRealtimeFeatureExtractor"),{input_features:(await this._extract_fbank_features(e,{center:t})).unsqueeze_(0)}}},xg=class extends vt{constructor(e){super(e),this.config.mel_filters??=Wr(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney"),this.window=la(this.config.n_fft,"hann")}async _extract_fbank_features(e){return await qr(e,this.window,this.config.n_fft,this.config.hop_length,{power:2,mel_filters:this.config.mel_filters,log_mel:"log10_max_norm",max_num_frames:Math.min(Math.floor(e.length/this.config.hop_length),this.config.nb_max_frames)})}async _call(e,{max_length:t=null}={}){yt(e,"WhisperFeatureExtractor");let r,a=t??this.config.n_samples;return e.length>a?(e.length>this.config.n_samples&&fe.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`."),r=e.slice(0,a)):(r=new Float32Array(a),r.set(e)),{input_features:(await this._extract_fbank_features(r)).unsqueeze_(0)}}},sr=class{static async from_pretrained(e,t={}){let r=await jr(e,ep,!0,t),a=r.feature_extractor_type,n=tp[a];if(!n)throw new Error(`Unknown feature_extractor_type: '${a}'. Please report this at ${TH}.`);return new n(r)}},vg=class extends Ne{static tokenizer_class=we;static feature_extractor_class=sr;async _call(e,t=null){let r=this.tokenizer(e),a=t?await this.feature_extractor(t):{};return{...r,...a}}},pZ=new Set(["ja","zh"]),yg=class extends Ne{static tokenizer_class=we;static feature_extractor_class=sr;static uses_processor_config=!0;get_decoder_prompt_ids(e="en"){let t=["\u2581","<|startofcontext|>","<|startoftranscript|>","<|emo:undefined|>",`<|${e}|>`,`<|${e}|>`,"<|pnc|>","<|noitn|>","<|notimestamp|>","<|nodiarize|>"];return this.tokenizer.convert_tokens_to_ids(t)}static join_chunks(e,t="en"){let r=e.filter(s=>s&&s.trim());if(r.length===0)return"";let a=pZ.has(t)?"":" ";return[r[0].trimEnd(),...r.slice(1).map(s=>s.trim())].join(a)}async _call(e){return await this.feature_extractor(e)}};if(Ie.IS_WEB_ENV)za=(e,t)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this environment.");return new self.OffscreenCanvas(e,t)},Ta=self.createImageBitmap,Dg=self.ImageData;else if(pH.default)Ta=async e=>{let r=(await e.metadata()).channels,{data:a,info:n}=await e.rotate().raw().toBuffer({resolveWithObject:!0}),s=new Xt(new Uint8ClampedArray(a),n.width,n.height,n.channels);return r!==void 0&&r!==n.channels&&s.convert(r),s};else throw new Error("Unable to load image processing library.");hZ={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},fZ=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]),Xt=class Fr{constructor(t,r,a,n){this.data=t,this.width=r,this.height=a,this.channels=n}get size(){return[this.width,this.height]}static async read(t){if(t instanceof Fr)return t;if(typeof t=="string"||t instanceof URL)return await this.fromURL(t);if(t instanceof Blob)return await this.fromBlob(t);if(typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&t instanceof OffscreenCanvas)return this.fromCanvas(t);throw new Error(`Unsupported input type: ${typeof t}`)}static fromCanvas(t){if(!Ie.IS_WEB_ENV)throw new Error("fromCanvas() is only supported in browser environments.");let a=t.getContext("2d").getImageData(0,0,t.width,t.height).data;return new Fr(a,t.width,t.height,4)}static async fromURL(t){let r=await si(t);if(r.status!==200)throw new Error(`Unable to read image from "${t}" (${r.status} ${r.statusText})`);let a=await r.blob();return this.fromBlob(a)}static async fromBlob(t){if(Ie.IS_WEB_ENV){let r=await Ta(t),a=za(r.width,r.height).getContext("2d");return a.drawImage(r,0,0),new this(a.getImageData(0,0,r.width,r.height).data,r.width,r.height,4)}else{let r=(0,pH.default)(await t.arrayBuffer());return await Ta(r)}}static fromTensor(t,r="CHW"){if(t.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${t.dims.length} dimensions.`);if(r==="CHW")t=t.transpose(1,2,0);else if(r!=="HWC")throw new Error(`Unsupported channel format: ${r}`);if(!(t.data instanceof Uint8ClampedArray||t.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${t.type}`);switch(t.dims[2]){case 1:case 2:case 3:case 4:return new Fr(t.data,t.dims[1],t.dims[0],t.dims[2]);default:throw new Error(`Unsupported number of channels: ${t.dims[2]}`)}}grayscale(){if(this.channels===1)return this;let t=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let r=0,a=0;r<this.data.length;r+=this.channels){let n=this.data[r],s=this.data[r+1],i=this.data[r+2];t[a++]=Math.round(.2989*n+.587*s+.114*i)}break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(t,this.width,this.height,1)}rgb(){if(this.channels===3)return this;let t=new Uint8ClampedArray(this.width*this.height*3);switch(this.channels){case 1:for(let r=0,a=0;r<this.data.length;++r)t[a++]=this.data[r],t[a++]=this.data[r],t[a++]=this.data[r];break;case 4:for(let r=0,a=0;r<this.data.length;r+=4)t[a++]=this.data[r],t[a++]=this.data[r+1],t[a++]=this.data[r+2];break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(t,this.width,this.height,3)}rgba(){if(this.channels===4)return this;let t=new Uint8ClampedArray(this.width*this.height*4);switch(this.channels){case 1:for(let r=0,a=0;r<this.data.length;++r)t[a++]=this.data[r],t[a++]=this.data[r],t[a++]=this.data[r],t[a++]=255;break;case 3:for(let r=0,a=0;r<this.data.length;r+=3)t[a++]=this.data[r],t[a++]=this.data[r+1],t[a++]=this.data[r+2],t[a++]=255;break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(t,this.width,this.height,4)}putAlpha(t){if(t.width!==this.width||t.height!==this.height)throw new Error(`Expected mask size to be ${this.width}x${this.height}, but got ${t.width}x${t.height}`);if(t.channels!==1)throw new Error(`Expected mask to have 1 channel, but got ${t.channels}`);let r=this.data,a=t.data,n=this.width*this.height;if(this.channels===3){let s=new Uint8ClampedArray(n*4);for(let i=0,o=0,H=0;i<n;++i)s[H++]=r[o++],s[H++]=r[o++],s[H++]=r[o++],s[H++]=a[i];return this._update(s,this.width,this.height,4)}else if(this.channels===4){for(let s=0;s<n;++s)r[4*s+3]=a[s];return this}throw new Error(`Expected image to have 3 or 4 channels, but got ${this.channels}`)}async resize(t,r,{resample:a=2}={}){if(this.width===t&&this.height===r)return this;let n=hZ[a]??a,s=dI(t),i=dI(r);if(s&&i)return this;if(s?t=r/this.height*this.width:i&&(r=t/this.width*this.height),Ie.IS_WEB_ENV){let o=this.channels,H=this.toCanvas(),_=za(t,r).getContext("2d");return _.drawImage(H,0,0,t,r),new Fr(_.getImageData(0,0,t,r).data,t,r,4).convert(o)}else{let o=this.toSharp();switch(n){case"box":case"hamming":(n==="box"||n==="hamming")&&(fe.warn(`Resampling method ${n} is not yet supported. Using bilinear instead.`),n="bilinear");case"nearest":case"bilinear":case"bicubic":o=o.affine([t/this.width,0,0,r/this.height],{interpolator:n});break;case"lanczos":o=o.resize({width:t,height:r,fit:"fill",kernel:"lanczos3"});break;default:throw new Error(`Resampling method ${n} is not supported.`)}return await Ta(o)}}async pad([t,r,a,n]){if(t=Math.max(t,0),r=Math.max(r,0),a=Math.max(a,0),n=Math.max(n,0),t===0&&r===0&&a===0&&n===0)return this;if(Ie.IS_WEB_ENV){let s=this.channels,i=this.toCanvas(),o=this.width+t+r,H=this.height+a+n,_=za(o,H).getContext("2d");return _.drawImage(i,0,0,this.width,this.height,t,a,this.width,this.height),new Fr(_.getImageData(0,0,o,H).data,o,H,4).convert(s)}else{let s=this.toSharp().extend({left:t,right:r,top:a,bottom:n});return await Ta(s)}}async crop([t,r,a,n]){if(t=Math.max(t,0),r=Math.max(r,0),a=Math.min(a,this.width-1),n=Math.min(n,this.height-1),t===0&&r===0&&a===this.width-1&&n===this.height-1)return this;let s=a-t+1,i=n-r+1;if(Ie.IS_WEB_ENV){let o=this.channels,H=this.toCanvas(),_=za(s,i).getContext("2d");return _.drawImage(H,t,r,s,i,0,0,s,i),new Fr(_.getImageData(0,0,s,i).data,s,i,4).convert(o)}else{let o=this.toSharp().extract({left:t,top:r,width:s,height:i});return await Ta(o)}}async center_crop(t,r){if(this.width===t&&this.height===r)return this;let a=(this.width-t)/2,n=(this.height-r)/2;if(Ie.IS_WEB_ENV){let s=this.channels,i=this.toCanvas(),o=za(t,r).getContext("2d"),H=0,_=0,c=0,l=0;return a>=0?H=a:c=-a,n>=0?_=n:l=-n,o.drawImage(i,H,_,t,r,c,l,t,r),new Fr(o.getImageData(0,0,t,r).data,t,r,4).convert(s)}else{let s=this.toSharp();if(a>=0&&n>=0)s=s.extract({left:Math.floor(a),top:Math.floor(n),width:t,height:r});else if(a<=0&&n<=0){let i=Math.floor(-n),o=Math.floor(-a);s=s.extend({top:i,left:o,right:t-this.width-o,bottom:r-this.height-i})}else{let i=[0,0],o=0;n<0?(i[0]=Math.floor(-n),i[1]=r-this.height-i[0]):o=Math.floor(n);let H=[0,0],_=0;a<0?(H[0]=Math.floor(-a),H[1]=t-this.width-H[0]):_=Math.floor(a),s=s.extend({top:i[0],bottom:i[1],left:H[0],right:H[1]}).extract({left:_,top:o,width:t,height:r})}return await Ta(s)}}async toBlob(t="image/png",r=1){if(!Ie.IS_WEB_ENV)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:t,quality:r})}toTensor(t="CHW"){let r=new j("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(t!=="HWC")if(t==="CHW")r=r.permute(2,0,1);else throw new Error(`Unsupported channel format: ${t}`);return r}toCanvas(){if(!Ie.IS_WEB_ENV)throw new Error("toCanvas() is only supported in browser environments.");let t=this.clone().rgba(),r=za(t.width,t.height),a=new Dg(t.data,t.width,t.height);return r.getContext("2d").putImageData(a,0,0),r}split(){let{data:t,width:r,height:a,channels:n}=this,s=t.constructor,i=t.length/n,o=Array.from({length:n},()=>new s(i));for(let H=0;H<i;++H){let _=n*H;for(let c=0;c<n;++c)o[c][H]=t[_+c]}return o.map(H=>new Fr(H,r,a,1))}_update(t,r,a,n=null){return this.data=t,this.width=r,this.height=a,n!==null&&(this.channels=n),this}clone(){return new Fr(this.data.slice(),this.width,this.height,this.channels)}convert(t){if(this.channels===t)return this;switch(t){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(t){if(Ie.IS_WEB_ENV){if(Ie.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");let r=t.split(".").pop().toLowerCase(),a=fZ.get(r)??"image/png",n=await this.toBlob(a);return _g(t,n)}else if(Ie.IS_FS_AVAILABLE)await this.toSharp().toFile(t);else throw new Error("Unable to save the image because filesystem is disabled in this environment.")}toSharp(){if(Ie.IS_WEB_ENV)throw new Error("toSharp() is only supported in server-side environments.");return(0,pH.default)(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}},EZ=Xt.read.bind(Xt);Ee=class extends zt{constructor(e){super(),this.image_mean=e.image_mean??e.mean,this.image_std=e.image_std??e.std,this.resample=e.resample??2,this.do_rescale=e.do_rescale??!0,this.rescale_factor=e.rescale_factor??1/255,this.do_normalize=e.do_normalize,this.do_thumbnail=e.do_thumbnail,this.size=e.size??e.image_size,this.do_resize=e.do_resize??this.size!==void 0,this.size_divisibility=e.size_divisibility??e.size_divisor,this.do_center_crop=e.do_center_crop,this.crop_size=e.crop_size,this.do_convert_rgb=e.do_convert_rgb??!0,this.do_crop_margin=e.do_crop_margin,this.pad_size=e.pad_size,this.do_pad=e.do_pad,this.min_pixels=e.min_pixels,this.max_pixels=e.max_pixels,this.do_pad&&!this.pad_size&&!this.size_divisibility&&this.size&&this.size.width!==void 0&&this.size.height!==void 0&&(this.pad_size=this.size),this.do_flip_channel_order=e.do_flip_channel_order??!1,this.config=e}async thumbnail(e,t,r=2){let a=e.height,n=e.width,s=t.height,i=t.width,o=Math.min(a,s),H=Math.min(n,i);return o===a&&H===n?e:(a>n?H=Math.floor(n*o/a):n>a&&(o=Math.floor(a*H/n)),await e.resize(H,o,{resample:r}))}async crop_margin(e,t=200){let r=e.clone().grayscale(),a=ed(r.data)[0],s=nt(r.data)[0]-a;if(s===0)return e;let i=t/255,o=r.width,H=r.height,_=0,c=0,l=r.data;for(let d=0;d<r.height;++d){let h=d*r.width;for(let $=0;$<r.width;++$)(l[h+$]-a)/s<i&&(o=Math.min(o,$),H=Math.min(H,d),_=Math.max(_,$),c=Math.max(c,d))}return e=await e.crop([o,H,_,c]),e}pad_image(e,t,r,{mode:a="constant",center:n=!1,constant_values:s=0}={}){let[i,o,H]=t,_,c;if(typeof r=="number"?(_=r,c=r):r==="square"?_=c=Math.max(i,o):(_=r.width,c=r.height),_!==o||c!==i){let l=new Float32Array(_*c*H);if(Array.isArray(s))for(let $=0;$<l.length;++$)l[$]=s[$%H];else s!==0&&l.fill(s);let[d,h]=n?[Math.floor((_-o)/2),Math.floor((c-i)/2)]:[0,0];for(let $=0;$<i;++$){let m=($+h)*_,S=$*o;for(let I=0;I<o;++I){let g=(m+I+d)*H,T=(S+I)*H;for(let x=0;x<H;++x)l[g+x]=e[T+x]}}if(a==="symmetric"){if(n)throw new Error("`center` padding is not supported when `mode` is set to `symmetric`.");let $=i-1,m=o-1;for(let S=0;S<c;++S){let I=S*_,g=nH(S,$)*o;for(let T=0;T<_;++T){if(S<i&&T<o)continue;let x=(I+T)*H,v=(g+nH(T,m))*H;for(let k=0;k<H;++k)l[x+k]=e[v+k]}}}e=l,t=[c,_,H]}return[e,t]}rescale(e){for(let t=0;t<e.length;++t)e[t]=this.rescale_factor*e[t]}get_resize_output_image_size(e,t){let[r,a]=e.size,n,s;if(this.do_thumbnail){let{height:i,width:o}=t;n=Math.min(i,o)}else Number.isInteger(t)?(n=t,s=this.config.max_size??n):t!==void 0&&(n=t.shortest_edge,s=t.longest_edge);if(n!==void 0||s!==void 0){let i=n===void 0?1:Math.max(n/r,n/a),o=r*i,H=a*i,_=s===void 0?1:Math.min(s/o,s/H),c=Math.floor(Number((o*_).toFixed(2))),l=Math.floor(Number((H*_).toFixed(2)));return this.size_divisibility!==void 0&&([c,l]=AS([c,l],this.size_divisibility)),[c,l]}else if(t!==void 0&&t.width!==void 0&&t.height!==void 0){let i=t.width,o=t.height;if(this.config.keep_aspect_ratio&&this.config.ensure_multiple_of){let H=o/a,_=i/r;Math.abs(1-_)<Math.abs(1-H)?H=_:_=H,o=LS(H*a,this.config.ensure_multiple_of),i=LS(_*r,this.config.ensure_multiple_of)}return[i,o]}else{if(this.size_divisibility!==void 0)return AS([r,a],this.size_divisibility);throw new Error(`Could not resize image due to unsupported \`this.size\` option in config: ${JSON.stringify(t)}`)}}async resize(e){let[t,r]=this.get_resize_output_image_size(e,this.size);return await e.resize(t,r,{resample:this.resample})}async preprocess(e,{do_normalize:t=null,do_pad:r=null,do_convert_rgb:a=null,do_convert_grayscale:n=null,do_flip_channel_order:s=null}={}){this.do_crop_margin&&(e=await this.crop_margin(e));let[i,o]=e.size;if(a??this.do_convert_rgb?e=e.rgb():n&&(e=e.grayscale()),this.do_resize&&(e=await this.resize(e)),this.do_thumbnail&&(e=await this.thumbnail(e,this.size,this.resample)),this.do_center_crop){let d,h;Number.isInteger(this.crop_size)?(d=this.crop_size,h=this.crop_size):(d=this.crop_size.width,h=this.crop_size.height),e=await e.center_crop(d,h)}let H=[e.height,e.width],_=Float32Array.from(e.data),c=[e.height,e.width,e.channels];if(this.do_rescale&&this.rescale(_),t??this.do_normalize){let d=this.image_mean;Array.isArray(this.image_mean)||(d=new Array(e.channels).fill(d));let h=this.image_std;if(Array.isArray(this.image_std)||(h=new Array(e.channels).fill(h)),d.length!==e.channels||h.length!==e.channels)throw new Error(`When set to arrays, the length of \`image_mean\` (${d.length}) and \`image_std\` (${h.length}) must match the number of channels in the image (${e.channels}).`);for(let $=0;$<_.length;$+=e.channels)for(let m=0;m<e.channels;++m)_[$+m]=(_[$+m]-d[m])/h[m]}if(r??this.do_pad){if(this.pad_size)[_,c]=this.pad_image(_,[e.height,e.width,e.channels],this.pad_size);else if(this.size_divisibility){let d=Math.ceil(c[1]/this.size_divisibility)*this.size_divisibility,h=Math.ceil(c[0]/this.size_divisibility)*this.size_divisibility;[_,c]=this.pad_image(_,c,{width:d,height:h})}}if(s??this.do_flip_channel_order){if(c[2]!==3)throw new Error("Flipping channel order is only supported for RGB images.");for(let d=0;d<_.length;d+=3){let h=_[d];_[d]=_[d+2],_[d+2]=h}}let l=new j("float32",_,c).permute(2,0,1);return{original_size:[o,i],reshaped_input_size:H,pixel_values:l}}async _call(e,...t){Array.isArray(e)||(e=[e]);let r=await Promise.all(e.map(n=>this.preprocess(n)));return{pixel_values:Ur(r.map(n=>n.pixel_values),0),original_sizes:r.map(n=>n.original_size),reshaped_input_sizes:r.map(n=>n.reshaped_input_size)}}static async from_pretrained(e,t={}){let r=await jr(e,_i,!0,t);return new this(r)}},hH={};us(hH,{BeitFeatureExtractor:()=>Mg,BitImageProcessor:()=>Pg,CHMv2ImageProcessor:()=>Rg,CLIPFeatureExtractor:()=>Og,CLIPImageProcessor:()=>_p,ChineseCLIPFeatureExtractor:()=>kg,ConvNextFeatureExtractor:()=>Gg,ConvNextImageProcessor:()=>cp,DINOv3ViTImageProcessor:()=>Ug,DPTFeatureExtractor:()=>Kg,DPTImageProcessor:()=>dp,DeiTFeatureExtractor:()=>Fg,DeiTImageProcessor:()=>lp,DetrFeatureExtractor:()=>Zg,DetrImageProcessor:()=>up,DonutFeatureExtractor:()=>Wg,DonutImageProcessor:()=>vH,EfficientNetImageProcessor:()=>Vg,GLPNFeatureExtractor:()=>Xg,Gemma3ImageProcessor:()=>jg,Gemma4ImageProcessor:()=>pp,Glm46VImageProcessor:()=>qg,GroundingDinoImageProcessor:()=>zg,Idefics3ImageProcessor:()=>Hd,ImageFeatureExtractor:()=>Ee,ImageProcessor:()=>Ee,JinaCLIPImageProcessor:()=>Qg,Lfm2VlImageProcessor:()=>Yg,LlavaOnevisionImageProcessor:()=>eb,Mask2FormerImageProcessor:()=>rb,MaskFormerFeatureExtractor:()=>tb,MaskFormerImageProcessor:()=>yH,MobileNetV1FeatureExtractor:()=>ab,MobileNetV1ImageProcessor:()=>fp,MobileNetV2FeatureExtractor:()=>nb,MobileNetV2ImageProcessor:()=>Ep,MobileNetV3FeatureExtractor:()=>sb,MobileNetV3ImageProcessor:()=>$p,MobileNetV4FeatureExtractor:()=>ib,MobileNetV4ImageProcessor:()=>mp,MobileViTFeatureExtractor:()=>ob,MobileViTImageProcessor:()=>Ip,NougatImageProcessor:()=>Hb,OwlViTFeatureExtractor:()=>_b,OwlViTImageProcessor:()=>DH,Owlv2ImageProcessor:()=>cb,Phi3VImageProcessor:()=>lb,PixtralImageProcessor:()=>ub,PvtImageProcessor:()=>db,Qwen2VLImageProcessor:()=>hp,RTDetrImageProcessor:()=>pb,Sam2ImageProcessor:()=>eH,Sam3ImageProcessor:()=>eH,SamImageProcessor:()=>eH,SapiensFeatureExtractor:()=>hb,SapiensImageProcessor:()=>Sp,SegformerFeatureExtractor:()=>fb,SegformerImageProcessor:()=>Lp,SiglipImageProcessor:()=>Eb,SmolVLMImageProcessor:()=>Hd,Swin2SRImageProcessor:()=>$b,VLMImageProcessor:()=>Jg,ViTFeatureExtractor:()=>mb,ViTImageProcessor:()=>Ap,VitMatteImageProcessor:()=>Ib,VitPoseImageProcessor:()=>Sb,YolosFeatureExtractor:()=>Lb,YolosImageProcessor:()=>gp});Mg=class extends Ee{},Pg=class extends Ee{},kg=class extends Ee{},Rg=class extends Ee{},_p=class extends Ee{},Og=class extends _p{},cp=class extends Ee{constructor(e){super(e),this.crop_pct=this.config.crop_pct??224/256}async resize(e){let t=this.size?.shortest_edge;if(t===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(t<384){let r=Math.floor(t/this.crop_pct),[a,n]=this.get_resize_output_image_size(e,{shortest_edge:r});e=await e.resize(a,n,{resample:this.resample}),e=await e.center_crop(t,t)}else e=await e.resize(t,t,{resample:this.resample});return e}},Gg=class extends cp{},lp=class extends Ee{},Fg=class extends lp{},up=class extends Ee{async _call(e){let t=await super._call(e),r=[t.pixel_values.dims[0],64,64],a=xt(r,1n);return{...t,pixel_mask:a}}post_process_object_detection(...e){return xH(...e)}post_process_panoptic_segmentation(...e){return Ng(...e)}post_process_instance_segmentation(...e){return Bg(...e)}},Zg=class extends up{},Ug=class extends Ee{},vH=class extends Ee{pad_image(e,t,r,a={}){let[n,s,i]=t,o=this.image_mean;Array.isArray(this.image_mean)||(o=new Array(i).fill(o));let H=this.image_std;Array.isArray(H)||(H=new Array(i).fill(o));let _=o.map((c,l)=>-c/H[l]);return super.pad_image(e,t,r,{center:!0,constant_values:_,...a})}},Wg=class extends vH{},dp=class extends Ee{},Kg=class extends dp{},Vg=class extends Ee{constructor(e){super(e),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(t=>t*t))}},jg=class extends Ee{};pp=class extends zt{constructor(e){super(),this.config=e,this.patch_size=e.patch_size??16,this.max_soft_tokens=e.max_soft_tokens??280,this.pooling_kernel_size=e.pooling_kernel_size??3,this.resample=e.resample??3,this.rescale_factor=e.rescale_factor??1/255,this.do_rescale=e.do_rescale??!0,this.do_resize=e.do_resize??!0,this.do_convert_rgb=e.do_convert_rgb??!0}async _call(e){Array.isArray(e)||(e=[e]);let{patch_size:t,pooling_kernel_size:r}=this,a=this.max_soft_tokens*r**2,n=[],s=[],i=[];for(let o of e){if(this.do_convert_rgb&&(o=o.rgb()),this.do_resize){let[d,h]=SZ(o.height,o.width,t,a,r);(d!==o.height||h!==o.width)&&(o=await o.resize(h,d,{resample:this.resample}))}let H=Float32Array.from(o.data);if(this.do_rescale)for(let d=0;d<H.length;++d)H[d]*=this.rescale_factor;let{patches:_,positions:c,num_soft_tokens:l}=LZ(H,o.height,o.width,o.channels,t,a,r);n.push(_),s.push(c),i.push(l)}return{pixel_values:Ur(n,0),image_position_ids:Ur(s,0),num_soft_tokens_per_image:i}}},hp=class extends Ee{constructor(e){super(e),this.min_pixels=e.min_pixels??e.size?.shortest_edge,this.max_pixels=e.max_pixels??e.size?.longest_edge,this.patch_size=e.patch_size,this.merge_size=e.merge_size}get_resize_output_image_size(e,t){let r=this.patch_size*this.merge_size;return Hp(e.height,e.width,r,this.min_pixels,this.max_pixels)}async _call(e,...t){let{pixel_values:r,original_sizes:a,reshaped_input_sizes:n}=await super._call(e,...t),s=r,{temporal_patch_size:i,merge_size:o,patch_size:H}=this.config;s.dims[0]===1&&(s=Ue(Array.from({length:i},()=>s),0));let _=s.dims[0]/i,c=s.dims[1],l=Math.floor(s.dims[2]/H),d=Math.floor(s.dims[3]/H),h=s.view(_,i,c,Math.floor(l/o),o,H,Math.floor(d/o),o,H).permute(0,3,6,4,7,2,1,5,8).view(_*l*d,c*i*H*H),$=new j("int64",[_,l,d],[1,3]);return{pixel_values:h,image_grid_thw:$,original_sizes:a,reshaped_input_sizes:n}}},qg=class extends hp{get_resize_output_image_size(e,t){let r=this.patch_size*this.merge_size,a=this.config.temporal_patch_size??2;return Hp(e.height,e.width,r,this.min_pixels,this.max_pixels,a)}},Xg=class extends Ee{},zg=class extends Ee{async _call(e){let t=await super._call(e),r=t.pixel_values.dims,a=Kt([r[0],r[2],r[3]]);return{...t,pixel_mask:a}}},Hd=class extends Ee{constructor(e){super(e),this.do_image_splitting=e.do_image_splitting??!0,this.max_image_size=e.max_image_size}get_resize_for_vision_encoder(e,t){let[r,a]=e.dims.slice(-2),n=a/r;return a>=r?(a=Math.ceil(a/t)*t,r=Math.floor(a/n),r=Math.ceil(r/t)*t):(r=Math.ceil(r/t)*t,a=Math.floor(r*n),a=Math.ceil(a/t)*t),{height:r,width:a}}async _call(e,{do_image_splitting:t=null,return_row_col_info:r=!1}={}){let a;if(!Array.isArray(e))a=[[e]];else{if(e.length===0||!e[0])throw new Error("No images provided.");Array.isArray(e[0])?a=e:a=[e]}let n=[],s=[],i=[],o=[],H=[];for(let S of a){let I=await Promise.all(S.map(x=>this.preprocess(x)));o.push(...I.map(x=>x.original_size)),H.push(...I.map(x=>x.reshaped_input_size)),I.forEach(x=>x.pixel_values.unsqueeze_(0));let{longest_edge:g}=this.max_image_size,T;if(t??this.do_image_splitting){let x=new Array(I.length),v=new Array(I.length);T=await Promise.all(I.map(async(k,L)=>{let V=this.get_resize_for_vision_encoder(k.pixel_values,g),K=await dr(k.pixel_values,{size:[V.height,V.width]}),{frames:X,num_splits_h:Q,num_splits_w:z}=await this.split_image(K,this.max_image_size);return x[L]=Q,v[L]=z,Ue(X,0)})),s.push(x),i.push(v)}else{let x=[g,g];T=await Promise.all(I.map(v=>dr(v.pixel_values,{size:x}))),s.push(new Array(I.length).fill(0)),i.push(new Array(I.length).fill(0))}n.push(Ue(T,0))}let _=n.length,[c,l,d,h]=n[0].dims,$,m;if(_===1)$=n[0].unsqueeze_(0),m=xt([_,c,d,h],!0);else{let S=Math.max(...n.map(T=>T.dims.at(0)));m=xt([_,S,d,h],!0);let I=m.data,g=S*d*h;for(let T=0;T<_;++T){let x=n[T].dims[0];if(x<S){n[T]=Ue([n[T],xt([S-x,l,d,h],0)],0);let v=T*g+x*d*h,k=(T+1)*g;I.fill(!1,v,k)}}$=Ur(n,0)}return{pixel_values:$,pixel_attention_mask:m,original_sizes:o,reshaped_input_sizes:H,...r?{rows:s,cols:i}:{}}}async split_image(e,{longest_edge:t}){let r=t,a=t,n=[],[s,i]=e.dims.slice(-2),o=0,H=0;if(s>r||i>a){o=Math.ceil(s/r),H=Math.ceil(i/a);let _=Math.ceil(s/o),c=Math.ceil(i/H);for(let h=0;h<o;++h)for(let $=0;$<H;++$){let m,S,I,g;h===o-1?(S=s-_,g=s):(S=h*_,g=(h+1)*_),$===H-1?(m=i-c,I=i):(m=$*c,I=($+1)*c);let v=await Wd(e,[S,m],[g,I],[2,3]);n.push(v)}let l=r,d=a;(s!==l||i!==d)&&(e=await dr(e,{size:[l,d]}))}return n.push(e),{frames:n,num_splits_h:o,num_splits_w:H}}},Jg=class extends Ee{constructor(e){super({do_pad:!0,pad_size:{width:e.image_size,height:e.image_size},...e}),this.constant_values=this.config.background_color.map(t=>t*this.rescale_factor)}pad_image(e,t,r,a){return super.pad_image(e,t,r,{constant_values:this.constant_values,center:!0,...a})}},Qg=class extends Ee{constructor(e){let{resize_mode:t,fill_color:r,interpolation:a,size:n,...s}=e,i=t==="squash"?{width:n,height:n}:t==="shortest"?{shortest_edge:n}:{longest_edge:n},o=a==="bicubic"?3:2;super({...s,size:i,resample:o,do_center_crop:!0,crop_size:n,do_normalize:!0})}};Yg=class extends Ee{constructor(e){super(e),this.downsample_factor=e.downsample_factor??2,this.do_image_splitting=e.do_image_splitting??!0,this.min_tiles=e.min_tiles??2,this.max_tiles=e.max_tiles??10,this.use_thumbnail=e.use_thumbnail??!0,this.min_image_tokens=e.min_image_tokens??64,this.max_image_tokens=e.max_image_tokens??256,this.encoder_patch_size=e.encoder_patch_size??e.patch_size??16,this.tile_size=e.tile_size??512,this.max_pixels_tolerance=e.max_pixels_tolerance??2,this.return_row_col_info=e.return_row_col_info??!1;let t=this.max_image_tokens*this.downsample_factor**2,r=this.do_image_splitting?(this.tile_size/this.encoder_patch_size)**2:0;this.max_num_patches=Math.max(t,r)}_is_image_too_large(e,t){let r=this.encoder_patch_size*this.downsample_factor,a=Math.max(this.encoder_patch_size,gS(e,r)),n=Math.max(this.encoder_patch_size,gS(t,r));return a*n>this.max_image_tokens*(this.encoder_patch_size*this.downsample_factor)**2*this.max_pixels_tolerance}_get_grid_layout(e,t){let r=gZ(this.min_tiles,this.max_tiles),[a,n]=AZ(t/e,r,t,e,this.tile_size);return{grid_width:a,grid_height:n,target_width:this.tile_size*a,target_height:this.tile_size*n}}async _call(e,{return_row_col_info:t=null}={}){let r;Array.isArray(e)?Array.isArray(e[0])?r=e:r=[e]:r=[[e]];let a=[],n=[],s=[],i=[],o=[],H=[];for(let c of r){let l=await Promise.all(c.map(d=>this.preprocess(d,{do_pad:!1})));for(let{pixel_values:d}of l){let[,h,$]=d.dims,m=d.unsqueeze_(0),S=this.encoder_patch_size*this.downsample_factor,I=S**2,[g,T]=Hp(Math.max(S,h),Math.max(S,$),S,this.min_image_tokens*I,this.max_image_tokens*I).map(K=>Math.max(S,K)),x,v=1,k=1,L=this._is_image_too_large(h,$),V=this.do_image_splitting&&!(this.min_tiles===1&&this.max_tiles===1);if(L&&V){let{grid_width:K,grid_height:X,target_width:Q,target_height:z}=this._get_grid_layout(h,$);v=X,k=K;let M=await dr(m,{size:[z,Q]});x=[];for(let F=0;F<X;++F)for(let N=0;N<K;++N){let G=F*this.tile_size,te=N*this.tile_size;x.push(M.slice(null,null,[G,G+this.tile_size],[te,te+this.tile_size]))}this.use_thumbnail&&K*X!==1&&x.push(await dr(m,{size:[T,g]}))}else x=[await dr(m,{size:[T,g]})];for(let K of x){let[,,X,Q]=K.dims,z=bZ(K,this.encoder_patch_size),{padded:M,mask:F}=TZ(z,this.max_num_patches);a.push(M),n.push(F),s.push([Math.floor(X/this.encoder_patch_size),Math.floor(Q/this.encoder_patch_size)])}i.push(v),o.push(k),H.push([T,g])}}let _={pixel_values:Ue(a,0),pixel_attention_mask:Ur(n,0),spatial_shapes:new j("int64",BigInt64Array.from(s.flat(),BigInt),[s.length,2])};return(t??this.return_row_col_info)&&(_.image_rows=i,_.image_cols=o,_.image_sizes=H),_}},eb=class extends Ee{},yH=class extends Ee{post_process_panoptic_segmentation(...e){return Ng(...e)}post_process_instance_segmentation(...e){return Bg(...e)}},tb=class extends yH{},rb=class extends yH{},fp=class extends Ee{},ab=class extends fp{},Ep=class extends Ee{},nb=class extends Ep{},$p=class extends Ee{},sb=class extends $p{},mp=class extends Ee{},ib=class extends mp{},Ip=class extends Ee{},ob=class extends Ip{},Hb=class extends vH{},DH=class extends Ee{post_process_object_detection(...e){return xH(...e)}},_b=class extends DH{},cb=class extends DH{},er=336,xZ=[2,3],{ceil:qu,floor:Yn,sqrt:Xu}=Math,lb=class extends Ee{constructor(e){super({...e,do_normalize:!0,do_pad:!0,pad_size:"custom",do_convert_rgb:!0,do_resize:!0}),this._num_crops=e.num_crops}calc_num_image_tokens_from_image_size(e,t){let{num_img_tokens:r}=this.config;return Yn((Yn(t/er)*Yn(e/er)+1)*r+1+(Yn(t/er)+1)*Xu(r))}get_resize_output_image_size(e,t){let r=this._num_crops,[a,n]=e.size,s=a/n,i=1;for(;i*Math.ceil(i/s)<=r;)i+=1;i-=1;let o=Math.floor(i*336),H=Math.floor(o/s);return[o,H]}pad_image(e,t,r,a={}){let[n,s]=t,i=er*qu(n/er),o=er*qu(s/er),H=[1,1,1].map((_,c)=>(_-this.image_mean[c])/this.image_std[c]);return super.pad_image(e,t,{width:o,height:i},{center:!0,constant_values:H,...a})}async _call(e,{num_crops:t=null}={}){if(this._num_crops=t??=this.config.num_crops,t<4||Xu(t)%1!==0)throw new Error("num_crops must be a square number >= 4");Array.isArray(e)||(e=[e]);let r=e.length,a=await Promise.all(e.map(l=>this.preprocess(l))),n=a.map(l=>l.original_size),s=a.map(l=>l.reshaped_input_size),i=[];for(let{pixel_values:l}of a){l.unsqueeze_(0);let[d,h]=l.dims.slice(-2),$=await dr(l,{size:[er,er],mode:"bicubic"});if(t>0){let m=[],S=Xu(t),I=Yn(h/S),g=Yn(d/S);for(let x=0;x<S;++x)for(let v=0;v<S;++v){let k,L,V,K;x===S-1?(L=d-g,K=d):(L=x*g,K=(x+1)*g),v===S-1?(k=h-I,V=h):(k=v*I,V=(v+1)*I);let z=await Wd(l,[L,k],[K,V],xZ);m.push(z)}let T=await dr(Ue(m,0),{size:[er,er],mode:"bicubic"});i.push(Ue([$,T],0))}else i.push($)}let o=Ur(i,0),H=s.map(l=>l.map(d=>er*qu(d/er))),_=new j("int64",H.flat(),[r,2]),c=H.map(([l,d])=>this.calc_num_image_tokens_from_image_size(d,l));return{pixel_values:o,original_sizes:n,reshaped_input_sizes:s,image_sizes:_,num_img_tokens:c}}},ub=class extends Ee{get_resize_output_image_size(e,t){let{longest_edge:r}=t;if(r===void 0)throw new Error("size must contain 'longest_edge'");let[a,n]=e.size,s=Math.max(a,n)/r,i=a,o=n;s>1&&(i=Math.floor(a/s),o=Math.floor(n/s));let{patch_size:H,spatial_merge_size:_}=this.config;if(!_)throw new Error("config must contain 'spatial_merge_size'");let c=H*_,l=Math.floor((i-1)/c)+1,d=Math.floor((o-1)/c)+1;return[l*c,d*c]}},db=class extends Ee{},pb=class extends Ee{post_process_object_detection(...e){return xH(...e)}},eH=class extends Ee{reshape_input_points(e,t,r,a=!1){e=structuredClone(e);let n=pI(e);if(n.length===3)a||(n=[1,...n]),e=[e];else if(n.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 s=0;s<e.length;++s){let[i,o]=t[s],[H,_]=r[s],c=[_/o,H/i];for(let l=0;l<e[s].length;++l)for(let d=0;d<e[s][l].length;++d)for(let h=0;h<e[s][l][d].length;++h)e[s][l][d][h]*=c[h%2]}return new j("float32",Float32Array.from(e.flat(1/0)),n)}add_input_labels(e,t){let r=pI(e);if(r.length===2)r=[1,...r],e=[e];else if(r.length!==3)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");if(r.some((a,n)=>a!==t.dims[n]))throw Error(`The first ${r.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new j("int64",e.flat(1/0).map(BigInt),r)}async _call(e,{input_points:t=null,input_labels:r=null,input_boxes:a=null}={}){let n=await super._call(e);if(t&&(n.input_points=this.reshape_input_points(t,n.original_sizes,n.reshaped_input_sizes)),r){if(!n.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");n.input_labels=this.add_input_labels(r,n.input_points)}return a&&(n.input_boxes=this.reshape_input_points(a,n.original_sizes,n.reshaped_input_sizes,!0)),n}async post_process_masks(e,t,r,{mask_threshold:a=0,binarize:n=!0,pad_size:s=null}={}){let i=[];s=s??this.pad_size??this.size;let o=[s.height,s.width];for(let H=0;H<t.length;++H){let _=t[H],c=r[H],l=await dr(e[H],{mode:"bilinear",size:o});if(l=l.slice(null,null,[0,c[0]],[0,c[1]]),l=await dr(l,{mode:"bilinear",size:_}),n){let d=l.data,h=new Uint8Array(d.length);for(let $=0;$<d.length;++$)d[$]>a&&(h[$]=1);l=new j("bool",h,l.dims)}i.push(l)}return i}generate_crop_boxes(e,t,{crop_n_layers:r=0,overlap_ratio:a=512/1500,points_per_crop:n=32,crop_n_points_downscale_factor:s=1}={}){}},Sp=class extends Ee{post_process_semantic_segmentation(...e){return wg(...e)}},hb=class extends Sp{},Lp=class extends Ee{post_process_semantic_segmentation(...e){return wg(...e)}},fb=class extends Lp{},Eb=class extends Ee{},$b=class extends Ee{pad_image(e,t,r,a={}){let[n,s,i]=t;return super.pad_image(e,t,{width:s+(r-s%r)%r,height:n+(r-n%r)%r},{mode:"symmetric",center:!1,constant_values:-1,...a})}},Ap=class extends Ee{},mb=class extends Ap{},Ib=class extends Ee{async _call(e,t){Array.isArray(e)||(e=[e]),Array.isArray(t)||(t=[t]);let r=await Promise.all(e.map(s=>this.preprocess(s))),a=await Promise.all(t.map(s=>this.preprocess(s,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:Ur(r.map((s,i)=>Ue([s.pixel_values,a[i].pixel_values],0)),0),original_sizes:r.map(s=>s.original_size),reshaped_input_sizes:r.map(s=>s.reshaped_input_size)}}},Sb=class extends Ee{post_process_pose_estimation(e,t,{threshold:r=null}={}){let a=e.tolist(),[n,s,i,o]=e.dims,H=[];for(let _=0;_<n;++_){let c=a[_],l=t[_],d=[];for(let h=0;h<l.length;++h){let $=l[h],m=[],S=[],I=[],g=$.at(-2)/o,T=$.at(-1)/i;for(let x=0;x<c.length;++x){let[v,k]=[0,0],L=0,V=-1/0,K=c[x];for(let Q=0;Q<K.length;++Q){let z=K[Q];for(let M=0;M<z.length;++M){let F=z[M];L+=F,V=Math.max(V,F),v+=(M+.5)*F,k+=Q*F}}if(r!=null&&V<r)continue;let X=[g*v/L,T*k/L];m.push(X),I.push(x),S.push(V)}d.push({bbox:$,scores:S,labels:I,keypoints:m})}H.push(d)}return H}},gp=class extends Ee{post_process_object_detection(...e){return xH(...e)}},Lb=class extends gp{},Dt=class{static async from_pretrained(e,t={}){let r=await jr(e,_i,!0,t),a=r.image_processor_type??r.feature_extractor_type,n=hH[a?.replace(/Fast$/,"")];return n||(a!==void 0&&fe.warn(`Image processor type '${a}' not found, assuming base ImageProcessor. Please report this at ${TH}.`),n=Ee),new n(r)}},Ab=class extends Ne{static tokenizer_class=we;static image_processor_class=Dt;constructor(e,t,r){super(e,t,r);let{tasks_answer_post_processing_type:a,task_prompts_without_inputs:n,task_prompts_with_input:s}=this.image_processor.config;this.tasks_answer_post_processing_type=new Map(Object.entries(a??{})),this.task_prompts_without_inputs=new Map(Object.entries(n??{})),this.task_prompts_with_input=new Map(Object.entries(s??{})),this.regexes={quad_boxes:/(.+?)<loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)>/gm,bboxes:/([^<]+)?<loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)>/gm},this.size_per_bin=1e3}construct_prompts(e){typeof e=="string"&&(e=[e]);let t=[];for(let r of e)if(this.task_prompts_without_inputs.has(r))t.push(this.task_prompts_without_inputs.get(r));else{for(let[a,n]of this.task_prompts_with_input)if(r.includes(a)){t.push(n.replaceAll("{input}",r).replaceAll(a,""));break}t.length!==e.length&&t.push(r)}return t}post_process_generation(e,t,r){let a=this.tasks_answer_post_processing_type.get(t)??"pure_text";e=e.replaceAll("<s>","").replaceAll("</s>","");let n;switch(a){case"pure_text":n=e;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":let s=a==="ocr"?"quad_boxes":"bboxes",i=e.matchAll(this.regexes[s]),o=[],H=[];for(let[_,c,...l]of i)o.push(c?c.trim():o.at(-1)??""),H.push(l.map((d,h)=>(Number(d)+.5)/this.size_per_bin*r[h%2]));n={labels:o,[s]:H};break;default:throw new Error(`Task "${t}" (of type "${a}") not yet implemented.`)}return{[t]:n}}async _call(e,t=null,r={}){if(!e&&!t)throw new Error("Either text or images must be provided");let a=await this.image_processor(e,r),n=t?this.tokenizer(this.construct_prompts(t),r):{};return{...a,...n}}},gb=class extends Ne{static tokenizer_class=we;static image_processor_class=Dt;static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,t,r){super(e,t,r),this.image_seq_length=this.config.image_seq_length;let{boi_token:a,image_token:n,eoi_token:s}=this.tokenizer.config;this.boi_token=a,this.image_token=n,this.eoi_token=s;let i=n.repeat(this.image_seq_length);this.full_image_sequence=`
23
-
24
- ${a}${i}${s}
25
-
26
- `}async _call(e,t=null,r={}){typeof e=="string"&&(e=[e]);let a;return t&&(a=await this.image_processor(t,r),e=e.map(s=>s.replaceAll(this.boi_token,this.full_image_sequence))),{...this.tokenizer(e,r),...a}}},bb=class extends Ne{static image_processor_class=Dt;static feature_extractor_class=sr;static tokenizer_class=we;static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,t,r){super(e,t,r),this.audio_seq_length=this.config.audio_seq_length,this.image_seq_length=this.config.image_seq_length;let{audio_token_id:a,boa_token:n,audio_token:s,eoa_token:i,image_token_id:o,boi_token:H,image_token:_,eoi_token:c}=this.tokenizer.config;this.audio_token_id=a,this.boa_token=n,this.audio_token=s;let l=s.repeat(this.audio_seq_length);this.full_audio_sequence=`
27
-
28
- ${n}${l}${i}
29
-
30
- `,this.image_token_id=o,this.boi_token=H,this.image_token=_;let d=_.repeat(this.image_seq_length);this.full_image_sequence=`
31
-
32
- ${H}${d}${c}
33
-
34
- `}async _call(e,t=null,r=null,a={}){typeof e=="string"&&(e=[e]);let n;r&&(n=await this.feature_extractor(r,a),e=e.map(o=>o.replaceAll(this.audio_token,this.full_audio_sequence)));let s;return t&&(s=await this.image_processor(t,a),e=e.map(o=>o.replaceAll(this.image_token,this.full_image_sequence))),{...this.tokenizer(e,a),...s,...n}}},Tb=class extends Ne{static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,t,r){super(e,t,r),this.audio_ms_per_token=this.config.audio_ms_per_token??40,this.audio_seq_length=this.config.audio_seq_length??750,this.image_seq_length=this.config.image_seq_length??280;let{audio_token:a,boa_token:n,eoa_token:s,image_token:i,boi_token:o,eoi_token:H}=this.tokenizer.config;this.audio_token=a,this.boa_token=n,this.eoa_token=s,this.image_token=i,this.boi_token=o,this.eoi_token=H}static async from_pretrained(e,t={}){let[r,a,n]=await Promise.all([jr(e,ng,!0,t),we.from_pretrained(e,t),gd(e,sg,!1,t)]),s={tokenizer:a};return r.image_processor&&(s.image_processor=new pp(r.image_processor)),r.feature_extractor&&(s.feature_extractor=new ip(r.feature_extractor)),new this(r,s,n)}_compute_audio_num_tokens(e,t){let r=Math.round(t*20/1e3),a=Math.round(t*10/1e3),n=Math.floor(r/2),s=Math.floor((e+n-r-1)/a)+1;if(s<=0)return 0;for(let i=0;i<2;++i)s=Math.floor((s-1)/2)+1;return Math.min(s,this.audio_seq_length)}async _call(e,t=null,r=null,a={}){typeof e=="string"&&(e=[e]);let n;if(t){n=await this.image_processor(t,a);let i=n.num_soft_tokens_per_image,o=0;e=e.map(H=>H.replaceAll(this.image_token,()=>`
35
-
36
- ${this.boi_token}${this.image_token.repeat(i[o++])}${this.eoi_token}
37
-
38
- `))}let s;if(r){let i=Array.isArray(r)?r:[r];s=await this.feature_extractor(i[0],a);let o=this.feature_extractor.config.sampling_rate??16e3,H=0;e=e.map(_=>_.replaceAll(this.audio_token,()=>`
39
-
40
- ${this.boa_token}${this.audio_token.repeat(this._compute_audio_num_tokens(i[H++].length,o))}${this.eoa_token}
41
-
42
- `))}return{...this.tokenizer(e,a),...n,...s}}},CH=class extends Ne{static image_processor_class=Dt;static tokenizer_class=we;static image_token="<|image_pad|>";async _call(e,t=null,...r){Array.isArray(e)||(e=[e]);let a,n;if(t&&(a=await this.image_processor(t),n=a.image_grid_thw),n){let i=this.image_processor.config.merge_size**2,o=0,H=this.constructor.image_token,_=n.tolist();e=e.map(c=>{for(;c.includes(H);){let l=Number(_[o++].reduce((d,h)=>d*h,1n));c=c.replace(H,"<|placeholder|>".repeat(Math.floor(l/i)))}return c.replaceAll("<|placeholder|>",H)})}return{...this.tokenizer(e),...a}}},xb=class extends CH{static image_token="<|image|>"},vb=class extends Ne{static tokenizer_class=we;static feature_extractor_class=sr;static uses_processor_config=!0;_get_num_audio_features(e){let{hop_length:t}=this.feature_extractor.config.melspec_kwargs,{projector_window_size:r,projector_downsample_rate:a}=this.feature_extractor.config,n=Math.floor(r/a),s=Math.floor(e/t)+1,i=Math.floor(s/2);return Math.ceil(i/r)*n}async _call(e,t=null,r={}){if(Array.isArray(e))throw new Error("Batched inputs are not supported yet.");let a={};if(t){let{input_features:s}=await this.feature_extractor(t);a.input_features=s;let i=this._get_num_audio_features(t.length),o=new Uint8Array(i).fill(1);a.input_features_mask=new j("bool",o,[1,i]);let H=this.config.audio_token??"<|audio|>";if(!e.includes(H))throw new Error(`The input text does not contain the audio token ${H}.`);e=e.replaceAll(H,H.repeat(i))}return{...this.tokenizer(e,{add_special_tokens:!1,...r}),...a}}};yb=class extends Ne{static tokenizer_class=we;static image_processor_class=Dt;async _call(e,t,r={}){let a=e?await this.image_processor(e,r):{};return{...t?this.tokenizer(t,r):{},...a}}post_process_grounded_object_detection(e,t,{box_threshold:r=.25,text_threshold:a=.25,target_sizes:n=null}={}){let{logits:s,pred_boxes:i}=e,o=s.dims[0];if(n!==null&&n.length!==o)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let H=s.dims.at(1),_=s.sigmoid(),c=_.max(-1).tolist(),l=i.tolist().map(h=>h.map($=>Cg($))),d=[];for(let h=0;h<o;++h){let $=n!==null?n[h]:null;$!==null&&(l[h]=l[h].map(T=>T.map((x,v)=>x*$[(v+1)%2])));let m=c[h],S=[],I=[],g=[];for(let T=0;T<H;++T){let x=m[T];if(x<=r)continue;let v=l[h][T],k=_[h][T];S.push(x),g.push(v);let L=vZ(k.gt(a),t[h]);I.push(L)}d.push({scores:S,boxes:g,labels:this.batch_decode(I)})}return d}};_d=class extends Ne{static image_processor_class=Dt;static tokenizer_class=we;static uses_processor_config=!0;fake_image_token="<fake_token_around_image>";image_token="<image>";global_img_token="<global-img>";async _call(e,t=null,r={}){r.return_row_col_info??=!0;let a;t&&(a=await this.image_processor(t,r)),Array.isArray(e)||(e=[e]);let n=a.rows??[new Array(e.length).fill(0)],s=a.cols??[new Array(e.length).fill(0)],i=this.config.image_seq_len,o=[],H=[];for(let c=0;c<e.length;++c){let l=e[c],d=n[c],h=s[c];o.push(vO(l,this.image_token));let $=d.map((I,g)=>CZ(I,h[g],i,this.fake_image_token,this.image_token,this.global_img_token)),m=l.split(this.image_token);if(m.length===0)throw new Error("The image token should be present in the text.");let S=m[0];for(let I=0;I<$.length;++I)S+=$[I]+m[I+1];H.push(S)}return{...this.tokenizer(H),...a}}},Db=class extends Ne{static image_processor_class=Dt;static tokenizer_class=we;static uses_processor_config=!0;constructor(e,t,r){super(e,t,r),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(e,{images:t=null,chat_template:r="default"}={}){t?Array.isArray(t)||(t=[t]):t=await Promise.all(e.filter(m=>m.images).flatMap(m=>m.images).map(m=>Xt.read(m)));let a=this.tokenizer,n=a.apply_chat_template(e,{tokenize:!1,add_generation_prompt:!0,chat_template:r}),s=m=>a.encode(m,{add_special_tokens:!1}),i=n.split(this.image_tag),o=i.length-1;if(t.length!==o)throw new Error(`Number of images provided (${t.length}) does not match number of "${this.image_tag}" image tags (${o})`);let[H,_,c]=a.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]),l=s(i[0]),d=new Array(l.length).fill(!1);for(let m=1;m<i.length;++m){let S=new Array(this.num_image_tokens).fill(H),I=s(i[m]);l=$r(l,[_],S,[c],I);let g=new Array(this.num_image_tokens).fill(!0);d=$r(d,[!1],g,[!1],new Array(I.length).fill(!1))}let h=[1,l.length],$={input_ids:new j("int64",l,h),attention_mask:new j("int64",new Array(l.length).fill(1),h),images_seq_mask:new j("bool",d,h),images_emb_mask:new j("bool",new Array(o*this.num_image_tokens).fill(!0),[1,o,this.num_image_tokens])};if(t&&t.length>0){let m=await this.image_processor(t);return m.pixel_values.unsqueeze_(0),{...$,...m}}return $}},Cb=class extends Ne{static tokenizer_class=we;static image_processor_class=Dt;async _call(e=null,t=null,r={}){if(!e&&!t)throw new Error("Either text or images must be provided");let a=e?this.tokenizer(e,r):{},n=t?await this.image_processor(t,r):{};return{...a,...n}}},wb=class extends Ne{static tokenizer_class=we;static image_processor_class=Dt;async _call(e,t=null,r={}){let{image_rows:a,image_cols:n,image_sizes:s,...i}=await this.image_processor(e,{...r,return_row_col_info:!0});if(t){let o=this.config.image_token??"<image>",{tile_size:H=512,downsample_factor:_=2,encoder_patch_size:c=16,use_thumbnail:l=!0}=this.image_processor.config,d=g=>Math.ceil(Math.floor(g/c)/_),h=d(H)**2,$=this.config.image_start_token??"<|image_start|>",m=this.config.image_end_token??"<|image_end|>",S=this.config.image_thumbnail??"<|img_thumbnail|>";Array.isArray(t)||(t=[t]);let I=0;t=t.map(g=>{let T=g.split(o);return T[0]+T.slice(1).map(x=>{let v=I++,[k,L]=s[v],V=a[v],K=n[v],X=d(k)*d(L),Q=$;if(V>1||K>1){let z=o.repeat(h);for(let M=0;M<V;++M)for(let F=0;F<K;++F)Q+=`<|img_row_${M+1}_col_${F+1}|>`+z;l&&(Q+=S+o.repeat(X))}else Q+=o.repeat(X);return Q+m+x}).join("")})}return{...i,...t?this.tokenizer(t,r):{}}}},Nb=class extends Ne{static tokenizer_class=we;static image_processor_class=Dt;static uses_processor_config=!0;async _call(e,t=null,r={}){let a=await this.image_processor(e,r);if(t){let[s,i]=a.pixel_values.dims.slice(-2),{image_token:o,patch_size:H,num_additional_image_tokens:_}=this.config,c=Math.floor(s/H)*Math.floor(i/H)+_;t=structuredClone(t),Array.isArray(t)||(t=[t]);for(let l=0;l<t.length;++l)t[l]=t[l].replace(o,o.repeat(c))}let n=t?this.tokenizer(t,r):{};return{...a,...n}}},bS={char:["char_decode",1],bpe:["bpe_decode",2],wp:["wp_decode",102]},Bb=class extends Ne{static tokenizer_class=we;static image_processor_class=Dt;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(e,t){if(!bS.hasOwnProperty(t))throw new Error(`Format ${t} is not supported.`);let[r,a]=bS[t],n=this[r].bind(this),[s,i]=e.dims,o=[],H=[],_=e.tolist();for(let l=0;l<s;++l){let d=_[l],h=[],$=[];for(let S=1;S<i;++S){let[I,g]=nt(St(d[S]));if($.push(I),g==a)break;h.push(g)}let m=$.length>0?$.reduce((S,I)=>S*I,1):0;H.push(h),o.push(m)}return[n(H),o]}char_decode(e){return this.char_tokenizer.batch_decode(e).map(t=>t.replaceAll(" ",""))}bpe_decode(e){return this.bpe_tokenizer.batch_decode(e)}wp_decode(e){return this.wp_tokenizer.batch_decode(e).map(t=>t.replaceAll(" ",""))}batch_decode([e,t,r]){let[a,n]=this._decode_helper(e,"char"),[s,i]=this._decode_helper(t,"bpe"),[o,H]=this._decode_helper(r,"wp"),_=[],c=[];for(let l=0;l<a.length;++l){let[d,h]=nt([n[l],i[l],H[l]]);_.push([a[l],s[l],o[l]][h]),c.push(d)}return{generated_text:_,scores:c,char_preds:a,bpe_preds:s,wp_preds:o}}static async from_pretrained(...e){let t=await super.from_pretrained(...e),r=await we.from_pretrained("Xenova/gpt2"),a=await we.from_pretrained("Xenova/bert-base-uncased");return t.components={image_processor:t.image_processor,char_tokenizer:t.tokenizer,bpe_tokenizer:r,wp_tokenizer:a},t}async _call(e,t=null){let r=await this.image_processor(e);return t&&(r.labels=this.tokenizer(t).input_ids),r}},Mb=class extends Ne{static tokenizer_class=we;static feature_extractor_class=sr;async _call(e){return await this.feature_extractor(e)}},Pb=class extends Ne{static tokenizer_class=we;static image_processor_class=Dt},es="<image>";kb=class extends Ne{static tokenizer_class=we;static image_processor_class=Dt;static uses_processor_config=!1;async _call(e,t=null,r={}){t||(fe.warn("You are using PaliGemma without a text prefix. It will perform as a picture-captioning model."),t=""),Array.isArray(e)||(e=[e]),Array.isArray(t)||(t=[t]);let a=this.tokenizer.bos_token,n=this.image_processor.config.image_seq_length,s;t.some(H=>H.includes(es))?s=t.map(H=>{let _=H.replaceAll(es,es.repeat(n)),c=_.lastIndexOf(es),l=c===-1?0:c+es.length;return _.slice(0,l)+a+_.slice(l)+`
43
- `}):(fe.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 `<image>` tokens in the very beginning of your text. For this call, we will infer how many images each text has and add special tokens."),s=t.map(H=>wZ(H,a,n,es,e.length)));let i=this.tokenizer(s,r);return{...await this.image_processor(e,r),...i}}},TS="<|image|>",NZ=/<\|image_\d+\|>/g,Rb=class extends Ne{static image_processor_class=Dt;static tokenizer_class=we;async _call(e,t=null,{padding:r=!0,truncation:a=!0,num_crops:n=null}={}){Array.isArray(e)||(e=[e]);let s,i;if(t){i=await this.image_processor(t,{num_crops:n});let{num_img_tokens:o}=i,H=e.map((c,l)=>c.split(NZ).join(TS.repeat(o[l])));s=this.tokenizer(H,{padding:r,truncation:a});let _=this.tokenizer._tokenizer.token_to_id(TS);s.input_ids.map_(c=>c==_?-c:c)}else s=this.tokenizer(e);return{...s,...i}}},Ob=class extends Ne{static tokenizer_class=we;static image_processor_class=Dt;static uses_processor_config=!0;async _call(e,t=null,r={}){let a=await this.image_processor(e,r);if(t){let[s,i]=a.pixel_values.dims.slice(-2),{image_token:o,image_break_token:H,image_end_token:_,patch_size:c,spatial_merge_size:l}=this.config,d=c*l,h=Math.floor(s/d),$=Math.floor(i/d);t=structuredClone(t),Array.isArray(t)||(t=[t]);for(let m=0;m<t.length;++m){let S=o.repeat($),I=S+H,g=S+_,T=I.repeat(h-1)+g;t[m]=t[m].replace(o,T)}}let n=t?this.tokenizer(t,r):{};return{...a,...n}}},Gb=class extends Ne{static feature_extractor_class=op;async _call(e){return await this.feature_extractor(e)}post_process_speaker_diarization(...e){return this.feature_extractor.post_process_speaker_diarization(...e)}get sampling_rate(){return this.feature_extractor.config.sampling_rate}},bp=class extends CH{},Fb=class extends bp{},Tp=class extends Ne{static image_processor_class=Dt;async _call(...e){return await this.image_processor(...e)}post_process_masks(...e){return this.image_processor.post_process_masks(...e)}reshape_input_points(...e){return this.image_processor.reshape_input_points(...e)}},xp=class extends Tp{},Zb=class extends xp{},Ub=class extends Ne{static tokenizer_class=we;static feature_extractor_class=sr;async _call(e){return await this.feature_extractor(e)}},Wb=class extends Ne{static tokenizer_class=we;static feature_extractor_class=sr;static uses_processor_config=!0;async _call(e,t=null,r={}){if(Array.isArray(e))throw new Error("Batched inputs are not supported yet.");let a={};if(t){let s=t.length,{input_features:i}=await this.feature_extractor(t,{...r,max_length:s}),o=Math.round(s/this.config.encoder_ds_factor+1e-4),H=1+Math.ceil(o/this.config.stack_factor);a.audio_token_len=[H],a.audio_values=i;let _=this.config.audio_placeholder;if(!e.includes(_))throw new Error(`The input text does not contain the image token ${_}.`);e=e.replaceAll(_,_.repeat(H))}return{...this.tokenizer(e,{add_special_tokens:!1,...r}),...a}}},jo="[AUDIO]",BZ="[BEGIN_AUDIO]",MZ=375;Kb=class extends Ne{static tokenizer_class=we;static feature_extractor_class=sr;static uses_processor_config=!1;async _call(e,t=null,r={}){if(Array.isArray(e))throw new Error("Batched inputs are not supported yet.");let a={};if(t){if(!e.includes(jo))throw new Error(`The input text does not contain the audio token ${jo}.`);Array.isArray(t)||(t=[t]);let s=e.split(jo),i=s.length-1;if(i!==t.length)throw new Error(`The number of audio inputs (${t.length}) does not match the number of audio tokens in the text (${i}).`);let o=this.feature_extractor.config.n_samples,H=t.map(h=>PZ(h,o)),_=H.map(h=>h.length),c=H.flat(),l=(await Promise.all(c.map(h=>this.feature_extractor(h,r)))).map(h=>h.input_features);a.audio_values=l.length>1?Ue(l,0):l[0];let d=s[0];for(let h=0;h<_.length;++h){d+=BZ;for(let $=0;$<_[h];++$)d+=jo.repeat(MZ);d+=s[h+1]}e=d}return{...this.tokenizer(e,{add_special_tokens:!1,...r}),...a}}},xS=32,zu=6,qo=8,kZ=10,RZ=32,Vb=class extends Ne{static tokenizer_class=we;static feature_extractor_class=sr;static uses_processor_config=!1;get num_mel_frames_first_audio_chunk(){return(zu+1)*qo}get num_samples_first_audio_chunk(){let{hop_length:e,n_fft:t}=this.feature_extractor.config;return(this.num_mel_frames_first_audio_chunk-1)*e+Math.floor(t/2)}get num_samples_per_audio_chunk(){let{hop_length:e,n_fft:t}=this.feature_extractor.config;return qo*e+t}get num_right_pad_tokens(){return zu+1+kZ}get audio_length_per_tok(){return qo}get raw_audio_length_per_tok(){return qo*this.feature_extractor.config.hop_length}async _call(e,{is_streaming:t=!1,is_first_audio_chunk:r=!0}={}){if(yt(e,"VoxtralRealtimeProcessor"),!t&&!r)throw new Error("In non-streaming mode (`is_streaming=false`), `is_first_audio_chunk` must be `true`.");if(r)if(t){let a=xS*this.raw_audio_length_per_tok,n=new Float32Array(a+e.length);n.set(e,a);let s=await this.feature_extractor(n,{center:!0}),o=1+(xS+zu),H=new BigInt64Array(o).fill(BigInt(RZ));return H[0]=1n,{input_ids:new j("int64",H,[1,o]),...s}}else{let a=this.num_right_pad_tokens*this.raw_audio_length_per_tok,n=new Float32Array(e.length+a);return n.set(e),await this.feature_extractor(n,{center:!0})}else return await this.feature_extractor(e,{center:!1})}},jb=class extends Ne{static tokenizer_class=we;static feature_extractor_class=sr;async _call(e){return await this.feature_extractor(e)}},qb=class extends Ne{static tokenizer_class=we;static feature_extractor_class=sr;async _call(e){return await this.feature_extractor(e)}},Xb=class extends Ne{static tokenizer_class=we;static feature_extractor_class=sr;async _call(e){return await this.feature_extractor(e)}},zb=class{static async from_pretrained(e,t={}){let r=await jr(e,_i,!0,t),{image_processor_type:a,feature_extractor_type:n,processor_class:s}=r;if(s&&od[s])return od[s].from_pretrained(e,t);if(!a&&!n)throw new Error("No `image_processor_type` or `feature_extractor_type` found in the config.");let i={};if(a){let H=hH[a.replace(/Fast$/,"")];if(!H)throw new Error(`Unknown image_processor_type: '${a}'.`);i.image_processor=new H(r)}if(n){let H=hH[n];if(H)i.image_processor=new H(r);else{let _=tp[n];if(!_)throw new Error(`Unknown feature_extractor_type: '${n}'.`);i.feature_extractor=new _(r)}}let o={};return new Ne(o,i,null)}};fH=class cd{model_type=null;is_encoder_decoder=!1;max_position_embeddings;"transformers.js_config";constructor(t){Object.assign(this,t),this.normalized_config=as(this)}static async from_pretrained(t,{progress_callback:r=null,config:a=null,cache_dir:n=null,local_files_only:s=!1,revision:i="main"}={}){a&&!(a instanceof cd)&&(a=new cd(a));let o=a??await OZ(t,{progress_callback:r,config:a,cache_dir:n,local_files_only:s,revision:i});return new this(o)}},ls=class{static async from_pretrained(...e){return fH.from_pretrained(...e)}};dt=class{},de=class extends dt{constructor({logits:e,...t}){super(),this.logits=e;let r=Object.values(t);r.length>0&&(this.attentions=r)}},ot=class extends dt{constructor({logits:e}){super(),this.logits=e}},pt=class extends dt{constructor({logits:e}){super(),this.logits=e}},Nt=class extends dt{constructor({start_logits:e,end_logits:t}){super(),this.start_logits=e,this.end_logits=t}},cn=class extends dt{constructor({logits:e}){super(),this.logits=e}},VZ=class extends dt{constructor({alphas:e}){super(),this.alphas=e}},pr=class extends zt{_call(e,t){throw Error("`_call` should be implemented in a subclass")}},NH=class extends zt{_call(e,t){throw Error("`_call` should be implemented in a subclass")}},EH=class extends zt{constructor(){super(),this.processors=[]}push(e){this.processors.push(e)}extend(e){this.processors.push(...e)}_call(e,t){let r=t;for(let a of this.processors)r=a(e,r);return r}[Symbol.iterator](){return this.processors.values()}},eT=class extends pr{constructor(e){super(),this.bos_token_id=e}_call(e,t){for(let r=0;r<e.length;++r)if(e[r].length===1){let a=t[r].data;a.fill(-1/0),a[this.bos_token_id]=0}return t}},tT=class extends pr{constructor(e,t){super(),this.max_length=e,this.eos_token_id=Array.isArray(t)?t:[t]}_call(e,t){for(let r=0;r<e.length;++r)if(e[r].length===this.max_length-1){let a=t[r].data;a.fill(-1/0);for(let n of this.eos_token_id)a[n]=0}return t}},rT=class extends pr{constructor(e){super(),this.suppress_tokens=e}_call(e,t){for(let r=0;r<e.length;++r){let a=t[r].data;for(let n of this.suppress_tokens)a[n]=-1/0}return t}},vp=class extends pr{constructor(e,t){super(),this.begin_suppress_tokens=e,this.begin_index=t}_call(e,t){for(let r=0;r<e.length;++r)if(e[r].length===this.begin_index){let a=t[r].data;for(let n of this.begin_suppress_tokens)a[n]=-1/0}return t}},aT=class extends pr{constructor(e,t){super(),this.eos_token_id=Array.isArray(e.eos_token_id)?e.eos_token_id[0]:e.eos_token_id,this.no_timestamps_token_id=e.no_timestamps_token_id,this.timestamp_begin=this.no_timestamps_token_id+1,this.begin_index=t.length,t.at(-1)===this.no_timestamps_token_id&&(this.begin_index-=1),this.max_initial_timestamp_index=e.max_initial_timestamp_index}_call(e,t){for(let r=0;r<e.length;++r){let a=t[r].data;if(a[this.no_timestamps_token_id]=-1/0,e[r].length===this.begin_index){a.subarray(0,this.timestamp_begin).fill(-1/0);continue}let n=e[r].slice(this.begin_index),s=n.length>=1&&n[n.length-1]>=this.timestamp_begin,i=n.length<2||n[n.length-2]>=this.timestamp_begin;if(s&&(i?a.subarray(this.timestamp_begin).fill(-1/0):a.subarray(0,this.eos_token_id).fill(-1/0)),e[r].length===this.begin_index&&this.max_initial_timestamp_index!==null){let c=this.timestamp_begin+this.max_initial_timestamp_index;a.subarray(c+1).fill(-1/0)}let o=tL(a),H=Math.log(o.subarray(this.timestamp_begin).map(Math.exp).reduce((c,l)=>c+l)),_=nt(o.subarray(0,this.timestamp_begin))[0];H>_&&a.subarray(0,this.timestamp_begin).fill(-1/0)}return t}},nT=class extends pr{constructor(e){super(),this.no_repeat_ngram_size=e}getNgrams(e){let t=e.length,r=[];for(let n=0;n<t+1-this.no_repeat_ngram_size;++n){let s=[];for(let i=0;i<this.no_repeat_ngram_size;++i)s.push(e[n+i]);r.push(s.map(Number))}let a=new Map;for(let n of r){let s=n.slice(0,n.length-1),i=JSON.stringify(s),o=a.get(i)??[];o.push(n[n.length-1]),a.set(i,o)}return a}getGeneratedNgrams(e,t){let r=t.slice(t.length+1-this.no_repeat_ngram_size,t.length);return e.get(JSON.stringify(r.map(Number)))??[]}calcBannedNgramTokens(e){let t=[];if(e.length+1<this.no_repeat_ngram_size)return t;{let r=this.getNgrams(e);return this.getGeneratedNgrams(r,e)}}_call(e,t){for(let r=0;r<e.length;++r){let a=t[r].data,n=this.calcBannedNgramTokens(e[r]);for(let s of n)a[s]=-1/0}return t}},sT=class extends pr{constructor(e){super(),this.penalty=e}_call(e,t){for(let r=0;r<e.length;++r){let a=t[r].data;for(let n of new Set(e[r])){let s=Number(n);a[s]<0?a[s]*=this.penalty:a[s]/=this.penalty}}return t}},iT=class extends pr{constructor(e,t){super(),this.min_length=e,this.eos_token_id=Array.isArray(t)?t:[t]}_call(e,t){for(let r=0;r<e.length;++r)if(e[r].length<this.min_length){let a=t[r].data;for(let n of this.eos_token_id)a[n]=-1/0}return t}},oT=class extends pr{constructor(e,t,r){super(),this.prompt_length_to_skip=e,this.min_new_tokens=t,this.eos_token_id=Array.isArray(r)?r:[r]}_call(e,t){for(let r=0;r<e.length;++r)if(e[r].length-this.prompt_length_to_skip<this.min_new_tokens){let n=t[r].data;for(let s of this.eos_token_id)n[s]=-1/0}return t}},HT=class extends pr{constructor(e,t){super(),this.bad_words_ids=e,this.eos_token_id=Array.isArray(t)?t:[t]}_call(e,t){for(let r=0;r<e.length;++r){let a=t[r].data,n=e[r];for(let s of this.bad_words_ids){if(n.length<s.length-1)continue;let i=!0;for(let o=1;o<=s.length-1;++o)if(s.at(-o-1)!=n.at(-o)){i=!1;break}i&&(a[s.at(-1)]=-1/0)}}return t}},_T=class extends pr{constructor(e){if(super(),e<=1)throw new Error(`Require guidance scale >1 to use the classifier free guidance processor, got guidance scale ${e}.`);this.guidance_scale=e}_call(e,t){if(t.dims[0]!==2*e.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 ${t.dims[0]} for the logits and ${e.length} for the input ids.`);let r=e.length,a=t.slice([0,r],null),n=t.slice([r,t.dims[0]],null);for(let s=0;s<n.data.length;++s)n.data[s]+=(a.data[s]-n.data[s])*this.guidance_scale;return n}},cT=class extends NH{constructor(e){if(super(),typeof e!="number"||e<=0){let t=`\`temperature\` (=${e}) must be a strictly positive float, otherwise your next token scores will be invalid.`;e===0&&(t+=" If you're looking for greedy decoding strategies, set `do_sample=false`.")}this.temperature=e}_call(e,t){let r=t.data;for(let a=0;a<r.length;++a)r[a]/=this.temperature;return t}},jZ=class extends NH{constructor(e,{filter_value:t=-1/0,min_tokens_to_keep:r=1}={}){if(super(),e<0||e>1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${e}`);if(!Number.isInteger(r)||r<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${r}`);this.top_p=e,this.filter_value=t,this.min_tokens_to_keep=r}},qZ=class extends NH{constructor(e,{filter_value:t=-1/0,min_tokens_to_keep:r=1}={}){if(super(),!Number.isInteger(e)||e<0)throw new Error(`\`top_k\` must be a positive integer, but is ${e}`);this.top_k=Math.max(e,r),this.filter_value=t}},lT=class{max_length=20;max_new_tokens=null;min_length=0;min_new_tokens=null;early_stopping=!1;max_time=null;do_sample=!1;num_beams=1;num_beam_groups=1;penalty_alpha=null;use_cache=!0;temperature=1;top_k=50;top_p=1;typical_p=1;epsilon_cutoff=0;eta_cutoff=0;diversity_penalty=0;repetition_penalty=1;encoder_repetition_penalty=1;length_penalty=1;no_repeat_ngram_size=0;bad_words_ids=null;force_words_ids=null;renormalize_logits=!1;constraints=null;forced_bos_token_id=null;forced_eos_token_id=null;remove_invalid_values=!1;exponential_decay_length_penalty=null;suppress_tokens=null;streamer=null;begin_suppress_tokens=null;forced_decoder_ids=null;guidance_scale=null;num_return_sequences=1;output_attentions=!1;output_hidden_states=!1;output_scores=!1;return_dict_in_generate=!1;pad_token_id=null;bos_token_id=null;eos_token_id=null;encoder_no_repeat_ngram_size=0;decoder_start_token_id=null;generation_kwargs={};constructor(e){Object.assign(this,It(e,Object.getOwnPropertyNames(this)))}},Es=class extends zt{_call(e,t){throw Error("StoppingCriteria needs to be subclassed")}},yp=class uT extends zt{constructor(){super(),this.criteria=[]}push(t){this.criteria.push(t)}extend(t){t instanceof uT?t=t.criteria:t instanceof Es&&(t=[t]),this.criteria.push(...t)}_call(t,r){let a=new Array(t.length).fill(!1);for(let n of this.criteria){let s=n(t,r);for(let i=0;i<a.length;++i)a[i]||=s[i]}return a}[Symbol.iterator](){return this.criteria.values()}},dT=class extends Es{constructor(e,t=null){super(),this.max_length=e,this.max_position_embeddings=t}_call(e){return e.map(t=>t.length>=this.max_length)}},pT=class extends Es{constructor(e){super(),Array.isArray(e)||(e=[e]),this.eos_token_id=e}_call(e,t){return e.map(r=>{let a=r.at(-1);return this.eos_token_id.some(n=>a==n)})}},XZ=class extends Es{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(e,t){return new Array(e.length).fill(this.interrupted)}},BH=class extends zt{constructor(e){super(),this.generation_config=e}async _call(e){return this.sample(e)}async sample(e){throw Error("sample should be implemented in subclasses.")}getLogits(e,t){let r=e.dims.at(-1),a=e.data;if(t===-1)a=a.slice(-r);else{let n=t*r;a=a.slice(n,n+r)}return a}randomSelect(e){return P6(e)}static getSampler(e){if(e.do_sample)return new JZ(e);if(e.num_beams>1)return new QZ(e);if(e.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${e.num_return_sequences}.`);return new zZ(e)}},zZ=class extends BH{async sample(e){let t=nt(e.data)[1];return[[BigInt(t),0]]}},JZ=class extends BH{async sample(e){let t=e.dims.at(-1);this.generation_config.top_k>0&&(t=Math.min(this.generation_config.top_k,t));let[r,a]=await _n(e,t),n=St(r.data);return Array.from({length:this.generation_config.num_beams},()=>{let s=this.randomSelect(n);return[a.data[s],Math.log(n[s])]})}},QZ=class extends BH{async sample(e){let t=e.dims.at(-1);this.generation_config.top_k>0&&(t=Math.min(this.generation_config.top_k,t));let[r,a]=await _n(e,t),n=St(r.data);return Array.from({length:this.generation_config.num_beams},(s,i)=>[a.data[i],Math.log(n[i])])}},YZ=class{constructor(e){if(e)for(let t in e){if(t in this)throw new TypeError(`Key "${t}" conflicts with an existing property on DynamicCache`);let r=e[t];if(!(r instanceof j))throw new TypeError(`Expected a Tensor for key "${t}", got ${typeof r}`);this[t]=r}}get_seq_length(){let e=this;if(Object.keys(e).length===0)return 0;for(let t in e)if(t.startsWith("past_key_values."))return e[t].dims.at(-2);throw new Error("Unable to determine sequence length from the cache.")}update(e){for(let t in e){let r=this[t],a=e[t];r&&r!==a&&r.location==="gpu-buffer"&&r.dispose(),this[t]=a}}async dispose(){let e=[];for(let t of Object.values(this))t.location==="gpu-buffer"&&e.push(t.dispose());await Promise.all(e)}},MH=YZ,J={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,DecoderOnlyWithoutHead:5,MaskGeneration:6,ImageTextToText:7,Musicgen:8,MultiModality:9,Phi3V:10,AudioTextToText:11,AutoEncoder:12,ImageAudioTextToText:13,Supertonic:14,Chatterbox:15,VoxtralRealtime:16},oa={[J.DecoderOnly]:{sessions:(e,t)=>({model:t.model_file_name??"model"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[J.DecoderOnlyWithoutHead]:{sessions:(e,t)=>({model:t.model_file_name??"model"})},[J.Seq2Seq]:{sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[J.Vision2Seq]:{sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[J.Musicgen]:{sessions:()=>({model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[J.EncoderDecoder]:{sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0}},[J.MaskGeneration]:{sessions:()=>({model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"})},[J.ImageTextToText]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(e,t,r)=>{let a={...oa[J.ImageTextToText].text_only_sessions};return r||(a.vision_encoder="vision_encoder"),e.is_encoder_decoder&&(a.model="encoder_model"),a},cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[J.AudioTextToText]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(e,t,r)=>{let a={...oa[J.AudioTextToText].text_only_sessions};return r||(a.audio_encoder="audio_encoder"),a},cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[J.ImageAudioTextToText]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(e,t,r)=>{let a={...oa[J.ImageAudioTextToText].text_only_sessions};return r||(a.audio_encoder="audio_encoder",a.vision_encoder="vision_encoder"),a},optional_configs:{generation_config:"generation_config.json"}},[J.Phi3V]:{sessions:()=>({prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[J.MultiModality]:{sessions:()=>({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"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[J.AutoEncoder]:{sessions:()=>({encoder_model:"encoder_model",decoder_model:"decoder_model"})},[J.Supertonic]:{sessions:()=>({text_encoder:"text_encoder",latent_denoiser:"latent_denoiser",voice_decoder:"voice_decoder"})},[J.Chatterbox]:{sessions:()=>({embed_tokens:"embed_tokens",speech_encoder:"speech_encoder",model:"language_model",conditional_decoder:"conditional_decoder"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[J.VoxtralRealtime]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(e,t,r)=>{let a={...oa[J.VoxtralRealtime].text_only_sessions};return r||(a.audio_encoder="audio_encoder"),a},cache_sessions:{decoder_model_merged:!0,audio_encoder:!0},optional_configs:{generation_config:"generation_config.json"}},default:{sessions:(e,t)=>({model:t.model_file_name??"model"})}};ns=null;vS={[J.DecoderOnly]:{can_generate:!0,forward:_a,prepare_inputs:ni},[J.DecoderOnlyWithoutHead]:{can_generate:!1,forward:_a,prepare_inputs:ni},[J.Seq2Seq]:{can_generate:!0,forward:Xo,prepare_inputs:$H},[J.Vision2Seq]:{can_generate:!0,forward:Xo,prepare_inputs:$H},[J.Musicgen]:{can_generate:!0,forward:Xo},[J.EncoderDecoder]:{can_generate:!1,forward:Xo},[J.ImageTextToText]:{can_generate:!0,forward:s7,prepare_inputs:zo},[J.AudioTextToText]:{can_generate:!0,forward:n7,prepare_inputs:zo},[J.ImageAudioTextToText]:{can_generate:!0,prepare_inputs:zo},[J.Phi3V]:{can_generate:!0,prepare_inputs:zo},[J.MultiModality]:{can_generate:!0},[J.AutoEncoder]:{can_generate:!1,forward:r7},[J.Chatterbox]:{can_generate:!0,forward:Da},[J.VoxtralRealtime]:{can_generate:!0,prepare_inputs:ni},default:{can_generate:!1,forward:Da}};Ha=new Map,Np=new Map,cs=new Map,C=class extends zt{main_input_name="input_ids";forward_params=["input_ids","attention_mask"];_return_dict_in_generate_keys=null;constructor(e,t,r){super(),this.config=e,this.sessions=t,this.configs=r;let a=cs.get(this.constructor),{typeConfig:n}=yS(a,e);this.can_generate=n.can_generate,this._forward=n.forward,this._prepare_inputs_for_generation=n.prepare_inputs,this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){let e=[];for(let t of Object.values(this.sessions))e.push(t.release?.());return await Promise.all(e)}static async from_pretrained(e,{progress_callback:t=null,config:r=null,cache_dir:a=null,local_files_only:n=!1,revision:s="main",model_file_name:i=null,subfolder:o="onnx",device:H=null,dtype:_=null,use_external_data_format:c=null,session_options:l={}}={}){let d={progress_callback:t,config:r,cache_dir:a,local_files_only:n,revision:s,model_file_name:i,subfolder:o,device:H,dtype:_,use_external_data_format:c,session_options:l},h=cs.get(this);r=d.config=await ls.from_pretrained(e,d);let{typeConfig:$,textOnly:m,modelType:S}=yS(h,r);if(S===void 0){let x=h??r?.model_type;x!=="custom"&&fe.warn(`Model type for '${x}' not found, assuming encoder-only architecture. Please report this at ${TH}.`)}if(t&&!(t instanceof Qu)){let x={};try{let v=await wp(e,{config:r,dtype:_,device:H,model_file_name:i});(await Promise.all(v.map(L=>sn(e,L,d)))).forEach((L,V)=>{if(L.exists){let K=v[V]==="config.json";x[v[V]]={loaded:K?L.size??0:0,total:L.size??0}}})}catch(v){fe.warn(`Unable to fetch model file metadata for total progress tracking: ${v}`)}Object.keys(x).length>0&&(d.progress_callback=new Qu(t,x))}let I=$.sessions(r,d,m),g=[WZ(e,I,d,$.cache_sessions)];$.optional_configs&&g.push(o7(e,$.optional_configs,d));let T=await Promise.all(g);return new this(r,...T)}async _call(e){return await this.forward(e)}async forward(e){return await this._forward(this,e)}get generation_config(){return this.configs?.generation_config??null}_get_logits_processor(e,t,r=null){let a=new EH;if(e.repetition_penalty!==null&&e.repetition_penalty!==1&&a.push(new sT(e.repetition_penalty)),e.no_repeat_ngram_size!==null&&e.no_repeat_ngram_size>0&&a.push(new nT(e.no_repeat_ngram_size)),e.bad_words_ids!==null&&a.push(new HT(e.bad_words_ids,e.eos_token_id)),e.min_length!==null&&e.eos_token_id!==null&&e.min_length>0&&a.push(new iT(e.min_length,e.eos_token_id)),e.min_new_tokens!==null&&e.eos_token_id!==null&&e.min_new_tokens>0&&a.push(new oT(t,e.min_new_tokens,e.eos_token_id)),e.forced_bos_token_id!==null&&a.push(new eT(e.forced_bos_token_id)),e.forced_eos_token_id!==null&&a.push(new tT(e.max_length,e.forced_eos_token_id)),e.suppress_tokens!==null&&a.push(new rT(e.suppress_tokens)),e.begin_suppress_tokens!==null){let n=t>1||e.forced_bos_token_id===null?t:t+1;a.push(new vp(e.begin_suppress_tokens,n))}return e.guidance_scale!==null&&e.guidance_scale>1&&a.push(new _T(e.guidance_scale)),e.temperature===0&&e.do_sample&&(fe.warn("`do_sample` changed to false because `temperature: 0` implies greedy sampling (always selecting the most likely token), which is incompatible with `do_sample: true`."),e.do_sample=!1),e.do_sample&&e.temperature!==null&&e.temperature!==1&&a.push(new cT(e.temperature)),r!==null&&a.extend(r),a}_prepare_generation_config(e,t,r=lT){let a={...this.config};for(let s of["decoder","generator","text_config"])s in a&&Object.assign(a,a[s]);let n=new r(a);return Object.assign(n,this.generation_config??{}),e&&Object.assign(n,e),t&&Object.assign(n,It(t,Object.getOwnPropertyNames(n))),n}_get_stopping_criteria(e,t=null){let r=new yp;return e.max_length!==null&&r.push(new dT(e.max_length,this.config.max_position_embeddings??null)),e.eos_token_id!==null&&r.push(new pT(e.eos_token_id)),t&&r.extend(t),r}_validate_model_class(){if(!this.can_generate){let e=[ns.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,ns.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES,ns.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,ns.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES].filter(Boolean),t=cs.get(this.constructor),r=new Set,a=this.config.model_type;for(let s of e){let i=s?.get(a);i&&r.add(i)}let n=`The current model class (${t}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw r.size>0&&(n+=` Please use the following class instead: ${[...r].join(", ")}`),Error(n)}}prepare_inputs_for_generation(...e){if(!this._prepare_inputs_for_generation)throw new Error("prepare_inputs_for_generation is not implemented for this model.");return this._prepare_inputs_for_generation(this,...e)}_update_model_kwargs_for_generation({generated_input_ids:e,outputs:t,model_inputs:r,is_encoder_decoder:a}){return r.past_key_values=ud(t,r.past_key_values),r.input_ids=new j("int64",e.flat(),[e.length,1]),a?"decoder_attention_mask"in r&&(r.decoder_attention_mask=Ue([r.decoder_attention_mask,Kt([r.decoder_attention_mask.dims[0],1])],1)):r.attention_mask=Ue([r.attention_mask,Kt([r.attention_mask.dims[0],1])],1),r.position_ids=null,r}_prepare_model_inputs({inputs:e,bos_token_id:t,model_kwargs:r}){let a=It(r,this.forward_params),n=this.main_input_name;if(n in a){if(e)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else a[n]=e;return{inputs_tensor:a[n],model_inputs:a,model_input_name:n}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:e,model_inputs:t,model_input_name:r,generation_config:a}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!t.inputs_embeds&&"_prepare_inputs_embeds"in this){let{input_ids:s,pixel_values:i,attention_mask:o,...H}=t,_=await this._prepare_inputs_embeds(t);t={...H,...It(_,["inputs_embeds","attention_mask"])}}let{last_hidden_state:n}=await Da(this,t);if(a.guidance_scale!==null&&a.guidance_scale>1)n=Ue([n,dH(n,0)],0),"attention_mask"in t&&(t.attention_mask=Ue([t.attention_mask,Xd(t.attention_mask)],0));else if(t.decoder_input_ids){let s=ld(t.decoder_input_ids).dims[0];if(s!==n.dims[0]){if(n.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${n.dims[0]}) than the decoder inputs (${s}).`);n=Ue(Array.from({length:s},()=>n),0)}}return t.encoder_outputs=n,t}_prepare_decoder_input_ids_for_generation({batch_size:e,model_input_name:t,model_kwargs:r,decoder_start_token_id:a,bos_token_id:n,generation_config:s}){let{decoder_input_ids:i,...o}=r;if(!(i instanceof j)){if(i)Array.isArray(i[0])||(i=Array.from({length:e},()=>i));else if(a??=n,this.config.model_type==="musicgen")i=Array.from({length:e*this.config.decoder.num_codebooks},()=>[a]);else if(Array.isArray(a)){if(a.length!==e)throw new Error(`\`decoder_start_token_id\` expcted to have length ${e} but got ${a.length}`);i=a}else i=Array.from({length:e},()=>[a]);i=ld(i)}return o.decoder_attention_mask=jd(i),{input_ids:i,model_inputs:o}}async generate({inputs:e=null,generation_config:t=null,logits_processor:r=null,stopping_criteria:a=null,streamer:n=null,...s}){this._validate_model_class(),t=this._prepare_generation_config(t,s);let{inputs_tensor:i,model_inputs:o,model_input_name:H}=this._prepare_model_inputs({inputs:e,model_kwargs:s}),_=this.config.is_encoder_decoder;_&&("encoder_outputs"in o||(o=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:i,model_inputs:o,model_input_name:H,generation_config:t})));let c;_?{input_ids:c,model_inputs:o}=this._prepare_decoder_input_ids_for_generation({batch_size:o[H].dims.at(0),model_input_name:H,model_kwargs:o,decoder_start_token_id:t.decoder_start_token_id,bos_token_id:t.bos_token_id,generation_config:t}):c=o[H];let l=c.dims.at(-1);t.max_new_tokens!==null&&(t.max_length=l+t.max_new_tokens);let d=this._get_logits_processor(t,l,r),h=this._get_stopping_criteria(t,a),$=o[H].dims.at(0),m=BH.getSampler(t),S=new Array($).fill(0),I=c.tolist();n&&n.put(I);let g,T={},x={};for(;;){if(o=this.prepare_inputs_for_generation(I,o,t),g=await this.forward(o),t.return_dict_in_generate)if(t.output_attentions){let M=a7(g);for(let F in M)F in T||(T[F]=[]),T[F].push(M[F])}else this._return_dict_in_generate_keys&&Object.assign(x,It(g,this._return_dict_in_generate_keys));let K=g.logits.slice(null,-1,null).to("float32"),X=d(I,K),Q=[];for(let M=0;M<X.dims.at(0);++M){let F=X[M],N=await m(F);for(let[G,te]of N){let B=BigInt(G);S[M]+=te,I[M].push(B),Q.push([B]);break}}if(n&&n.put(Q),h(I).every(M=>M))break;o=this._update_model_kwargs_for_generation({generated_input_ids:Q,outputs:g,model_inputs:o,is_encoder_decoder:_})}n&&n.end();let v=new j("int64",I.flat(),[I.length,I[0].length]),k=ud(g,o.past_key_values),L=new Set(Object.values(k));for(let K of Object.values(g))K.location==="gpu-buffer"&&!L.has(K)&&K.dispose();return"past_key_values"in s||t.return_dict_in_generate||await k.dispose(),t.return_dict_in_generate?{sequences:v,past_key_values:k,...T,...x}:v}async _encode_input(e,t,r){if(!Object.hasOwn(this.sessions,e))throw new Error(`Model does not have a ${e} session.`);let a=this.sessions[e];return(await xe(a,It(t,a.inputNames)))[r]}async encode_image(e){return this._encode_input("vision_encoder",e,"image_features")}async encode_text(e){return this._encode_input("embed_tokens",e,"inputs_embeds")}async encode_audio(e){return this._encode_input("audio_encoder",e,"audio_features")}};Pp={};us(Pp,{ASTForAudioClassification:()=>NT,ASTModel:()=>wT,ASTPreTrainedModel:()=>OH,AfmoeForCausalLM:()=>yT,AfmoeModel:()=>vT,AfmoePreTrainedModel:()=>kH,AlbertForMaskedLM:()=>bT,AlbertForQuestionAnswering:()=>gT,AlbertForSequenceClassification:()=>AT,AlbertModel:()=>LT,AlbertPreTrainedModel:()=>$s,ApertusForCausalLM:()=>xT,ApertusModel:()=>TT,ApertusPreTrainedModel:()=>PH,ArceeForCausalLM:()=>CT,ArceeModel:()=>DT,ArceePreTrainedModel:()=>RH,BartForConditionalGeneration:()=>MT,BartForSequenceClassification:()=>PT,BartModel:()=>BT,BartPretrainedModel:()=>fi,BeitForImageClassification:()=>RT,BeitModel:()=>kT,BeitPreTrainedModel:()=>GH,BertForMaskedLM:()=>GT,BertForQuestionAnswering:()=>UT,BertForSequenceClassification:()=>FT,BertForTokenClassification:()=>ZT,BertModel:()=>OT,BertPreTrainedModel:()=>ln,BlenderbotForConditionalGeneration:()=>KT,BlenderbotModel:()=>WT,BlenderbotPreTrainedModel:()=>FH,BlenderbotSmallForConditionalGeneration:()=>jT,BlenderbotSmallModel:()=>VT,BlenderbotSmallPreTrainedModel:()=>ZH,BloomForCausalLM:()=>XT,BloomModel:()=>qT,BloomPreTrainedModel:()=>UH,CHMv2ForDepthEstimation:()=>rx,CHMv2PreTrainedModel:()=>Gp,CLIPModel:()=>nx,CLIPPreTrainedModel:()=>Ca,CLIPSegForImageSegmentation:()=>_x,CLIPSegModel:()=>Hx,CLIPSegPreTrainedModel:()=>WH,CLIPTextModel:()=>sx,CLIPTextModelWithProjection:()=>Up,CLIPVisionModel:()=>ix,CLIPVisionModelWithProjection:()=>ox,CamembertForMaskedLM:()=>JT,CamembertForQuestionAnswering:()=>ex,CamembertForSequenceClassification:()=>QT,CamembertForTokenClassification:()=>YT,CamembertModel:()=>zT,CamembertPreTrainedModel:()=>un,ChatterboxModel:()=>Rp,ChatterboxPreTrainedModel:()=>kp,ChineseCLIPModel:()=>tx,ChineseCLIPPreTrainedModel:()=>Op,ClapAudioModelWithProjection:()=>Zp,ClapModel:()=>ax,ClapPreTrainedModel:()=>Ei,ClapTextModelWithProjection:()=>Fp,CodeGenForCausalLM:()=>lx,CodeGenModel:()=>cx,CodeGenPreTrainedModel:()=>KH,Cohere2ForCausalLM:()=>hx,Cohere2Model:()=>px,Cohere2PreTrainedModel:()=>jH,CohereAsrForConditionalGeneration:()=>Ex,CohereAsrModel:()=>fx,CohereAsrPreTrainedModel:()=>qH,CohereForCausalLM:()=>dx,CohereModel:()=>ux,CoherePreTrainedModel:()=>VH,ConvBertForMaskedLM:()=>mx,ConvBertForQuestionAnswering:()=>Lx,ConvBertForSequenceClassification:()=>Ix,ConvBertForTokenClassification:()=>Sx,ConvBertModel:()=>$x,ConvBertPreTrainedModel:()=>dn,ConvNextForImageClassification:()=>gx,ConvNextModel:()=>Ax,ConvNextPreTrainedModel:()=>XH,ConvNextV2ForImageClassification:()=>Tx,ConvNextV2Model:()=>bx,ConvNextV2PreTrainedModel:()=>zH,DFineForObjectDetection:()=>Dx,DFineModel:()=>yx,DFinePreTrainedModel:()=>QH,DINOv3ConvNextModel:()=>rv,DINOv3ConvNextPreTrainedModel:()=>Qp,DINOv3ViTModel:()=>av,DINOv3ViTPreTrainedModel:()=>Yp,DPTForDepthEstimation:()=>lv,DPTModel:()=>cv,DPTPreTrainedModel:()=>n_,DacDecoderModel:()=>jp,DacDecoderOutput:()=>Kp,DacEncoderModel:()=>Vp,DacEncoderOutput:()=>Wp,DacModel:()=>Cx,DacPreTrainedModel:()=>$i,DebertaForMaskedLM:()=>Nx,DebertaForQuestionAnswering:()=>Px,DebertaForSequenceClassification:()=>Bx,DebertaForTokenClassification:()=>Mx,DebertaModel:()=>wx,DebertaPreTrainedModel:()=>pn,DebertaV2ForMaskedLM:()=>Gx,DebertaV2ForQuestionAnswering:()=>Ux,DebertaV2ForSequenceClassification:()=>Fx,DebertaV2ForTokenClassification:()=>Zx,DebertaV2Model:()=>Ox,DebertaV2PreTrainedModel:()=>hn,DecisionTransformerModel:()=>Wx,DecisionTransformerPreTrainedModel:()=>qp,DeepseekV3ForCausalLM:()=>Rx,DeepseekV3Model:()=>kx,DeepseekV3PreTrainedModel:()=>YH,DeiTForImageClassification:()=>Vx,DeiTModel:()=>Kx,DeiTPreTrainedModel:()=>e_,DepthAnythingForDepthEstimation:()=>jx,DepthAnythingPreTrainedModel:()=>Xp,DepthProForDepthEstimation:()=>qx,DepthProPreTrainedModel:()=>zp,DetrForObjectDetection:()=>zx,DetrForSegmentation:()=>Jx,DetrModel:()=>Xx,DetrObjectDetectionOutput:()=>t_,DetrPreTrainedModel:()=>mi,DetrSegmentationOutput:()=>Jp,Dinov2ForImageClassification:()=>Yx,Dinov2Model:()=>Qx,Dinov2PreTrainedModel:()=>r_,Dinov2WithRegistersForImageClassification:()=>tv,Dinov2WithRegistersModel:()=>ev,Dinov2WithRegistersPreTrainedModel:()=>a_,DistilBertForMaskedLM:()=>Hv,DistilBertForQuestionAnswering:()=>ov,DistilBertForSequenceClassification:()=>sv,DistilBertForTokenClassification:()=>iv,DistilBertModel:()=>nv,DistilBertPreTrainedModel:()=>fn,DonutSwinModel:()=>_v,DonutSwinPreTrainedModel:()=>eh,EdgeTamModel:()=>Lw,EfficientNetForImageClassification:()=>dv,EfficientNetModel:()=>uv,EfficientNetPreTrainedModel:()=>s_,ElectraForMaskedLM:()=>hv,ElectraForQuestionAnswering:()=>$v,ElectraForSequenceClassification:()=>fv,ElectraForTokenClassification:()=>Ev,ElectraModel:()=>pv,ElectraPreTrainedModel:()=>En,Ernie4_5ForCausalLM:()=>Iv,Ernie4_5Model:()=>mv,Ernie4_5PretrainedModel:()=>i_,EsmForMaskedLM:()=>Lv,EsmForSequenceClassification:()=>Av,EsmForTokenClassification:()=>gv,EsmModel:()=>Sv,EsmPreTrainedModel:()=>Is,EuroBertForMaskedLM:()=>Tv,EuroBertForSequenceClassification:()=>xv,EuroBertForTokenClassification:()=>vv,EuroBertModel:()=>bv,EuroBertPreTrainedModel:()=>Ss,ExaoneForCausalLM:()=>Dv,ExaoneModel:()=>yv,ExaonePreTrainedModel:()=>o_,FalconForCausalLM:()=>wv,FalconH1ForCausalLM:()=>Bv,FalconH1Model:()=>Nv,FalconH1PreTrainedModel:()=>__,FalconModel:()=>Cv,FalconPreTrainedModel:()=>H_,FastViTForImageClassification:()=>Pv,FastViTModel:()=>Mv,FastViTPreTrainedModel:()=>c_,Florence2ForConditionalGeneration:()=>kv,Florence2PreTrainedModel:()=>th,GLPNForDepthEstimation:()=>ey,GLPNModel:()=>Yv,GLPNPreTrainedModel:()=>$_,GPT2LMHeadModel:()=>cy,GPT2Model:()=>_y,GPT2PreTrainedModel:()=>A_,GPTBigCodeForCausalLM:()=>ry,GPTBigCodeModel:()=>ty,GPTBigCodePreTrainedModel:()=>m_,GPTJForCausalLM:()=>uy,GPTJModel:()=>ly,GPTJPreTrainedModel:()=>g_,GPTNeoForCausalLM:()=>ny,GPTNeoModel:()=>ay,GPTNeoPreTrainedModel:()=>I_,GPTNeoXForCausalLM:()=>iy,GPTNeoXModel:()=>sy,GPTNeoXPreTrainedModel:()=>S_,Gemma2ForCausalLM:()=>Fv,Gemma2Model:()=>Gv,Gemma2PreTrainedModel:()=>u_,Gemma3ForCausalLM:()=>Kv,Gemma3ForConditionalGeneration:()=>nh,Gemma3Model:()=>Wv,Gemma3PreTrainedModel:()=>ah,Gemma3nForCausalLM:()=>Vv,Gemma3nForConditionalGeneration:()=>Ii,Gemma3nPreTrainedModel:()=>sh,Gemma4ForCausalLM:()=>jv,Gemma4ForConditionalGeneration:()=>d_,GemmaForCausalLM:()=>Ov,GemmaModel:()=>Rv,GemmaPreTrainedModel:()=>l_,GlmForCausalLM:()=>Xv,GlmModel:()=>qv,GlmMoeDsaForCausalLM:()=>Jv,GlmMoeDsaModel:()=>zv,GlmMoeDsaPreTrainedModel:()=>h_,GlmOcrForConditionalGeneration:()=>Qv,GlmPreTrainedModel:()=>p_,GptOssForCausalLM:()=>Hy,GptOssModel:()=>oy,GptOssPreTrainedModel:()=>L_,GraniteForCausalLM:()=>py,GraniteModel:()=>dy,GraniteMoeHybridForCausalLM:()=>fy,GraniteMoeHybridModel:()=>hy,GraniteMoeHybridPreTrainedModel:()=>T_,GranitePreTrainedModel:()=>b_,GraniteSpeechForConditionalGeneration:()=>Ey,GroundingDinoForObjectDetection:()=>$y,GroundingDinoPreTrainedModel:()=>ch,GroupViTModel:()=>my,GroupViTPreTrainedModel:()=>lh,HeliumForCausalLM:()=>Sy,HeliumModel:()=>Iy,HeliumPreTrainedModel:()=>v_,HieraForImageClassification:()=>Ay,HieraModel:()=>Ly,HieraPreTrainedModel:()=>y_,HubertForCTC:()=>Dy,HubertForSequenceClassification:()=>Cy,HubertModel:()=>yy,HubertPreTrainedModel:()=>vy,HunYuanDenseV1ForCausalLM:()=>Ny,HunYuanDenseV1Model:()=>wy,HunYuanDenseV1PreTrainedModel:()=>D_,IJepaForImageClassification:()=>My,IJepaModel:()=>By,IJepaPreTrainedModel:()=>C_,Idefics3ForConditionalGeneration:()=>uh,JAISLMHeadModel:()=>ky,JAISModel:()=>Py,JAISPreTrainedModel:()=>w_,JinaCLIPModel:()=>Ry,JinaCLIPPreTrainedModel:()=>Si,JinaCLIPTextModel:()=>dh,JinaCLIPVisionModel:()=>Oy,Lfm2ForCausalLM:()=>Fy,Lfm2Model:()=>Gy,Lfm2MoeForCausalLM:()=>Wy,Lfm2MoeModel:()=>Uy,Lfm2MoePreTrainedModel:()=>B_,Lfm2PreTrainedModel:()=>N_,Lfm2VlForConditionalGeneration:()=>Ky,LightOnOcrForConditionalGeneration:()=>Zy,LiteWhisperForConditionalGeneration:()=>PN,Llama4ForCausalLM:()=>qy,Llama4PreTrainedModel:()=>ph,LlamaForCausalLM:()=>jy,LlamaModel:()=>Vy,LlamaPreTrainedModel:()=>M_,LlavaForConditionalGeneration:()=>Kr,LlavaOnevisionForConditionalGeneration:()=>Kr,LlavaPreTrainedModel:()=>rh,LlavaQwen2ForCausalLM:()=>Uv,LongT5ForConditionalGeneration:()=>zy,LongT5Model:()=>Xy,LongT5PreTrainedModel:()=>P_,M2M100ForConditionalGeneration:()=>Qy,M2M100Model:()=>Jy,M2M100PreTrainedModel:()=>k_,MBartForCausalLM:()=>iD,MBartForConditionalGeneration:()=>nD,MBartForSequenceClassification:()=>sD,MBartModel:()=>aD,MBartPreTrainedModel:()=>Ls,MPNetForMaskedLM:()=>VD,MPNetForQuestionAnswering:()=>XD,MPNetForSequenceClassification:()=>jD,MPNetForTokenClassification:()=>qD,MPNetModel:()=>KD,MPNetPreTrainedModel:()=>$n,MT5ForConditionalGeneration:()=>YD,MT5Model:()=>QD,MT5PreTrainedModel:()=>q_,MarianMTModel:()=>eD,MarianModel:()=>Yy,MarianPreTrainedModel:()=>R_,MaskFormerForInstanceSegmentation:()=>rD,MaskFormerModel:()=>tD,MaskFormerPreTrainedModel:()=>O_,Metric3DForDepthEstimation:()=>oD,Metric3DPreTrainedModel:()=>hh,Metric3Dv2ForDepthEstimation:()=>HD,Metric3Dv2PreTrainedModel:()=>fh,MgpstrForSceneTextRecognition:()=>_D,MgpstrModelOutput:()=>Eh,MgpstrPreTrainedModel:()=>$h,MimiDecoderModel:()=>Lh,MimiDecoderOutput:()=>Ih,MimiEncoderModel:()=>Sh,MimiEncoderOutput:()=>mh,MimiModel:()=>cD,MimiPreTrainedModel:()=>Li,Mistral4ForCausalLM:()=>pD,Mistral4Model:()=>dD,Mistral4PreTrainedModel:()=>F_,MistralForCausalLM:()=>uD,MistralModel:()=>lD,MistralPreTrainedModel:()=>G_,MobileBertForMaskedLM:()=>fD,MobileBertForQuestionAnswering:()=>$D,MobileBertForSequenceClassification:()=>ED,MobileBertModel:()=>hD,MobileBertPreTrainedModel:()=>As,MobileLLMForCausalLM:()=>ID,MobileLLMModel:()=>mD,MobileLLMPreTrainedModel:()=>Z_,MobileNetV1ForImageClassification:()=>LD,MobileNetV1ForSemanticSegmentation:()=>AD,MobileNetV1Model:()=>SD,MobileNetV1PreTrainedModel:()=>Ai,MobileNetV2ForImageClassification:()=>bD,MobileNetV2ForSemanticSegmentation:()=>TD,MobileNetV2Model:()=>gD,MobileNetV2PreTrainedModel:()=>gi,MobileNetV3ForImageClassification:()=>vD,MobileNetV3ForSemanticSegmentation:()=>yD,MobileNetV3Model:()=>xD,MobileNetV3PreTrainedModel:()=>bi,MobileNetV4ForImageClassification:()=>CD,MobileNetV4ForSemanticSegmentation:()=>wD,MobileNetV4Model:()=>DD,MobileNetV4PreTrainedModel:()=>Ti,MobileViTForImageClassification:()=>BD,MobileViTModel:()=>ND,MobileViTPreTrainedModel:()=>U_,MobileViTV2ForImageClassification:()=>PD,MobileViTV2Model:()=>MD,MobileViTV2PreTrainedModel:()=>W_,ModernBertDecoderForCausalLM:()=>ZD,ModernBertDecoderModel:()=>FD,ModernBertDecoderPreTrainedModel:()=>K_,ModernBertForMaskedLM:()=>RD,ModernBertForSequenceClassification:()=>OD,ModernBertForTokenClassification:()=>GD,ModernBertModel:()=>kD,ModernBertPreTrainedModel:()=>gs,Moondream1ForConditionalGeneration:()=>Zv,MoonshineForConditionalGeneration:()=>WD,MoonshineModel:()=>UD,MoonshinePreTrainedModel:()=>V_,MptForCausalLM:()=>JD,MptModel:()=>zD,MptPreTrainedModel:()=>j_,MultiModalityCausalLM:()=>eC,MultiModalityPreTrainedModel:()=>Ah,MusicgenForCausalLM:()=>rC,MusicgenForConditionalGeneration:()=>gh,MusicgenModel:()=>tC,MusicgenPreTrainedModel:()=>X_,NanoChatForCausalLM:()=>nC,NanoChatModel:()=>aC,NanoChatPreTrainedModel:()=>z_,NemotronHForCausalLM:()=>iC,NemotronHModel:()=>sC,NemotronHPreTrainedModel:()=>J_,NeoBertForMaskedLM:()=>HC,NeoBertForQuestionAnswering:()=>lC,NeoBertForSequenceClassification:()=>_C,NeoBertForTokenClassification:()=>cC,NeoBertModel:()=>oC,NeoBertPreTrainedModel:()=>mn,NomicBertModel:()=>uC,NomicBertPreTrainedModel:()=>bh,OPTForCausalLM:()=>TC,OPTModel:()=>bC,OPTPreTrainedModel:()=>nc,Olmo2ForCausalLM:()=>fC,Olmo2Model:()=>hC,Olmo2PreTrainedModel:()=>Y_,Olmo3ForCausalLM:()=>$C,Olmo3Model:()=>EC,Olmo3PreTrainedModel:()=>ec,OlmoForCausalLM:()=>pC,OlmoHybridForCausalLM:()=>IC,OlmoHybridModel:()=>mC,OlmoHybridPreTrainedModel:()=>tc,OlmoModel:()=>dC,OlmoPreTrainedModel:()=>Q_,OpenAIPrivacyFilterForTokenClassification:()=>LC,OpenAIPrivacyFilterModel:()=>SC,OpenAIPrivacyFilterPreTrainedModel:()=>rc,OpenELMForCausalLM:()=>gC,OpenELMModel:()=>AC,OpenELMPreTrainedModel:()=>ac,OwlViTForObjectDetection:()=>DC,OwlViTModel:()=>yC,OwlViTPreTrainedModel:()=>ic,Owlv2ForObjectDetection:()=>vC,Owlv2Model:()=>xC,Owlv2PreTrainedModel:()=>sc,PaliGemmaForConditionalGeneration:()=>CC,ParakeetForCTC:()=>wC,ParakeetPreTrainedModel:()=>Th,PatchTSMixerForPrediction:()=>BC,PatchTSMixerModel:()=>NC,PatchTSMixerPreTrainedModel:()=>oc,PatchTSTForPrediction:()=>PC,PatchTSTModel:()=>MC,PatchTSTPreTrainedModel:()=>Hc,Phi3ForCausalLM:()=>GC,Phi3Model:()=>OC,Phi3PreTrainedModel:()=>cc,Phi3VForCausalLM:()=>vh,Phi3VPreTrainedModel:()=>xh,PhiForCausalLM:()=>RC,PhiModel:()=>kC,PhiPreTrainedModel:()=>_c,PreTrainedModel:()=>C,PvtForImageClassification:()=>ZC,PvtModel:()=>FC,PvtPreTrainedModel:()=>lc,PyAnnoteForAudioFrameClassification:()=>WC,PyAnnoteModel:()=>UC,PyAnnotePreTrainedModel:()=>uc,Qwen2ForCausalLM:()=>VC,Qwen2Model:()=>KC,Qwen2MoeForCausalLM:()=>qC,Qwen2MoeModel:()=>jC,Qwen2MoePreTrainedModel:()=>pc,Qwen2PreTrainedModel:()=>dc,Qwen2VLForCausalLM:()=>oh,Qwen2VLForConditionalGeneration:()=>f_,Qwen2VLPreTrainedModel:()=>ih,Qwen2_5_VLForCausalLM:()=>Hh,Qwen2_5_VLForConditionalGeneration:()=>E_,Qwen3ForCausalLM:()=>zC,Qwen3Model:()=>XC,Qwen3MoeForCausalLM:()=>QC,Qwen3MoeModel:()=>JC,Qwen3MoePreTrainedModel:()=>fc,Qwen3NextForCausalLM:()=>ew,Qwen3NextModel:()=>YC,Qwen3NextPreTrainedModel:()=>Ec,Qwen3PreTrainedModel:()=>hc,Qwen3VLForCausalLM:()=>yh,Qwen3VLForConditionalGeneration:()=>$c,Qwen3VLMoeForCausalLM:()=>rw,Qwen3VLMoeForConditionalGeneration:()=>tw,Qwen3_5ForCausalLM:()=>Dh,Qwen3_5ForConditionalGeneration:()=>mc,Qwen3_5MoeForCausalLM:()=>nw,Qwen3_5MoeForConditionalGeneration:()=>aw,RFDetrForObjectDetection:()=>Hw,RFDetrModel:()=>ow,RFDetrObjectDetectionOutput:()=>Ch,RFDetrPreTrainedModel:()=>Sc,RTDetrForObjectDetection:()=>vx,RTDetrModel:()=>xx,RTDetrObjectDetectionOutput:()=>ms,RTDetrPreTrainedModel:()=>JH,RTDetrV2ForObjectDetection:()=>Iw,RTDetrV2Model:()=>mw,RTDetrV2ObjectDetectionOutput:()=>wh,RTDetrV2PreTrainedModel:()=>Lc,ResNetForImageClassification:()=>iw,ResNetModel:()=>sw,ResNetPreTrainedModel:()=>Ic,RoFormerForMaskedLM:()=>hw,RoFormerForQuestionAnswering:()=>$w,RoFormerForSequenceClassification:()=>fw,RoFormerForTokenClassification:()=>Ew,RoFormerModel:()=>pw,RoFormerPreTrainedModel:()=>Sn,RobertaForMaskedLM:()=>cw,RobertaForQuestionAnswering:()=>dw,RobertaForSequenceClassification:()=>lw,RobertaForTokenClassification:()=>uw,RobertaModel:()=>_w,RobertaPreTrainedModel:()=>In,Sam2ImageSegmentationOutput:()=>Mh,Sam2Model:()=>Ac,Sam2PreTrainedModel:()=>Ph,Sam3TrackerModel:()=>Aw,SamImageSegmentationOutput:()=>Nh,SamModel:()=>Sw,SamPreTrainedModel:()=>Bh,SapiensForDepthEstimation:()=>bw,SapiensForNormalEstimation:()=>Tw,SapiensForSemanticSegmentation:()=>gw,SapiensPreTrainedModel:()=>xi,SegformerForImageClassification:()=>vw,SegformerForSemanticSegmentation:()=>yw,SegformerModel:()=>xw,SegformerPreTrainedModel:()=>vi,SiglipModel:()=>Dw,SiglipPreTrainedModel:()=>gc,SiglipTextModel:()=>kh,SiglipVisionModel:()=>Cw,SmolLM3ForCausalLM:()=>Nw,SmolLM3Model:()=>ww,SmolLM3PreTrainedModel:()=>bc,SmolVLMForConditionalGeneration:()=>Bw,SnacDecoderModel:()=>Oh,SnacEncoderModel:()=>Rh,SnacModel:()=>Mw,SnacPreTrainedModel:()=>yi,SolarOpenForCausalLM:()=>kw,SolarOpenModel:()=>Pw,SolarOpenPreTrainedModel:()=>Tc,SpeechT5ForSpeechToText:()=>Ow,SpeechT5ForTextToSpeech:()=>Gw,SpeechT5HifiGan:()=>Fw,SpeechT5Model:()=>Rw,SpeechT5PreTrainedModel:()=>Di,SqueezeBertForMaskedLM:()=>Uw,SqueezeBertForQuestionAnswering:()=>Kw,SqueezeBertForSequenceClassification:()=>Ww,SqueezeBertModel:()=>Zw,SqueezeBertPreTrainedModel:()=>bs,StableLmForCausalLM:()=>jw,StableLmModel:()=>Vw,StableLmPreTrainedModel:()=>xc,Starcoder2ForCausalLM:()=>Xw,Starcoder2Model:()=>qw,Starcoder2PreTrainedModel:()=>vc,StyleTextToSpeech2Model:()=>zw,StyleTextToSpeech2PreTrainedModel:()=>Gh,SupertonicForConditionalGeneration:()=>Zh,SupertonicPreTrainedModel:()=>Fh,Swin2SRForImageSuperResolution:()=>tN,Swin2SRModel:()=>eN,Swin2SRPreTrainedModel:()=>yc,SwinForImageClassification:()=>Qw,SwinForSemanticSegmentation:()=>Yw,SwinModel:()=>Jw,SwinPreTrainedModel:()=>Ci,T5ForConditionalGeneration:()=>aN,T5Model:()=>rN,T5PreTrainedModel:()=>Dc,TableTransformerForObjectDetection:()=>sN,TableTransformerModel:()=>nN,TableTransformerObjectDetectionOutput:()=>Uh,TableTransformerPreTrainedModel:()=>Cc,TrOCRForCausalLM:()=>iN,TrOCRPreTrainedModel:()=>Wh,UltravoxModel:()=>x_,UltravoxPreTrainedModel:()=>_h,UniSpeechForCTC:()=>HN,UniSpeechForSequenceClassification:()=>_N,UniSpeechModel:()=>oN,UniSpeechPreTrainedModel:()=>wi,UniSpeechSatForAudioFrameClassification:()=>dN,UniSpeechSatForCTC:()=>lN,UniSpeechSatForSequenceClassification:()=>uN,UniSpeechSatModel:()=>cN,UniSpeechSatPreTrainedModel:()=>Ts,VaultGemmaForCausalLM:()=>hN,VaultGemmaModel:()=>pN,VaultGemmaPreTrainedModel:()=>wc,ViTForImageClassification:()=>$N,ViTMAEModel:()=>mN,ViTMAEPreTrainedModel:()=>Kh,ViTMSNForImageClassification:()=>SN,ViTMSNModel:()=>IN,ViTMSNPreTrainedModel:()=>Bc,ViTModel:()=>EN,ViTPreTrainedModel:()=>Nc,VisionEncoderDecoderModel:()=>fN,VitMatteForImageMatting:()=>LN,VitMattePreTrainedModel:()=>Vh,VitPoseForPoseEstimation:()=>AN,VitPosePreTrainedModel:()=>jh,VitsModel:()=>gN,VitsModelOutput:()=>qh,VitsPreTrainedModel:()=>Xh,VoxtralForConditionalGeneration:()=>bN,VoxtralRealtimeForConditionalGeneration:()=>Jh,VoxtralRealtimePreTrainedModel:()=>zh,Wav2Vec2BertForCTC:()=>xN,Wav2Vec2BertForSequenceClassification:()=>vN,Wav2Vec2BertModel:()=>TN,Wav2Vec2BertPreTrainedModel:()=>Ni,Wav2Vec2ForAudioFrameClassification:()=>xy,Wav2Vec2ForCTC:()=>by,Wav2Vec2ForSequenceClassification:()=>Ty,Wav2Vec2Model:()=>gy,Wav2Vec2PreTrainedModel:()=>ua,WavLMForAudioFrameClassification:()=>NN,WavLMForCTC:()=>DN,WavLMForSequenceClassification:()=>CN,WavLMForXVector:()=>wN,WavLMModel:()=>yN,WavLMPreTrainedModel:()=>Ln,WeSpeakerResNetModel:()=>BN,WeSpeakerResNetPreTrainedModel:()=>Yh,WhisperForConditionalGeneration:()=>ef,WhisperModel:()=>MN,WhisperPreTrainedModel:()=>Mc,XLMForQuestionAnswering:()=>FN,XLMForSequenceClassification:()=>ON,XLMForTokenClassification:()=>GN,XLMModel:()=>kN,XLMPreTrainedModel:()=>An,XLMRobertaForMaskedLM:()=>UN,XLMRobertaForQuestionAnswering:()=>VN,XLMRobertaForSequenceClassification:()=>WN,XLMRobertaForTokenClassification:()=>KN,XLMRobertaModel:()=>ZN,XLMRobertaPreTrainedModel:()=>gn,XLMWithLMHeadModel:()=>RN,XVectorOutput:()=>Qh,YolosForObjectDetection:()=>qN,YolosModel:()=>jN,YolosObjectDetectionOutput:()=>tf,YolosPreTrainedModel:()=>Pc,YoutuForCausalLM:()=>zN,YoutuModel:()=>XN,YoutuPreTrainedModel:()=>kc});$s=class extends C{},LT=class extends $s{},AT=class extends $s{async _call(e){return new de(await super._call(e))}},gT=class extends $s{async _call(e){return new Nt(await super._call(e))}},bT=class extends $s{async _call(e){return new pt(await super._call(e))}},PH=class extends C{},TT=class extends PH{},xT=class extends PH{},kH=class extends C{},vT=class extends kH{},yT=class extends kH{},RH=class extends C{},DT=class extends RH{},CT=class extends RH{},OH=class extends C{},wT=class extends OH{},NT=class extends OH{},fi=class extends C{},BT=class extends fi{},MT=class extends fi{},PT=class extends fi{async _call(e){return new de(await super._call(e))}},GH=class extends C{},kT=class extends GH{},RT=class extends GH{async _call(e){return new de(await super._call(e))}},ln=class extends C{},OT=class extends ln{},GT=class extends ln{async _call(e){return new pt(await super._call(e))}},FT=class extends ln{async _call(e){return new de(await super._call(e))}},ZT=class extends ln{async _call(e){return new ot(await super._call(e))}},UT=class extends ln{async _call(e){return new Nt(await super._call(e))}},FH=class extends C{},WT=class extends FH{},KT=class extends FH{},ZH=class extends C{},VT=class extends ZH{},jT=class extends ZH{},UH=class extends C{},qT=class extends UH{},XT=class extends UH{},un=class extends C{},zT=class extends un{},JT=class extends un{async _call(e){return new pt(await super._call(e))}},QT=class extends un{async _call(e){return new de(await super._call(e))}},YT=class extends un{async _call(e){return new ot(await super._call(e))}},ex=class extends un{async _call(e){return new Nt(await super._call(e))}},H7=4299n,DS=6561n,kp=class extends C{forward_params=["input_ids","inputs_embeds","attention_mask","position_ids","audio_values","exaggeration","audio_features","audio_tokens","speaker_embeddings","speaker_features","past_key_values"];main_input_name="input_ids";_return_dict_in_generate_keys=["audio_tokens","speaker_embeddings","speaker_features"]},Rp=class extends kp{async encode_speech(e){return xe(this.sessions.speech_encoder,{audio_values:e})}async forward({input_ids:e=null,attention_mask:t=null,audio_values:r=null,exaggeration:a=null,position_ids:n=null,inputs_embeds:s=null,past_key_values:i=null,generation_config:o=null,logits_processor:H=null,audio_features:_=null,audio_tokens:c=null,speaker_embeddings:l=null,speaker_features:d=null,...h}){let $;if(!s){let S=this.sessions.embed_tokens.inputNames,I={input_ids:e};if(S.includes("exaggeration")){if(!(a instanceof j)){let g=e.dims[0];if(a==null)a=xt([g],.5);else if(typeof a=="number")a=xt([g],a);else if(Array.isArray(a))a=new j("float32",a,[g]);else throw new Error("Unsupported type for `exaggeration` input")}I.exaggeration=a}if(S.includes("position_ids")&&(I.position_ids=n),{inputs_embeds:s}=await xe(this.sessions.embed_tokens,I),_&&c&&l&&d&&($={audio_features:_,audio_tokens:c,speaker_embeddings:l,speaker_features:d}),$||r)$??=await this.encode_speech(r),s=Ue([$.audio_features,s],1),t=Kt([s.dims[0],s.dims[1]]);else{let g=s.dims[1];if(!i||g!==1)throw new Error("Incorrect state encountered during generation.");let T=i.get_seq_length();t=Kt([s.dims[0],T+g])}}return{...await _a(this,{inputs_embeds:s,past_key_values:i,attention_mask:t,generation_config:o,logits_processor:H},!1),...$}}prepare_inputs_for_generation(e,t,r){if(!t.position_ids&&this.sessions.embed_tokens.inputNames.includes("position_ids"))if(t.input_ids.dims[1]===1){let a=Array.from({length:e.length},(n,s)=>e[s].length-e[s].findLastIndex(i=>i==DS)-1);t.position_ids=new j("int64",a,[e.length,1])}else{let n=t.input_ids.tolist().map(s=>{let i=0;return s.map(o=>o>=DS?0:i++)});t.position_ids=new j("int64",n.flat(),t.input_ids.dims)}return t.input_ids.dims[1]===1&&(delete t.audio_values,delete t.audio_features,delete t.audio_tokens,delete t.speaker_embeddings,delete t.speaker_features),ni(this,e,t,r)}async generate(e){let{sequences:t,audio_tokens:r,speaker_embeddings:a,speaker_features:n}=await super.generate({...e,return_dict_in_generate:!0}),s=t.slice(null,[e.input_ids.dims[1],-1]),i=xt([s.dims[0],3],H7),o=Ue([r,s,i],1),{waveform:H}=await xe(this.sessions.conditional_decoder,{speech_tokens:o,speaker_features:n,speaker_embeddings:a});return H}},Op=class extends C{},tx=class extends Op{},Gp=class extends C{},rx=class extends Gp{},Ei=class extends C{},ax=class extends Ei{},Fp=class extends Ei{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},Zp=class extends Ei{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"audio_model"})}},Ca=class extends C{},nx=class extends Ca{},sx=class extends Ca{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},Up=class extends Ca{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},ix=class extends Ca{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},ox=class extends Ca{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},WH=class extends C{},Hx=class extends WH{},_x=class extends WH{},KH=class extends C{},cx=class extends KH{},lx=class extends KH{},VH=class extends C{},ux=class extends VH{},dx=class extends VH{},jH=class extends C{},px=class extends jH{},hx=class extends jH{},qH=class extends C{requires_attention_mask=!1;main_input_name="input_features";forward_params=["input_features","decoder_input_ids","decoder_attention_mask","past_key_values"]},fx=class extends qH{},Ex=class extends qH{},dn=class extends C{},$x=class extends dn{},mx=class extends dn{async _call(e){return new pt(await super._call(e))}},Ix=class extends dn{async _call(e){return new de(await super._call(e))}},Sx=class extends dn{async _call(e){return new ot(await super._call(e))}},Lx=class extends dn{async _call(e){return new Nt(await super._call(e))}},XH=class extends C{},Ax=class extends XH{},gx=class extends XH{async _call(e){return new de(await super._call(e))}},zH=class extends C{},bx=class extends zH{},Tx=class extends zH{async _call(e){return new de(await super._call(e))}},JH=class extends C{},xx=class extends JH{},vx=class extends JH{async _call(e){return new ms(await super._call(e))}},ms=class extends dt{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},QH=class extends C{},yx=class extends QH{},Dx=class extends QH{async _call(e){return new ms(await super._call(e))}},Wp=class extends dt{constructor({audio_codes:e}){super(),this.audio_codes=e}},Kp=class extends dt{constructor({audio_values:e}){super(),this.audio_values=e}},$i=class extends C{main_input_name="input_values";forward_params=["input_values"]},Cx=class extends $i{async encode(e){return new Wp(await xe(this.sessions.encoder_model,e))}async decode(e){return new Kp(await xe(this.sessions.decoder_model,e))}},Vp=class extends $i{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"encoder_model"})}},jp=class extends $i{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"decoder_model"})}},pn=class extends C{},wx=class extends pn{},Nx=class extends pn{async _call(e){return new pt(await super._call(e))}},Bx=class extends pn{async _call(e){return new de(await super._call(e))}},Mx=class extends pn{async _call(e){return new ot(await super._call(e))}},Px=class extends pn{async _call(e){return new Nt(await super._call(e))}},YH=class extends C{},kx=class extends YH{},Rx=class extends YH{},hn=class extends C{},Ox=class extends hn{},Gx=class extends hn{async _call(e){return new pt(await super._call(e))}},Fx=class extends hn{async _call(e){return new de(await super._call(e))}},Zx=class extends hn{async _call(e){return new ot(await super._call(e))}},Ux=class extends hn{async _call(e){return new Nt(await super._call(e))}},qp=class extends C{},Wx=class extends qp{},e_=class extends C{},Kx=class extends e_{},Vx=class extends e_{async _call(e){return new de(await super._call(e))}},Xp=class extends C{},jx=class extends Xp{},zp=class extends C{},qx=class extends zp{},mi=class extends C{},Xx=class extends mi{},zx=class extends mi{async _call(e){return new t_(await super._call(e))}},Jx=class extends mi{async _call(e){return new Jp(await super._call(e))}},t_=class extends dt{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},Jp=class extends dt{constructor({logits:e,pred_boxes:t,pred_masks:r}){super(),this.logits=e,this.pred_boxes=t,this.pred_masks=r}},r_=class extends C{},Qx=class extends r_{},Yx=class extends r_{async _call(e){return new de(await super._call(e))}},a_=class extends C{},ev=class extends a_{},tv=class extends a_{async _call(e){return new de(await super._call(e))}},Qp=class extends C{},rv=class extends Qp{},Yp=class extends C{},av=class extends Yp{},fn=class extends C{},nv=class extends fn{},sv=class extends fn{async _call(e){return new de(await super._call(e))}},iv=class extends fn{async _call(e){return new ot(await super._call(e))}},ov=class extends fn{async _call(e){return new Nt(await super._call(e))}},Hv=class extends fn{async _call(e){return new pt(await super._call(e))}},eh=class extends C{},_v=class extends eh{},n_=class extends C{},cv=class extends n_{},lv=class extends n_{},s_=class extends C{},uv=class extends s_{},dv=class extends s_{async _call(e){return new de(await super._call(e))}},En=class extends C{},pv=class extends En{},hv=class extends En{async _call(e){return new pt(await super._call(e))}},fv=class extends En{async _call(e){return new de(await super._call(e))}},Ev=class extends En{async _call(e){return new ot(await super._call(e))}},$v=class extends En{async _call(e){return new Nt(await super._call(e))}},i_=class extends C{},mv=class extends i_{},Iv=class extends i_{},Is=class extends C{},Sv=class extends Is{},Lv=class extends Is{async _call(e){return new pt(await super._call(e))}},Av=class extends Is{async _call(e){return new de(await super._call(e))}},gv=class extends Is{async _call(e){return new ot(await super._call(e))}},Ss=class extends C{},bv=class extends Ss{},Tv=class extends Ss{async _call(e){return new pt(await super._call(e))}},xv=class extends Ss{async _call(e){return new de(await super._call(e))}},vv=class extends Ss{async _call(e){return new ot(await super._call(e))}},o_=class extends C{},yv=class extends o_{},Dv=class extends o_{},H_=class extends C{},Cv=class extends H_{},wv=class extends H_{},__=class extends C{},Nv=class extends __{},Bv=class extends __{},c_=class extends C{},Mv=class extends c_{},Pv=class extends c_{async _call(e){return new de(await super._call(e))}},th=class extends C{forward_params=["input_ids","inputs_embeds","attention_mask","pixel_values","encoder_outputs","decoder_input_ids","decoder_inputs_embeds","decoder_attention_mask","past_key_values"];main_input_name="inputs_embeds"},kv=class extends th{_merge_input_ids_with_image_features({inputs_embeds:e,image_features:t,input_ids:r,attention_mask:a}){return{inputs_embeds:Ue([t,e],1),attention_mask:Ue([Kt(t.dims.slice(0,2)),a],1)}}async _prepare_inputs_embeds({input_ids:e,pixel_values:t,inputs_embeds:r,attention_mask:a}){if(!e&&!t)throw new Error("Either `input_ids` or `pixel_values` should be provided.");let n,s;return e&&(n=await this.encode_text({input_ids:e})),t&&(s=await this.encode_image({pixel_values:t})),n&&s?{inputs_embeds:r,attention_mask:a}=this._merge_input_ids_with_image_features({inputs_embeds:n,image_features:s,input_ids:e,attention_mask:a}):r=n||s,{inputs_embeds:r,attention_mask:a}}async forward({input_ids:e,pixel_values:t,attention_mask:r,decoder_input_ids:a,decoder_attention_mask:n,encoder_outputs:s,past_key_values:i,inputs_embeds:o,decoder_inputs_embeds:H}){if(o||({inputs_embeds:o,attention_mask:r}=await this._prepare_inputs_embeds({input_ids:e,pixel_values:t,inputs_embeds:o,attention_mask:r})),!s){let{last_hidden_state:c}=await Da(this,{inputs_embeds:o,attention_mask:r});s=c}if(!H){if(!a)throw new Error("Either `decoder_input_ids` or `decoder_inputs_embeds` should be provided.");H=await this.encode_text({input_ids:a})}return await _a(this,{inputs_embeds:H,attention_mask:n,encoder_attention_mask:r,encoder_hidden_states:s,past_key_values:i},!0)}},l_=class extends C{},Rv=class extends l_{},Ov=class extends l_{},u_=class extends C{},Gv=class extends u_{},Fv=class extends u_{},rh=class extends C{forward_params=["input_ids","attention_mask","pixel_values","position_ids","past_key_values"]},Kr=class extends rh{_merge_input_ids_with_image_features(e){let t=e.image_features.dims.at(-1),r=e.image_features.view(-1,t);return Mp({image_token_id:this.config.image_token_index??this.config.image_token_id,...e,image_features:r})}},Zv=class extends Kr{},Uv=class extends Kr{},ah=class extends C{},Wv=class extends ah{},nh=class extends Kr{},Kv=class extends nh{},sh=class extends C{forward_params=["input_ids","attention_mask","inputs_embeds","per_layer_inputs","position_ids","pixel_values","input_features","input_features_mask","past_key_values"]},Ii=class extends sh{async forward({input_ids:e=null,attention_mask:t=null,pixel_values:r=null,input_features:a=null,input_features_mask:n=null,position_ids:s=null,inputs_embeds:i=null,per_layer_inputs:o=null,past_key_values:H=null,generation_config:_=null,logits_processor:c=null,...l}){if((!i||!o)&&({inputs_embeds:i,per_layer_inputs:o}=await xe(this.sessions.embed_tokens,{input_ids:e}),e.dims[1]!==1)){if(r){let{image_features:h}=await this._encode_vision({pixel_values:r,...l});({inputs_embeds:i,attention_mask:t}=this._merge_input_ids_with_image_features({image_features:h,inputs_embeds:i,input_ids:e,attention_mask:t}))}if(a){let{audio_features:h}=await xe(this.sessions.audio_encoder,{input_features:a,input_features_mask:n});({inputs_embeds:i,attention_mask:t}=this._merge_input_ids_with_audio_features({audio_features:h,inputs_embeds:i,input_ids:e,attention_mask:t}))}}return await _a(this,{inputs_embeds:i,per_layer_inputs:o,past_key_values:H,attention_mask:t,position_ids:s,generation_config:_,logits_processor:c},!0)}_encode_vision(e){return xe(this.sessions.vision_encoder,{pixel_values:e.pixel_values})}_merge_input_ids_with_image_features(e){let t=e.image_features.dims.at(-1),r=e.image_features.view(-1,t);return Mp({image_token_id:this.config.image_token_id,...e,image_features:r})}_merge_input_ids_with_audio_features(e){let t=e.audio_features.dims.at(-1),r=e.audio_features.view(-1,t);return ST({audio_token_id:this.config.audio_token_id,...e,audio_features:r})}},Vv=class extends Ii{},d_=class extends Ii{forward_params=["input_ids","attention_mask","inputs_embeds","per_layer_inputs","position_ids","pixel_values","image_position_ids","input_features","input_features_mask","past_key_values"];_encode_vision(e){return xe(this.sessions.vision_encoder,{pixel_values:e.pixel_values,pixel_position_ids:e.image_position_ids})}},jv=class extends d_{},p_=class extends C{},qv=class extends p_{},Xv=class extends p_{},h_=class extends C{},zv=class extends h_{},Jv=class extends h_{},ih=class extends C{forward_params=["input_ids","attention_mask","position_ids","past_key_values","pixel_values","image_grid_thw"]},f_=class extends ih{image_grid_thw_name="grid_thw";_get_text_only_rope_index(e,t){if(t){let{data:r,dims:a}=mT(t),n=BigInt64Array.from({length:3*r.length},(i,o)=>r[o%r.length]),s=Array.from({length:a[0]},(i,o)=>nt(r.subarray(a[1]*o,a[1]*(o+1)))[0]+1n+BigInt(a[1]));return[new j("int64",n,[3,...a]),new j("int64",s,[s.length,1])]}else{let[r,a]=e.dims,n=BigInt64Array.from({length:3*r*a},(s,i)=>BigInt(Math.floor(i%a/r)));return[new j("int64",n,[3,...e.dims]),qd([r,1])]}}_reorder_and_write_positions(e,t,r,a){let n=e.reduce((H,_)=>H+_.length,0),s=new Array(n),i=0;for(let H=0;H<3;++H)for(let _ of e){let c=_.length/3;for(let l=H*c;l<(H+1)*c;++l)s[i++]=_[l]}let o=0;for(let H=0;H<t.length;++H)if(t[H]==1){for(let _=0;_<3;++_)r[_][a][H]=s[_*n/3+o];++o}return s}_get_multimodal_rope_positions({filtered_ids:e,image_grid_thw_list:t,video_grid_thw_list:r,spatial_merge_size:a,state:n}){let{image_token_id:s,video_token_id:i,vision_start_token_id:o}=this.config,H=e,c=H.reduce((I,g,T)=>(g==o&&I.push(T),I),[]).map(I=>H[I+1]),l=c.filter(I=>I==s).length,d=c.filter(I=>I==i).length,h=[],$=0,m=l,S=d;for(let I=0;I<c.length;++I){let g=H.findIndex((U,Y)=>Y>$&&U==s),T=H.findIndex((U,Y)=>Y>$&&U==i),x=m>0&&g!==-1?g:H.length+1,v=S>0&&T!==-1?T:H.length+1,k,L,V,K;x<v?([L,V,K]=t[n.image_index],++n.image_index,--m,k=x):([L,V,K]=r[n.video_index],++n.video_index,--S,k=v);let[X,Q,z]=[Number(L),Math.floor(Number(V)/a),Math.floor(Number(K)/a)],M=k-$,F=h.length>0?nt(h.at(-1))[0]+1:0;h.push(Array.from({length:3*M},(U,Y)=>F+Y%M));let N=M+F,G=X*Q*z,te=Array.from({length:G},(U,Y)=>N+Math.floor(Y/(Q*z))),B=Array.from({length:G},(U,Y)=>N+Math.floor(Y/z)%Q),O=Array.from({length:G},(U,Y)=>N+Y%z);h.push([te,B,O].flat()),$=k+G}if($<H.length){let I=h.length>0?nt(h.at(-1))[0]+1:0,g=H.length-$;h.push(Array.from({length:3*g},(T,x)=>I+x%g))}return h}get_rope_index(e,t,r,a){let{vision_config:n}=this.config,s=n.spatial_merge_size??2;if(t||r){let i=e.tolist();a||(a=jd(e));let o=a.tolist(),H=Array.from({length:3},()=>Array.from({length:e.dims[0]},()=>Array.from({length:e.dims[1]},()=>0))),_=t?t.tolist():[],c=r?r.tolist():[],l={image_index:0,video_index:0},d=[];for(let h=0;h<i.length;++h){let $=i[h].filter((I,g)=>o[h][g]==1),m=this._get_multimodal_rope_positions({filtered_ids:$,image_grid_thw_list:_,video_grid_thw_list:c,spatial_merge_size:s,state:l}),S=this._reorder_and_write_positions(m,o[h],H,h);d.push(nt(S)[0]+1-i[h].length)}return[new j("int64",H.flat(1/0),[3,e.dims[0],e.dims[1]]),new j("int64",d,[d.length,1])]}else return this._get_text_only_rope_index(e,a)}async encode_image({pixel_values:e,image_grid_thw:t}){return(await xe(this.sessions.vision_encoder,{pixel_values:e,[this.image_grid_thw_name]:t})).image_features}_merge_input_ids_with_image_features(e){return Mp({image_token_id:this.config.image_token_id,...e})}prepare_inputs_for_generation(e,t,r){if(!t.attention_mask||t.position_ids||!(this.sessions.decoder_model_merged??this.sessions.model).inputNames.includes("position_ids"))return t;if(!t.past_key_values)[t.position_ids,t.rope_deltas]=this.get_rope_index(t.input_ids,t.image_grid_thw,t.video_grid_thw,t.attention_mask);else{t.pixel_values=null;let n=t.past_key_values.get_seq_length();if(n<t.input_ids.dims[1]){let[s,i]=this.get_rope_index(t.input_ids,t.image_grid_thw,t.video_grid_thw,t.attention_mask);t.rope_deltas=i,t.position_ids=s.slice(null,null,[n,null]),t.input_ids=t.input_ids.slice(null,[n,null])}else{t.rope_deltas||([,t.rope_deltas]=this.get_rope_index(t.input_ids,t.image_grid_thw,t.video_grid_thw,t.attention_mask));let s=BigInt(n),i=t.rope_deltas.map(o=>s+o);t.position_ids=Ur([i,i,i],0)}}return t}},oh=class extends f_{},E_=class extends f_{image_grid_thw_name="image_grid_thw"},Hh=class extends oh{image_grid_thw_name="image_grid_thw"},Qv=class extends E_{get_vision_position_ids(e,t,r,a){let n=Math.floor(t[0]/r),s=Math.floor(t[1]/a),i=Math.floor(t[2]/a),o=s*i*n,H=Array.from({length:o},()=>e),_=Array.from({length:o},(l,d)=>e+Math.floor(d/(i*n))),c=Array.from({length:o},(l,d)=>e+d%i);return[...H,..._,...c]}_get_multimodal_rope_positions({filtered_ids:e,image_grid_thw_list:t,video_grid_thw_list:r,spatial_merge_size:a,state:n}){let{image_token_id:s}=this.config,i=[],o=0,H=e[0]==s?1:0;for(let l=1;l<=e.length;++l){let d=l<e.length?e[l]==s?1:0:-1;d!==H&&(i.push([H,o,l]),o=l,H=d)}let _=0,c=[];for(let[l,d,h]of i)if(l===0){let $=h-d;c.push(Array.from({length:3*$},(m,S)=>_+S%$)),_+=$}else{let $=t[n.image_index++].map(Number),m=$[0];c.push(this.get_vision_position_ids(_,$,m,a)),_+=Math.max($[1],$[2])/a}return c}},$_=class extends C{},Yv=class extends $_{},ey=class extends $_{},m_=class extends C{},ty=class extends m_{},ry=class extends m_{},I_=class extends C{},ay=class extends I_{},ny=class extends I_{},S_=class extends C{},sy=class extends S_{},iy=class extends S_{},L_=class extends C{},oy=class extends L_{},Hy=class extends L_{},A_=class extends C{},_y=class extends A_{},cy=class extends A_{},g_=class extends C{},ly=class extends g_{},uy=class extends g_{},b_=class extends C{},dy=class extends b_{},py=class extends b_{},T_=class extends C{},hy=class extends T_{},fy=class extends T_{},_h=class extends C{forward_params=["input_ids","attention_mask","position_ids","audio_values","past_key_values"]},x_=class extends _h{_merge_input_ids_with_audio_features(e){let t=e.audio_features.dims.at(-1),r=e.audio_features.view(-1,t);return ST({audio_token_id:this.config.ignore_index??this.config.audio_token_id??this.config.audio_token_index,...e,audio_features:r})}},Ey=class extends x_{forward_params=["input_ids","attention_mask","input_features","past_key_values"]},ch=class extends C{},$y=class extends ch{},lh=class extends C{},my=class extends lh{},v_=class extends C{},Iy=class extends v_{},Sy=class extends v_{},y_=class extends C{},Ly=class extends y_{},Ay=class extends y_{async _call(e){return new de(await super._call(e))}},ua=class extends C{},gy=class extends ua{},by=class extends ua{async _call(e){return new cn(await super._call(e))}},Ty=class extends ua{async _call(e){return new de(await super._call(e))}},xy=class extends ua{async _call(e){return new ot(await super._call(e))}},vy=class extends C{},yy=class extends ua{},Dy=class extends ua{async _call(e){return new cn(await super._call(e))}},Cy=class extends ua{async _call(e){return new de(await super._call(e))}},D_=class extends C{},wy=class extends D_{},Ny=class extends D_{},uh=class extends Kr{forward_params=["input_ids","attention_mask","pixel_values","pixel_attention_mask","position_ids","past_key_values"]},C_=class extends C{},By=class extends C_{},My=class extends C_{async _call(e){return new de(await super._call(e))}},w_=class extends C{},Py=class extends w_{},ky=class extends w_{},Si=class extends C{},Ry=class extends Si{async forward(e){let t=!e.input_ids,r=!e.pixel_values;if(t&&r)throw new Error("Either `input_ids` or `pixel_values` should be provided.");if(t&&(e.input_ids=Kt([e.pixel_values.dims[0],1])),r){let{image_size:H}=this.config.vision_config;e.pixel_values=xt([0,3,H,H],0)}let{text_embeddings:a,image_embeddings:n,l2norm_text_embeddings:s,l2norm_image_embeddings:i}=await super.forward(e),o={};return t||(o.text_embeddings=a,o.l2norm_text_embeddings=s),r||(o.image_embeddings=n,o.l2norm_image_embeddings=i),o}},dh=class extends Si{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},Oy=class extends Si{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},N_=class extends C{},Gy=class extends N_{},Fy=class extends N_{},Zy=class extends Kr{},B_=class extends C{},Uy=class extends B_{},Wy=class extends B_{},Ky=class extends Kr{forward_params=["input_ids","attention_mask","pixel_values","pixel_attention_mask","spatial_shapes","position_ids","past_key_values"]},M_=class extends C{},Vy=class extends M_{},jy=class extends M_{},ph=class extends C{},qy=class extends ph{},P_=class extends C{},Xy=class extends P_{},zy=class extends P_{},k_=class extends C{},Jy=class extends k_{},Qy=class extends k_{},R_=class extends C{},Yy=class extends R_{},eD=class extends R_{},O_=class extends C{},tD=class extends O_{},rD=class extends O_{},Ls=class extends C{},aD=class extends Ls{},nD=class extends Ls{},sD=class extends Ls{async _call(e){return new de(await super._call(e))}},iD=class extends Ls{},hh=class extends C{},oD=class extends hh{},fh=class extends C{},HD=class extends fh{},Eh=class extends dt{constructor({char_logits:e,bpe_logits:t,wp_logits:r}){super(),this.char_logits=e,this.bpe_logits=t,this.wp_logits=r}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}},$h=class extends C{},_D=class extends $h{async _call(e){return new Eh(await super._call(e))}},mh=class extends dt{constructor({audio_codes:e}){super(),this.audio_codes=e}},Ih=class extends dt{constructor({audio_values:e}){super(),this.audio_values=e}},Li=class extends C{main_input_name="input_values";forward_params=["input_values"]},cD=class extends Li{async encode(e){return new mh(await xe(this.sessions.encoder_model,e))}async decode(e){return new Ih(await xe(this.sessions.decoder_model,e))}},Sh=class extends Li{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"encoder_model"})}},Lh=class extends Li{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"decoder_model"})}},G_=class extends C{},lD=class extends G_{},uD=class extends G_{},F_=class extends C{},dD=class extends F_{},pD=class extends F_{},As=class extends C{},hD=class extends As{},fD=class extends As{async _call(e){return new pt(await super._call(e))}},ED=class extends As{async _call(e){return new de(await super._call(e))}},$D=class extends As{async _call(e){return new Nt(await super._call(e))}},Z_=class extends C{},mD=class extends Z_{},ID=class extends Z_{},Ai=class extends C{},SD=class extends Ai{},LD=class extends Ai{async _call(e){return new de(await super._call(e))}},AD=class extends Ai{},gi=class extends C{},gD=class extends gi{},bD=class extends gi{async _call(e){return new de(await super._call(e))}},TD=class extends gi{},bi=class extends C{},xD=class extends bi{},vD=class extends bi{async _call(e){return new de(await super._call(e))}},yD=class extends bi{},Ti=class extends C{},DD=class extends Ti{},CD=class extends Ti{async _call(e){return new de(await super._call(e))}},wD=class extends Ti{},U_=class extends C{},ND=class extends U_{},BD=class extends U_{async _call(e){return new de(await super._call(e))}},W_=class extends C{},MD=class extends W_{},PD=class extends W_{async _call(e){return new de(await super._call(e))}},gs=class extends C{},kD=class extends gs{},RD=class extends gs{async _call(e){return new pt(await super._call(e))}},OD=class extends gs{async _call(e){return new de(await super._call(e))}},GD=class extends gs{async _call(e){return new ot(await super._call(e))}},K_=class extends C{},FD=class extends K_{},ZD=class extends K_{},V_=class extends C{requires_attention_mask=!1;main_input_name="input_values";forward_params=["input_values","decoder_input_ids","past_key_values"]},UD=class extends V_{},WD=class extends V_{},$n=class extends C{},KD=class extends $n{},VD=class extends $n{async _call(e){return new pt(await super._call(e))}},jD=class extends $n{async _call(e){return new de(await super._call(e))}},qD=class extends $n{async _call(e){return new ot(await super._call(e))}},XD=class extends $n{async _call(e){return new Nt(await super._call(e))}},j_=class extends C{},zD=class extends j_{},JD=class extends j_{},q_=class extends C{},QD=class extends q_{},YD=class extends q_{},Ah=class extends C{},eC=class extends Ah{forward_params=["input_ids","pixel_values","images_seq_mask","images_emb_mask","attention_mask","position_ids","past_key_values"];constructor(...e){super(...e),this._generation_mode="text"}async forward(e){let t=this._generation_mode??"text",r;if(t==="text"||!e.past_key_values){let o=this.sessions.prepare_inputs_embeds,H=It(e,o.inputNames);r=await xe(o,H)}else{let o=this.sessions.gen_img_embeds,H=It({image_ids:e.input_ids},o.inputNames);r=await xe(o,H)}let a={...e,...r},n=await _a(this,a),s=this.sessions[t==="text"?"lm_head":"gen_head"];if(!s)throw new Error(`Unable to find "${s}" generation head`);let i=await xe(s,It(n,s.inputNames));return{...r,...n,...i}}prepare_inputs_for_generation(e,t,r){let a=!!t.past_key_values;return r.guidance_scale!==null&&r.guidance_scale>1&&(a?t.input_ids=Ue([t.input_ids,t.input_ids],0):(t.input_ids=Ue([t.input_ids,dH(t.input_ids,BigInt(r.pad_token_id))],0),t.attention_mask=Ue([t.attention_mask,dH(t.attention_mask,0n)],0))),(a||!t.pixel_values)&&(t.pixel_values=xt([0,0,3,384,384],1)),a&&(t.images_seq_mask=new j("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),t.images_emb_mask=new j("bool",new Array(0).fill(!1),[1,1,0])),t}async generate(e){return this._generation_mode="text",super.generate(e)}async generate_images(e){this._generation_mode="image";let t=(e.inputs??e[this.main_input_name]).dims[1],a=(await super.generate(e)).slice(null,[t,null]),n=this.sessions.image_decode,{decoded_image:s}=await xe(n,{generated_tokens:a}),i=s.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),o=[];for(let H of i){let _=Xt.fromTensor(H);o.push(_)}return o}},X_=class extends C{},tC=class extends X_{},rC=class extends X_{},gh=class extends C{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"];_apply_and_filter_by_delay_pattern_mask(e){let[t,r]=e.dims,a=this.config.decoder.num_codebooks,n=r-a,s=0;for(let H=0;H<e.size;++H){if(e.data[H]==this.config.decoder.pad_token_id)continue;let _=H%r,c=Math.floor(H/r)%a,l=_-c;l>0&&l<=n&&(e.data[s++]=e.data[H])}let i=Math.floor(t/a),o=s/(i*a);return new j(e.type,e.data.slice(0,s),[i,a,o])}prepare_inputs_for_generation(e,t,r){let a=BigInt(this.config.decoder.pad_token_id),n=structuredClone(e);for(let s=0;s<n.length;++s)for(let i=0;i<n[s].length;++i)s%this.config.decoder.num_codebooks>=i&&(n[s][i]=a);return r.guidance_scale!==null&&r.guidance_scale>1&&(n=n.concat(n)),$H(this,n,t,r)}async generate(e){let t=await super.generate(e),r=this._apply_and_filter_by_delay_pattern_mask(t).unsqueeze_(0),{audio_values:a}=await xe(this.sessions.encodec_decode,{audio_codes:r});return a}},z_=class extends C{},aC=class extends z_{},nC=class extends z_{},J_=class extends C{},sC=class extends J_{},iC=class extends J_{},mn=class extends C{},oC=class extends mn{},HC=class extends mn{async _call(e){return new pt(await super._call(e))}},_C=class extends mn{async _call(e){return new de(await super._call(e))}},cC=class extends mn{async _call(e){return new ot(await super._call(e))}},lC=class extends mn{async _call(e){return new Nt(await super._call(e))}},bh=class extends C{},uC=class extends bh{},Q_=class extends C{},dC=class extends Q_{},pC=class extends Q_{},Y_=class extends C{},hC=class extends Y_{},fC=class extends Y_{},ec=class extends C{},EC=class extends ec{},$C=class extends ec{},tc=class extends C{},mC=class extends tc{},IC=class extends tc{},rc=class extends C{},SC=class extends rc{},LC=class extends rc{async _call(e){return new de(await super._call(e))}},ac=class extends C{},AC=class extends ac{},gC=class extends ac{},nc=class extends C{},bC=class extends nc{},TC=class extends nc{},sc=class extends C{},xC=class extends sc{},vC=class extends sc{},ic=class extends C{},yC=class extends ic{},DC=class extends ic{},CC=class extends Kr{},Th=class extends C{},wC=class extends Th{async _call(e){return new cn(await super._call(e))}},oc=class extends C{},NC=class extends oc{},BC=class extends oc{},Hc=class extends C{},MC=class extends Hc{},PC=class extends Hc{},_c=class extends C{},kC=class extends _c{},RC=class extends _c{},cc=class extends C{},OC=class extends cc{},GC=class extends cc{},xh=class extends C{forward_params=["input_ids","inputs_embeds","attention_mask","position_ids","pixel_values","image_sizes","past_key_values"]},vh=class extends xh{async forward({input_ids:e=null,attention_mask:t=null,pixel_values:r=null,image_sizes:a=null,position_ids:n=null,inputs_embeds:s=null,past_key_values:i=null,generation_config:o=null,logits_processor:H=null,..._}){if(!s){let l;if(r&&e.dims[1]!==1){if(!a)throw new Error("`image_sizes` must be provided when `pixel_values` is provided.");({image_features:l}=await xe(this.sessions.vision_encoder,{pixel_values:r,image_sizes:a}))}else{let d=this.config.normalized_config.hidden_size;l=new j("float32",[],[0,d])}({inputs_embeds:s}=await xe(this.sessions.prepare_inputs_embeds,{input_ids:e,image_features:l}))}return await _a(this,{inputs_embeds:s,past_key_values:i,attention_mask:t,position_ids:n,generation_config:o,logits_processor:H},!1)}},lc=class extends C{},FC=class extends lc{},ZC=class extends lc{async _call(e){return new de(await super._call(e))}},uc=class extends C{},UC=class extends uc{},WC=class extends uc{async _call(e){return new ot(await super._call(e))}},dc=class extends C{},KC=class extends dc{},VC=class extends dc{},pc=class extends C{},jC=class extends pc{},qC=class extends pc{},hc=class extends C{},XC=class extends hc{},zC=class extends hc{},fc=class extends C{},JC=class extends fc{},QC=class extends fc{},Ec=class extends C{},YC=class extends Ec{},ew=class extends Ec{},$c=class extends E_{},yh=class extends Hh{},tw=class extends $c{},rw=class extends yh{},mc=class extends $c{},Dh=class extends mc{},aw=class extends mc{},nw=class extends Dh{},Ic=class extends C{},sw=class extends Ic{},iw=class extends Ic{async _call(e){return new de(await super._call(e))}},Sc=class extends C{},ow=class extends Sc{},Hw=class extends Sc{async _call(e){return new Ch(await super._call(e))}},Ch=class extends ms{},In=class extends C{},_w=class extends In{},cw=class extends In{async _call(e){return new pt(await super._call(e))}},lw=class extends In{async _call(e){return new de(await super._call(e))}},uw=class extends In{async _call(e){return new ot(await super._call(e))}},dw=class extends In{async _call(e){return new Nt(await super._call(e))}},Sn=class extends C{},pw=class extends Sn{},hw=class extends Sn{async _call(e){return new pt(await super._call(e))}},fw=class extends Sn{async _call(e){return new de(await super._call(e))}},Ew=class extends Sn{async _call(e){return new ot(await super._call(e))}},$w=class extends Sn{async _call(e){return new Nt(await super._call(e))}},Lc=class extends C{},mw=class extends Lc{},Iw=class extends Lc{async _call(e){return new wh(await super._call(e))}},wh=class extends ms{},Nh=class extends dt{constructor({iou_scores:e,pred_masks:t}){super(),this.iou_scores=e,this.pred_masks=t}},Bh=class extends C{},Sw=class extends Bh{async get_image_embeddings({pixel_values:e}){return await Da(this,{pixel_values:e})}async forward(e){!e.image_embeddings||!e.image_positional_embeddings?e={...e,...await this.get_image_embeddings(e)}:e={...e},e.input_labels??=Kt(e.input_points.dims.slice(0,-1));let t={image_embeddings:e.image_embeddings,image_positional_embeddings:e.image_positional_embeddings};return e.input_points&&(t.input_points=e.input_points),e.input_labels&&(t.input_labels=e.input_labels),e.input_boxes&&(t.input_boxes=e.input_boxes),await xe(this.sessions.prompt_encoder_mask_decoder,t)}async _call(e){return new Nh(await super._call(e))}},Mh=class extends dt{constructor({iou_scores:e,pred_masks:t,object_score_logits:r}){super(),this.iou_scores=e,this.pred_masks=t,this.object_score_logits=r}},Ph=class extends C{},Ac=class extends Ph{async get_image_embeddings({pixel_values:e}){return await Da(this,{pixel_values:e})}async forward(e){let{num_feature_levels:t}=this.config.vision_config;if(Array.from({length:t},(s,i)=>`image_embeddings.${i}`).some(s=>!e[s])?e={...e,...await this.get_image_embeddings(e)}:e={...e},e.input_points){if(e.input_boxes&&e.input_boxes.dims[1]!==1)throw new Error("When both `input_points` and `input_boxes` are provided, the number of boxes per image must be 1.");let s=e.input_points.dims;e.input_labels??=Kt(s.slice(0,-1)),e.input_boxes??=xt([s[0],0,4],0)}else if(e.input_boxes){let s=e.input_boxes.dims;e.input_labels=xt([s[0],s[1],0],-1n),e.input_points=xt([s[0],1,0,2],0)}else throw new Error("At least one of `input_points` or `input_boxes` must be provided.");let a=this.sessions.prompt_encoder_mask_decoder,n=It(e,a.inputNames);return await xe(a,n)}async _call(e){return new Mh(await super._call(e))}},Lw=class extends Ac{},Aw=class extends Ac{},xi=class extends C{},gw=class extends xi{},bw=class extends xi{},Tw=class extends xi{},vi=class extends C{},xw=class extends vi{},vw=class extends vi{},yw=class extends vi{},gc=class extends C{},Dw=class extends gc{},kh=class extends gc{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},Cw=class extends Ca{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},bc=class extends C{},ww=class extends bc{},Nw=class extends bc{},Bw=class extends uh{},yi=class extends C{main_input_name="input_values";forward_params=["input_values"]},Mw=class extends yi{async encode(e){return await xe(this.sessions.encoder_model,e)}async decode(e){return await xe(this.sessions.decoder_model,e)}},Rh=class extends yi{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"encoder_model"})}},Oh=class extends yi{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"decoder_model"})}},Tc=class extends C{},Pw=class extends Tc{},kw=class extends Tc{},Di=class extends C{},Rw=class extends Di{},Ow=class extends Di{},Gw=class extends Di{async generate_speech(e,t,{threshold:r=.5,minlenratio:a=0,maxlenratio:n=20,vocoder:s=null}={}){let i={input_ids:e},{encoder_outputs:o,encoder_attention_mask:H}=await Da(this,i),_=o.dims[1]/this.config.reduction_factor,c=Math.floor(_*n),l=Math.floor(_*a),d=this.config.num_mel_bins,h=[],$=null,m=null,S=0;for(;;){++S;let T=fT(!!m),x;m?x=m.output_sequence_out:x=new j("float32",new Float32Array(d),[1,1,d]);let v={use_cache_branch:T,output_sequence:x,encoder_attention_mask:H,speaker_embeddings:t,encoder_hidden_states:o};Bp(this,v,$),m=await xe(this.sessions.decoder_model_merged,v),$=ud(m,$);let{prob:k,spectrum:L}=m;if(h.push(L),S>=l&&(Array.from(k.data).filter(V=>V>=r).length>0||S>=c))break}let I=Ue(h),{waveform:g}=await xe(s.sessions.model,{spectrogram:I});return{spectrogram:I,waveform:g}}},Fw=class extends C{main_input_name="spectrogram"},bs=class extends C{},Zw=class extends bs{},Uw=class extends bs{async _call(e){return new pt(await super._call(e))}},Ww=class extends bs{async _call(e){return new de(await super._call(e))}},Kw=class extends bs{async _call(e){return new Nt(await super._call(e))}},xc=class extends C{},Vw=class extends xc{},jw=class extends xc{},vc=class extends C{},qw=class extends vc{},Xw=class extends vc{},Gh=class extends C{},zw=class extends Gh{},Fh=class extends C{},Zh=class extends Fh{async generate_speech({input_ids:e,attention_mask:t,style:r,num_inference_steps:a=5,speed:n=1.05}){let{sampling_rate:s,chunk_compress_factor:i,base_chunk_size:o,latent_dim:H}=this.config,{last_hidden_state:_,durations:c}=await xe(this.sessions.text_encoder,{input_ids:e,attention_mask:t,style:r}),l=c.div(n).mul_(s),d=o*i,h=l.data,$=Int32Array.from(h,K=>Math.ceil(K/d)),m=Math.max(...$),S=e.dims[0],I=new BigInt64Array(S*m);for(let K=0;K<S;++K)I.fill(1n,K*m,K*m+$[K]);let g=new j("int64",I,[S,m]),T=H*i,x=T*m,v=_A([S,T,m]),k=v.data;for(let K=0;K<S;++K)if($[K]!==m)for(let X=0;X<T;++X)k.fill(0,K*x+X*m+$[K],K*x+(X+1)*m);let L=xt([S],a);for(let K=0;K<a;++K){let X=xt([S],K);({denoised_latents:v}=await xe(this.sessions.latent_denoiser,{style:r,noisy_latents:v,latent_mask:g,encoder_outputs:_,attention_mask:t,timestep:X,num_inference_steps:L}))}let{waveform:V}=await xe(this.sessions.voice_decoder,{latents:v});return{waveform:V,durations:l}}},Ci=class extends C{},Jw=class extends Ci{},Qw=class extends Ci{async _call(e){return new de(await super._call(e))}},Yw=class extends Ci{},yc=class extends C{},eN=class extends yc{},tN=class extends yc{},Dc=class extends C{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]},rN=class extends Dc{},aN=class extends Dc{},Cc=class extends C{},nN=class extends Cc{},sN=class extends Cc{async _call(e){return new Uh(await super._call(e))}},Uh=class extends t_{},Wh=class extends C{},iN=class extends Wh{},wi=class extends C{},oN=class extends wi{},HN=class extends wi{async _call(e){return new cn(await super._call(e))}},_N=class extends wi{async _call(e){return new de(await super._call(e))}},Ts=class extends C{},cN=class extends Ts{},lN=class extends Ts{async _call(e){return new cn(await super._call(e))}},uN=class extends Ts{async _call(e){return new de(await super._call(e))}},dN=class extends Ts{async _call(e){return new ot(await super._call(e))}},wc=class extends C{},pN=class extends wc{},hN=class extends wc{},fN=class extends C{main_input_name="pixel_values";forward_params=["pixel_values","decoder_input_ids","encoder_hidden_states","past_key_values"]},Nc=class extends C{},EN=class extends Nc{},$N=class extends Nc{async _call(e){return new de(await super._call(e))}},Kh=class extends C{},mN=class extends Kh{},Bc=class extends C{},IN=class extends Bc{},SN=class extends Bc{async _call(e){return new de(await super._call(e))}},Vh=class extends C{},LN=class extends Vh{async _call(e){return new VZ(await super._call(e))}},jh=class extends C{},AN=class extends jh{},qh=class extends dt{constructor({waveform:e,spectrogram:t}){super(),this.waveform=e,this.spectrogram=t}},Xh=class extends C{},gN=class extends Xh{async _call(e){return new qh(await super._call(e))}},bN=class extends x_{},CS=2,_7=1,Ju=new WeakMap;p7=class extends Es{constructor(e){super(),this._s=e}_call(e){let t=this._s.stream_exhausted&&this._s.audio_embed_queue.length===0;return e.map(()=>t)}},zh=class extends C{forward_params=["input_ids","attention_mask","position_ids","past_key_values"]},Jh=class extends zh{async forward({input_ids:e,past_key_values:t,...r}){let a=e.dims[1],n=Ju.get(this);n&&await u7(n,n.audio_consumed+a);let{inputs_embeds:s}=await xe(this.sessions.embed_tokens,{input_ids:e});n&&d7(n,s,a);let i={inputs_embeds:s,...r};Bp(this,i,t);let o=this.sessions.decoder_model_merged,H=It(i,o.inputNames);return await xe(o,H)}async generate({input_features:e,stopping_criteria:t,...r}){if(!e)throw new Error("input_features (generator/iterable) must be provided");let a=c7(this,e);Ju.set(this,a);let n=new yp;n.push(new p7(a)),t&&n.extend(t);try{return await super.generate({...r,stopping_criteria:n})}finally{a.enc_kv_cache.dispose(),Ju.delete(this)}}},Ni=class extends C{},TN=class extends Ni{},xN=class extends Ni{async _call(e){return new cn(await super._call(e))}},vN=class extends Ni{async _call(e){return new de(await super._call(e))}},Qh=class extends dt{constructor({logits:e,embeddings:t}){super(),this.logits=e,this.embeddings=t}},Ln=class extends C{},yN=class extends Ln{},DN=class extends Ln{async _call(e){return new cn(await super._call(e))}},CN=class extends Ln{async _call(e){return new de(await super._call(e))}},wN=class extends Ln{async _call(e){return new Qh(await super._call(e))}},NN=class extends Ln{async _call(e){return new ot(await super._call(e))}},Yh=class extends C{},BN=class extends Yh{},h7=class extends lT{return_timestamps=null;return_token_timestamps=null;num_frames=null;alignment_heads=null;task=null;language=null;no_timestamps_token_id=null;prompt_ids=null;is_multilingual=null;lang_to_id=null;task_to_id=null;max_initial_timestamp_index=1},Mc=class extends C{requires_attention_mask=!1;main_input_name="input_features";forward_params=["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"]},MN=class extends Mc{},ef=class extends Mc{_prepare_generation_config(e,t){return super._prepare_generation_config(e,t,h7)}_retrieve_init_tokens(e){let t=[e.decoder_start_token_id],r=e.language,a=e.task;if(e.is_multilingual){r||(fe.warn("No language specified - defaulting to English (en)."),r="en");let s=`<|${tZ(r)}|>`;t.push(e.lang_to_id[s]),t.push(e.task_to_id[a??"transcribe"])}else if(r||a)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!e.return_timestamps&&e.no_timestamps_token_id&&t.at(-1)!==e.no_timestamps_token_id?t.push(e.no_timestamps_token_id):e.return_timestamps&&t.at(-1)===e.no_timestamps_token_id&&(fe.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),t.pop()),t.filter(n=>n!=null)}async generate({inputs:e=null,generation_config:t=null,logits_processor:r=null,stopping_criteria:a=null,...n}){t=this._prepare_generation_config(t,n);let s=n.decoder_input_ids instanceof j?Jd(n.decoder_input_ids):n.decoder_input_ids??this._retrieve_init_tokens(t);if(t.return_timestamps&&(r??=new EH,r.push(new aT(t,s))),t.begin_suppress_tokens&&(r??=new EH,r.push(new vp(t.begin_suppress_tokens,s.length))),t.return_token_timestamps){if(!t.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.");t.task==="translate"&&fe.warn("Token-level timestamps may not be reliable for task 'translate'."),t.output_attentions=!0,t.return_dict_in_generate=!0}if(t.return_timestamps&&!n.max_new_tokens)return this._generate_with_seek({inputs:e,generation_config:t,logits_processor:r,init_tokens:s,kwargs:n});let i=await super.generate({inputs:e,generation_config:t,logits_processor:r,decoder_input_ids:s,...n});return t.return_token_timestamps&&(i.token_timestamps=this._extract_token_timestamps(i,t.alignment_heads,t.num_frames,.02,s.length)),i}async _generate_with_seek({inputs:e,generation_config:t,logits_processor:r,init_tokens:a,kwargs:n}){let s=t.no_timestamps_token_id+1,i=Array.isArray(t.eos_token_id)?t.eos_token_id[0]:t.eos_token_id,o=t.return_token_timestamps,H=e,_=H.dims[2],c=2,l=this.config.max_source_positions,d=c*l,h=0,$=[],m=[];for(;h<_;){let I=Math.min(h+d,_),g=H.slice(null,null,[h,I]),T,x=g.dims[2];if(x<d){let G=H.dims[1],te=new Float32Array(G*d),B=g.data;for(let O=0;O<G;++O)te.set(B.subarray(O*x,(O+1)*x),O*d);T=new j("float32",te,[1,G,d])}else T=g;if(r)for(let G of r)"begin_index"in G&&(G.begin_index=a.length);let v=await super.generate({inputs:T,generation_config:t,logits_processor:r,decoder_input_ids:a,...n}),L=(o?v.sequences:v)[0].tolist().map(Number).slice(a.length),V;if(o){v.token_timestamps=this._extract_token_timestamps(v,t.alignment_heads,Math.floor((I-h)/c),.02,a.length);let G=h/c*.02;V=v.token_timestamps[0].tolist().slice(a.length).map(te=>te+G)}if(L.length>0&&L.at(-1)===i&&L.pop(),L.length===0)break;let K=L.map(G=>G>=s),X=L.length>=2&&K[L.length-1]&&!K[L.length-2],Q=[];for(let G=0;G<L.length-1;++G)K[G]&&K[G+1]&&Q.push(G+1);let z,M=L.length;if(Q.length>0)if(X)z=I-h;else{let G=Q.at(-1);z=(L[G-1]-s)*c,M=G}else z=I-h;let F=Math.floor(h/c),N=s+1500;for(let G=0;G<M;++G)L[G]>=s&&(L[G]=Math.min(L[G]+F,N));$.push(...L.slice(0,M)),V&&m.push(...V.slice(0,M)),h+=z}$.push(i);let S=[...a,...$];if(o){let I=new j("int64",S.map(BigInt),[1,S.length]),g=[...new Array(a.length).fill(0),...m,0],T=new j("float32",new Float32Array(g),[1,g.length]);return{sequences:I,token_timestamps:T}}return new j("int64",S.map(BigInt),[1,S.length])}_extract_token_timestamps(e,t,r=null,a=.02,n=0){if(!e.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`.");r==null&&fe.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 s=this.config.median_filter_width;s===void 0&&(fe.warn("Model config has no `median_filter_width`, using default value of 7."),s=7);let i=e.cross_attentions,o=Array.from({length:this.config.decoder_layers},(S,I)=>Ue(i.map(g=>g[I]),2)),H=Ur(t.map(([S,I])=>{if(S>=o.length)throw new Error(`Layer index ${S} is out of bounds for cross attentions (length ${o.length}).`);return r?o[S].slice(null,I,null,[0,r]):o[S].slice(null,I)})).transpose(1,0,2,3),[_,c]=Kd(H,-2,0,!0),l=H.clone();for(let S=0;S<l.dims[0];++S){let I=l[S];for(let g=0;g<I.dims[0];++g){let T=I[g],x=_[S][g][0].data,v=c[S][g][0].data;for(let k=0;k<T.dims[0];++k){let L=T[k].data;for(let V=0;V<L.length;++V)L[V]=(L[V]-v[V])/x[V];L.set(rF(L,s))}}}let d=n>0?l.slice(null,null,[n,l.dims[2]],null):l,h=[bH(d,1)],$=e.sequences.dims,m=new j("float32",new Float32Array($[0]*$[1]),$);for(let S=0;S<$[0];++S){let I=h[S].neg().squeeze_(0),[g,T]=nF(I.tolist()),x=Array.from({length:g.length-1},(V,K)=>g[K+1]-g[K]),v=$r([1],x).map(V=>!!V),k=[];for(let V=0;V<v.length;++V)v[V]&&k.push(T[V]*a);let L=new Array(n).fill(0);L.push(...k),k.length>0&&L.push(k.at(-1)),m[S].data.set(L)}return m}},PN=class extends ef{},An=class extends C{},kN=class extends An{},RN=class extends An{async _call(e){return new pt(await super._call(e))}},ON=class extends An{async _call(e){return new de(await super._call(e))}},GN=class extends An{async _call(e){return new ot(await super._call(e))}},FN=class extends An{async _call(e){return new Nt(await super._call(e))}},gn=class extends C{},ZN=class extends gn{},UN=class extends gn{async _call(e){return new pt(await super._call(e))}},WN=class extends gn{async _call(e){return new de(await super._call(e))}},KN=class extends gn{async _call(e){return new ot(await super._call(e))}},VN=class extends gn{async _call(e){return new Nt(await super._call(e))}},Pc=class extends C{},jN=class extends Pc{},qN=class extends Pc{async _call(e){return new tf(await super._call(e))}},tf=class extends dt{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},kc=class extends C{},XN=class extends kc{},zN=class extends kc{},f7=new Map([["bert","BertModel"],["eurobert","EuroBertModel"],["neobert","NeoBertModel"],["modernbert","ModernBertModel"],["nomic_bert","NomicBertModel"],["roformer","RoFormerModel"],["electra","ElectraModel"],["esm","EsmModel"],["convbert","ConvBertModel"],["camembert","CamembertModel"],["deberta","DebertaModel"],["deberta-v2","DebertaV2Model"],["mpnet","MPNetModel"],["albert","AlbertModel"],["distilbert","DistilBertModel"],["roberta","RobertaModel"],["xlm","XLMModel"],["xlm-roberta","XLMRobertaModel"],["clap","ClapModel"],["clip","CLIPModel"],["clipseg","CLIPSegModel"],["chinese_clip","ChineseCLIPModel"],["siglip","SiglipModel"],["jina_clip","JinaCLIPModel"],["mobilebert","MobileBertModel"],["squeezebert","SqueezeBertModel"],["wav2vec2","Wav2Vec2Model"],["wav2vec2-bert","Wav2Vec2BertModel"],["unispeech","UniSpeechModel"],["unispeech-sat","UniSpeechSatModel"],["hubert","HubertModel"],["wavlm","WavLMModel"],["audio-spectrogram-transformer","ASTModel"],["vits","VitsModel"],["pyannote","PyAnnoteModel"],["wespeaker-resnet","WeSpeakerResNetModel"],["detr","DetrModel"],["rt_detr","RTDetrModel"],["rt_detr_v2","RTDetrV2Model"],["rf_detr","RFDetrModel"],["d_fine","DFineModel"],["table-transformer","TableTransformerModel"],["vit","ViTModel"],["ijepa","IJepaModel"],["pvt","PvtModel"],["vit_msn","ViTMSNModel"],["vit_mae","ViTMAEModel"],["groupvit","GroupViTModel"],["fastvit","FastViTModel"],["mobilevit","MobileViTModel"],["mobilevitv2","MobileViTV2Model"],["owlvit","OwlViTModel"],["owlv2","Owlv2Model"],["beit","BeitModel"],["deit","DeiTModel"],["hiera","HieraModel"],["convnext","ConvNextModel"],["convnextv2","ConvNextV2Model"],["dinov2","Dinov2Model"],["dinov2_with_registers","Dinov2WithRegistersModel"],["dinov3_vit","DINOv3ViTModel"],["dinov3_convnext","DINOv3ConvNextModel"],["resnet","ResNetModel"],["swin","SwinModel"],["swin2sr","Swin2SRModel"],["donut-swin","DonutSwinModel"],["yolos","YolosModel"],["dpt","DPTModel"],["glpn","GLPNModel"],["hifigan","SpeechT5HifiGan"],["efficientnet","EfficientNetModel"],["decision_transformer","DecisionTransformerModel"],["patchtst","PatchTSTModel"],["patchtsmixer","PatchTSMixerModel"],["mobilenet_v1","MobileNetV1Model"],["mobilenet_v2","MobileNetV2Model"],["mobilenet_v3","MobileNetV3Model"],["mobilenet_v4","MobileNetV4Model"],["maskformer","MaskFormerModel"],["mgp-str","MgpstrForSceneTextRecognition"],["style_text_to_speech_2","StyleTextToSpeech2Model"],["openai_privacy_filter","OpenAIPrivacyFilterModel"]]),E7=new Map([["t5","T5Model"],["longt5","LongT5Model"],["mt5","MT5Model"],["bart","BartModel"],["mbart","MBartModel"],["marian","MarianModel"],["whisper","WhisperModel"],["cohere_asr","CohereAsrModel"],["m2m_100","M2M100Model"],["blenderbot","BlenderbotModel"],["blenderbot-small","BlenderbotSmallModel"]]),$7=new Map([["mimi","MimiModel"],["dac","DacModel"],["snac","SnacModel"]]),m7=new Map([["bloom","BloomModel"],["jais","JAISModel"],["gpt2","GPT2Model"],["gpt_oss","GptOssModel"],["gptj","GPTJModel"],["gpt_bigcode","GPTBigCodeModel"],["gpt_neo","GPTNeoModel"],["gpt_neox","GPTNeoXModel"],["codegen","CodeGenModel"],["llama","LlamaModel"],["apertus","ApertusModel"],["nanochat","NanoChatModel"],["arcee","ArceeModel"],["afmoe","AfmoeModel"],["lfm2","Lfm2Model"],["lfm2_moe","Lfm2MoeModel"],["smollm3","SmolLM3Model"],["exaone","ExaoneModel"],["olmo","OlmoModel"],["olmo2","Olmo2Model"],["olmo3","Olmo3Model"],["olmo_hybrid","OlmoHybridModel"],["mobilellm","MobileLLMModel"],["granite","GraniteModel"],["granitemoehybrid","GraniteMoeHybridModel"],["cohere","CohereModel"],["cohere2","Cohere2Model"],["gemma","GemmaModel"],["gemma2","Gemma2Model"],["vaultgemma","VaultGemmaModel"],["gemma3_text","Gemma3Model"],["helium","HeliumModel"],["glm","GlmModel"],["glm_moe_dsa","GlmMoeDsaModel"],["openelm","OpenELMModel"],["qwen2","Qwen2Model"],["qwen2_moe","Qwen2MoeModel"],["qwen3","Qwen3Model"],["qwen3_moe","Qwen3MoeModel"],["qwen3_next","Qwen3NextModel"],["phi","PhiModel"],["phi3","Phi3Model"],["mpt","MptModel"],["opt","OPTModel"],["mistral","MistralModel"],["mistral4","Mistral4Model"],["ministral","MinistralModel"],["ministral3","Ministral3Model"],["ernie4_5","Ernie4_5ForCausalLM"],["starcoder2","Starcoder2Model"],["deepseek_v3","DeepseekV3Model"],["falcon","FalconModel"],["falcon_h1","FalconH1Model"],["nemotron_h","NemotronHModel"],["solar_open","SolarOpenModel"],["stablelm","StableLmModel"],["modernbert-decoder","ModernBertDecoderModel"],["hunyuan_v1_dense","HunYuanDenseV1Model"],["youtu","YoutuModel"]]),JN=new Map([["speecht5","SpeechT5ForSpeechToText"],["whisper","WhisperForConditionalGeneration"],["lite-whisper","LiteWhisperForConditionalGeneration"],["moonshine","MoonshineForConditionalGeneration"],["cohere_asr","CohereAsrForConditionalGeneration"]]),QN=new Map([["speecht5","SpeechT5ForTextToSpeech"]]),YN=new Map([["vits","VitsModel"],["musicgen","MusicgenForConditionalGeneration"],["supertonic","SupertonicForConditionalGeneration"]]),e2=new Map([["bert","BertForSequenceClassification"],["eurobert","EuroBertForSequenceClassification"],["neobert","NeoBertForSequenceClassification"],["modernbert","ModernBertForSequenceClassification"],["roformer","RoFormerForSequenceClassification"],["electra","ElectraForSequenceClassification"],["esm","EsmForSequenceClassification"],["convbert","ConvBertForSequenceClassification"],["camembert","CamembertForSequenceClassification"],["deberta","DebertaForSequenceClassification"],["deberta-v2","DebertaV2ForSequenceClassification"],["mpnet","MPNetForSequenceClassification"],["albert","AlbertForSequenceClassification"],["distilbert","DistilBertForSequenceClassification"],["roberta","RobertaForSequenceClassification"],["xlm","XLMForSequenceClassification"],["xlm-roberta","XLMRobertaForSequenceClassification"],["bart","BartForSequenceClassification"],["mbart","MBartForSequenceClassification"],["mobilebert","MobileBertForSequenceClassification"],["squeezebert","SqueezeBertForSequenceClassification"]]),t2=new Map([["bert","BertForTokenClassification"],["eurobert","EuroBertForTokenClassification"],["neobert","NeoBertForTokenClassification"],["modernbert","ModernBertForTokenClassification"],["roformer","RoFormerForTokenClassification"],["electra","ElectraForTokenClassification"],["esm","EsmForTokenClassification"],["convbert","ConvBertForTokenClassification"],["camembert","CamembertForTokenClassification"],["deberta","DebertaForTokenClassification"],["deberta-v2","DebertaV2ForTokenClassification"],["mpnet","MPNetForTokenClassification"],["distilbert","DistilBertForTokenClassification"],["roberta","RobertaForTokenClassification"],["xlm","XLMForTokenClassification"],["xlm-roberta","XLMRobertaForTokenClassification"],["openai_privacy_filter","OpenAIPrivacyFilterForTokenClassification"]]),r2=new Map([["t5","T5ForConditionalGeneration"],["longt5","LongT5ForConditionalGeneration"],["mt5","MT5ForConditionalGeneration"],["bart","BartForConditionalGeneration"],["mbart","MBartForConditionalGeneration"],["marian","MarianMTModel"],["m2m_100","M2M100ForConditionalGeneration"],["blenderbot","BlenderbotForConditionalGeneration"],["blenderbot-small","BlenderbotSmallForConditionalGeneration"]]),a2=new Map([["bloom","BloomForCausalLM"],["gpt2","GPT2LMHeadModel"],["gpt_oss","GptOssForCausalLM"],["jais","JAISLMHeadModel"],["gptj","GPTJForCausalLM"],["gpt_bigcode","GPTBigCodeForCausalLM"],["gpt_neo","GPTNeoForCausalLM"],["gpt_neox","GPTNeoXForCausalLM"],["codegen","CodeGenForCausalLM"],["llama","LlamaForCausalLM"],["nanochat","NanoChatForCausalLM"],["apertus","ApertusForCausalLM"],["llama4_text","Llama4ForCausalLM"],["arcee","ArceeForCausalLM"],["afmoe","AfmoeForCausalLM"],["lfm2","Lfm2ForCausalLM"],["lfm2_moe","Lfm2MoeForCausalLM"],["smollm3","SmolLM3ForCausalLM"],["exaone","ExaoneForCausalLM"],["olmo","OlmoForCausalLM"],["olmo2","Olmo2ForCausalLM"],["olmo3","Olmo3ForCausalLM"],["olmo_hybrid","OlmoHybridForCausalLM"],["mobilellm","MobileLLMForCausalLM"],["granite","GraniteForCausalLM"],["granitemoehybrid","GraniteMoeHybridForCausalLM"],["cohere","CohereForCausalLM"],["cohere2","Cohere2ForCausalLM"],["gemma","GemmaForCausalLM"],["gemma2","Gemma2ForCausalLM"],["vaultgemma","VaultGemmaForCausalLM"],["gemma3_text","Gemma3ForCausalLM"],["gemma3","Gemma3ForCausalLM"],["helium","HeliumForCausalLM"],["glm","GlmForCausalLM"],["glm_moe_dsa","GlmMoeDsaForCausalLM"],["openelm","OpenELMForCausalLM"],["qwen2","Qwen2ForCausalLM"],["qwen2_moe","Qwen2MoeForCausalLM"],["qwen3","Qwen3ForCausalLM"],["qwen3_moe","Qwen3MoeForCausalLM"],["qwen3_next","Qwen3NextForCausalLM"],["qwen2_vl","Qwen2VLForCausalLM"],["qwen2_5_vl","Qwen2_5_VLForCausalLM"],["qwen3_vl","Qwen3VLForCausalLM"],["qwen3_vl_moe","Qwen3VLMoeForCausalLM"],["qwen3_5","Qwen3_5ForCausalLM"],["qwen3_5_text","Qwen3_5ForCausalLM"],["qwen3_5_moe","Qwen3_5MoeForCausalLM"],["gemma3n","Gemma3nForCausalLM"],["gemma4","Gemma4ForCausalLM"],["phi","PhiForCausalLM"],["phi3","Phi3ForCausalLM"],["mpt","MptForCausalLM"],["opt","OPTForCausalLM"],["mbart","MBartForCausalLM"],["mistral","MistralForCausalLM"],["mistral4","Mistral4ForCausalLM"],["ministral","MinistralForCausalLM"],["ministral3","Ministral3ForCausalLM"],["ernie4_5","Ernie4_5ForCausalLM"],["starcoder2","Starcoder2ForCausalLM"],["deepseek_v3","DeepseekV3ForCausalLM"],["falcon","FalconForCausalLM"],["falcon_h1","FalconH1ForCausalLM"],["nemotron_h","NemotronHForCausalLM"],["trocr","TrOCRForCausalLM"],["solar_open","SolarOpenForCausalLM"],["stablelm","StableLmForCausalLM"],["modernbert-decoder","ModernBertDecoderForCausalLM"],["hunyuan_v1_dense","HunYuanDenseV1ForCausalLM"],["youtu","YoutuForCausalLM"],["phi3_v","Phi3VForCausalLM"]]),I7=new Map([["multi_modality","MultiModalityCausalLM"]]),n2=new Map([["bert","BertForMaskedLM"],["eurobert","EuroBertForMaskedLM"],["neobert","NeoBertForMaskedLM"],["modernbert","ModernBertForMaskedLM"],["roformer","RoFormerForMaskedLM"],["electra","ElectraForMaskedLM"],["esm","EsmForMaskedLM"],["convbert","ConvBertForMaskedLM"],["camembert","CamembertForMaskedLM"],["deberta","DebertaForMaskedLM"],["deberta-v2","DebertaV2ForMaskedLM"],["mpnet","MPNetForMaskedLM"],["albert","AlbertForMaskedLM"],["distilbert","DistilBertForMaskedLM"],["roberta","RobertaForMaskedLM"],["xlm","XLMWithLMHeadModel"],["xlm-roberta","XLMRobertaForMaskedLM"],["mobilebert","MobileBertForMaskedLM"],["squeezebert","SqueezeBertForMaskedLM"]]),s2=new Map([["bert","BertForQuestionAnswering"],["neobert","NeoBertForQuestionAnswering"],["roformer","RoFormerForQuestionAnswering"],["electra","ElectraForQuestionAnswering"],["convbert","ConvBertForQuestionAnswering"],["camembert","CamembertForQuestionAnswering"],["deberta","DebertaForQuestionAnswering"],["deberta-v2","DebertaV2ForQuestionAnswering"],["mpnet","MPNetForQuestionAnswering"],["albert","AlbertForQuestionAnswering"],["distilbert","DistilBertForQuestionAnswering"],["roberta","RobertaForQuestionAnswering"],["xlm","XLMForQuestionAnswering"],["xlm-roberta","XLMRobertaForQuestionAnswering"],["mobilebert","MobileBertForQuestionAnswering"],["squeezebert","SqueezeBertForQuestionAnswering"]]),i2=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"],["idefics3","Idefics3ForConditionalGeneration"],["smolvlm","SmolVLMForConditionalGeneration"]]),o2=new Map([["llava","LlavaForConditionalGeneration"],["llava_onevision","LlavaOnevisionForConditionalGeneration"],["moondream1","Moondream1ForConditionalGeneration"],["florence2","Florence2ForConditionalGeneration"],["qwen2_vl","Qwen2VLForConditionalGeneration"],["qwen2_5_vl","Qwen2_5_VLForConditionalGeneration"],["qwen3_vl","Qwen3VLForConditionalGeneration"],["qwen3_vl_moe","Qwen3VLMoeForConditionalGeneration"],["qwen3_5","Qwen3_5ForConditionalGeneration"],["qwen3_5_moe","Qwen3_5MoeForConditionalGeneration"],["lfm2_vl","Lfm2VlForConditionalGeneration"],["idefics3","Idefics3ForConditionalGeneration"],["smolvlm","SmolVLMForConditionalGeneration"],["paligemma","PaliGemmaForConditionalGeneration"],["llava_qwen2","LlavaQwen2ForCausalLM"],["gemma3","Gemma3ForConditionalGeneration"],["gemma3n","Gemma3nForConditionalGeneration"],["gemma4","Gemma4ForConditionalGeneration"],["mistral3","Mistral3ForConditionalGeneration"],["lighton_ocr","LightOnOcrForConditionalGeneration"],["glm_ocr","GlmOcrForConditionalGeneration"]]),H2=new Map([["granite_speech","GraniteSpeechForConditionalGeneration"],["ultravox","UltravoxModel"],["voxtral","VoxtralForConditionalGeneration"],["voxtral_realtime","VoxtralRealtimeForConditionalGeneration"]]),S7=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"]]),_2=new Map([["vit","ViTForImageClassification"],["ijepa","IJepaForImageClassification"],["pvt","PvtForImageClassification"],["vit_msn","ViTMSNForImageClassification"],["fastvit","FastViTForImageClassification"],["mobilevit","MobileViTForImageClassification"],["mobilevitv2","MobileViTV2ForImageClassification"],["beit","BeitForImageClassification"],["deit","DeiTForImageClassification"],["hiera","HieraForImageClassification"],["convnext","ConvNextForImageClassification"],["convnextv2","ConvNextV2ForImageClassification"],["dinov2","Dinov2ForImageClassification"],["dinov2_with_registers","Dinov2WithRegistersForImageClassification"],["resnet","ResNetForImageClassification"],["swin","SwinForImageClassification"],["segformer","SegformerForImageClassification"],["efficientnet","EfficientNetForImageClassification"],["mobilenet_v1","MobileNetV1ForImageClassification"],["mobilenet_v2","MobileNetV2ForImageClassification"],["mobilenet_v3","MobileNetV3ForImageClassification"],["mobilenet_v4","MobileNetV4ForImageClassification"]]),c2=new Map([["detr","DetrForObjectDetection"],["rt_detr","RTDetrForObjectDetection"],["rt_detr_v2","RTDetrV2ForObjectDetection"],["rf_detr","RFDetrForObjectDetection"],["d_fine","DFineForObjectDetection"],["table-transformer","TableTransformerForObjectDetection"],["yolos","YolosForObjectDetection"]]),l2=new Map([["owlvit","OwlViTForObjectDetection"],["owlv2","Owlv2ForObjectDetection"],["grounding-dino","GroundingDinoForObjectDetection"]]),ss=new Map([["detr","DetrForSegmentation"],["clipseg","CLIPSegForImageSegmentation"]]),u2=new Map([["segformer","SegformerForSemanticSegmentation"],["sapiens","SapiensForSemanticSegmentation"],["swin","SwinForSemanticSegmentation"],["mobilenet_v1","MobileNetV1ForSemanticSegmentation"],["mobilenet_v2","MobileNetV2ForSemanticSegmentation"],["mobilenet_v3","MobileNetV3ForSemanticSegmentation"],["mobilenet_v4","MobileNetV4ForSemanticSegmentation"]]),d2=new Map([["detr","DetrForSegmentation"],["maskformer","MaskFormerForInstanceSegmentation"]]),p2=new Map([["sam","SamModel"],["sam2","Sam2Model"],["edgetam","EdgeTamModel"],["sam3_tracker","Sam3TrackerModel"]]),h2=new Map([["wav2vec2","Wav2Vec2ForCTC"],["wav2vec2-bert","Wav2Vec2BertForCTC"],["unispeech","UniSpeechForCTC"],["unispeech-sat","UniSpeechSatForCTC"],["wavlm","WavLMForCTC"],["hubert","HubertForCTC"],["parakeet_ctc","ParakeetForCTC"]]),f2=new Map([["wav2vec2","Wav2Vec2ForSequenceClassification"],["wav2vec2-bert","Wav2Vec2BertForSequenceClassification"],["unispeech","UniSpeechForSequenceClassification"],["unispeech-sat","UniSpeechSatForSequenceClassification"],["wavlm","WavLMForSequenceClassification"],["hubert","HubertForSequenceClassification"],["audio-spectrogram-transformer","ASTForAudioClassification"]]),E2=new Map([["wavlm","WavLMForXVector"]]),$2=new Map([["unispeech-sat","UniSpeechSatForAudioFrameClassification"],["wavlm","WavLMForAudioFrameClassification"],["wav2vec2","Wav2Vec2ForAudioFrameClassification"],["pyannote","PyAnnoteForAudioFrameClassification"]]),m2=new Map([["vitmatte","VitMatteForImageMatting"]]),L7=new Map([["patchtst","PatchTSTForPrediction"],["patchtsmixer","PatchTSMixerForPrediction"]]),I2=new Map([["swin2sr","Swin2SRForImageSuperResolution"]]),S2=new Map([["chmv2","CHMv2ForDepthEstimation"],["dpt","DPTForDepthEstimation"],["depth_anything","DepthAnythingForDepthEstimation"],["glpn","GLPNForDepthEstimation"],["sapiens","SapiensForDepthEstimation"],["depth_pro","DepthProForDepthEstimation"],["metric3d","Metric3DForDepthEstimation"],["metric3dv2","Metric3Dv2ForDepthEstimation"]]),L2=new Map([["sapiens","SapiensForNormalEstimation"]]),A2=new Map([["vitpose","VitPoseForPoseEstimation"]]),g2=new Map([["clip","CLIPVisionModelWithProjection"],["siglip","SiglipVisionModel"],["jina_clip","JinaCLIPVisionModel"]]),b2=[[f7,J.EncoderOnly],[E7,J.EncoderDecoder],[m7,J.DecoderOnlyWithoutHead],[$7,J.AutoEncoder],[e2,J.EncoderOnly],[t2,J.EncoderOnly],[r2,J.Seq2Seq],[JN,J.Seq2Seq],[a2,J.DecoderOnly],[I7,J.MultiModality],[n2,J.EncoderOnly],[s2,J.EncoderOnly],[i2,J.Vision2Seq],[o2,J.ImageTextToText],[H2,J.AudioTextToText],[_2,J.EncoderOnly],[ss,J.EncoderOnly],[d2,J.EncoderOnly],[u2,J.EncoderOnly],[m2,J.EncoderOnly],[L7,J.EncoderOnly],[I2,J.EncoderOnly],[S2,J.EncoderOnly],[L2,J.EncoderOnly],[A2,J.EncoderOnly],[c2,J.EncoderOnly],[l2,J.EncoderOnly],[p2,J.MaskGeneration],[h2,J.EncoderOnly],[f2,J.EncoderOnly],[QN,J.Seq2Seq],[YN,J.EncoderOnly],[E2,J.EncoderOnly],[$2,J.EncoderOnly],[g2,J.EncoderOnly]];for(let[e,t]of b2)for(let r of e.values()){Ha.set(r,t);let a=Pp[r];cs.set(a,r),Np.set(r,a)}A7=[["MusicgenForConditionalGeneration",gh,J.Musicgen],["Phi3VForCausalLM",vh,J.Phi3V],["CLIPTextModelWithProjection",Up,J.EncoderOnly],["SiglipTextModel",kh,J.EncoderOnly],["JinaCLIPTextModel",dh,J.EncoderOnly],["ClapTextModelWithProjection",Fp,J.EncoderOnly],["ClapAudioModelWithProjection",Zp,J.EncoderOnly],["DacEncoderModel",Vp,J.EncoderOnly],["DacDecoderModel",jp,J.EncoderOnly],["MimiEncoderModel",Sh,J.EncoderOnly],["MimiDecoderModel",Lh,J.EncoderOnly],["SnacEncoderModel",Rh,J.EncoderOnly],["SnacDecoderModel",Oh,J.EncoderOnly],["Gemma3nForConditionalGeneration",Ii,J.ImageAudioTextToText],["Gemma4ForConditionalGeneration",d_,J.ImageAudioTextToText],["SupertonicForConditionalGeneration",Zh,J.Supertonic],["ChatterboxModel",Rp,J.Chatterbox],["VoxtralRealtimeForConditionalGeneration",Jh,J.VoxtralRealtime]];for(let[e,t,r]of A7)Ha.set(e,r),cs.set(t,e),Np.set(e,t);T2=new Map([["modnet",ss],["birefnet",ss],["isnet",ss],["ben",ss]]);for(let[e,t]of T2.entries())t.set(e,"PreTrainedModel"),Ha.set(e,J.EncoderOnly),Np.set(e,C);g7=new Set(T2.keys());Ha.set("PreTrainedModel",J.EncoderOnly);cs.set(C,"PreTrainedModel");Me={MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES:e2,MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES:t2,MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES:QN,MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES:YN,MODEL_FOR_MASKED_LM_MAPPING_NAMES:n2,MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES:s2,MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES:_2,MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES:ss,MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES:u2,MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES:d2,MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES:c2,MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES:l2,MODEL_FOR_MASK_GENERATION_MAPPING_NAMES:p2,MODEL_FOR_CTC_MAPPING_NAMES:h2,MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES:f2,MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES:E2,MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES:$2,MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES:S7,MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES:m2,MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES:I2,MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES:S2,MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES:L2,MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES:A2,MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES:g2,MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES:o2,MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES:H2,MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES:r2,MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES:JN,MODEL_FOR_CAUSAL_LM_MAPPING_NAMES:a2,MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES:i2};t7(Me);Pe=class{static MODEL_CLASS_MAPPINGS=null;static BASE_IF_FAIL=!1;static supports(e){if(!this.MODEL_CLASS_MAPPINGS)return!1;for(let t of this.MODEL_CLASS_MAPPINGS)if(t.has(e))return!0;return this.BASE_IF_FAIL}static async from_pretrained(e,{progress_callback:t=null,config:r=null,cache_dir:a=null,local_files_only:n=!1,revision:s="main",model_file_name:i=null,subfolder:o="onnx",device:H=null,dtype:_=null,use_external_data_format:c=null,session_options:l={}}={}){let d={progress_callback:t,config:r,cache_dir:a,local_files_only:n,revision:s,model_file_name:i,subfolder:o,device:H,dtype:_,use_external_data_format:c,session_options:l};if(d.config=await ls.from_pretrained(e,d),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);let{model_type:h}=d.config;for(let $ of this.MODEL_CLASS_MAPPINGS){let m=$.get(h);if(!m){for(let S of $.values())if(S[0]===h){m=S;break}if(!m)continue}return await Pp[m].from_pretrained(e,d)}if(this.BASE_IF_FAIL)return g7.has(h)||fe.warn(`Unknown model class "${h}", attempting to construct from base class.`),await C.from_pretrained(e,d);throw Error(`Unsupported model type: ${h}`)}},is=class extends Pe{static MODEL_CLASS_MAPPINGS=b2.map(e=>e[0]);static BASE_IF_FAIL=!0},dd=class extends Pe{static MODEL_CLASS_MAPPINGS=[Me.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES]},x2=class extends Pe{static MODEL_CLASS_MAPPINGS=[Me.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES]},tH=class extends Pe{static MODEL_CLASS_MAPPINGS=[Me.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES]},v2=class extends Pe{static MODEL_CLASS_MAPPINGS=[Me.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES]},y2=class extends Pe{static MODEL_CLASS_MAPPINGS=[Me.MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES]},D2=class extends Pe{static MODEL_CLASS_MAPPINGS=[Me.MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES]},C2=class extends Pe{static MODEL_CLASS_MAPPINGS=[Me.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES]},w2=class extends Pe{static MODEL_CLASS_MAPPINGS=[Me.MODEL_FOR_MASKED_LM_MAPPING_NAMES]},N2=class extends Pe{static MODEL_CLASS_MAPPINGS=[Me.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES]},B2=class extends Pe{static MODEL_CLASS_MAPPINGS=[Me.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES]},M2=class extends Pe{static MODEL_CLASS_MAPPINGS=[Me.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES]},pd=class extends Pe{static MODEL_CLASS_MAPPINGS=[Me.MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES]},hd=class extends Pe{static MODEL_CLASS_MAPPINGS=[Me.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES]},fd=class extends Pe{static MODEL_CLASS_MAPPINGS=[Me.MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES]},P2=class extends Pe{static MODEL_CLASS_MAPPINGS=[Me.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES]},k2=class extends Pe{static MODEL_CLASS_MAPPINGS=[Me.MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES]},b7=class extends Pe{static MODEL_CLASS_MAPPINGS=[Me.MODEL_FOR_MASK_GENERATION_MAPPING_NAMES]},R2=class extends Pe{static MODEL_CLASS_MAPPINGS=[Me.MODEL_FOR_CTC_MAPPING_NAMES]},O2=class extends Pe{static MODEL_CLASS_MAPPINGS=[Me.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES]},T7=class extends Pe{static MODEL_CLASS_MAPPINGS=[Me.MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES]},x7=class extends Pe{static MODEL_CLASS_MAPPINGS=[Me.MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES]},G2=class extends Pe{static MODEL_CLASS_MAPPINGS=[Me.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES]},v7=class extends Pe{static MODEL_CLASS_MAPPINGS=[Me.MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES]},F2=class extends Pe{static MODEL_CLASS_MAPPINGS=[Me.MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES]},Z2=class extends Pe{static MODEL_CLASS_MAPPINGS=[Me.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES]},y7=class extends Pe{static MODEL_CLASS_MAPPINGS=[Me.MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES]},D7=class extends Pe{static MODEL_CLASS_MAPPINGS=[Me.MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES]},U2=class extends Pe{static MODEL_CLASS_MAPPINGS=[Me.MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES]},C7=class extends Pe{static MODEL_CLASS_MAPPINGS=[Me.MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES]},w7=class extends Pe{static MODEL_CLASS_MAPPINGS=[Me.MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES]};rt=class extends zt{constructor({task:e,model:t,tokenizer:r=null,processor:a=null}){super(),this.task=e,this.model=t,this.tokenizer=r,this.processor=a}async dispose(){await this.model.dispose()}},W2=class extends rt{async _call(e,{top_k:t=1}={}){let r=this.tokenizer(e,{padding:!0,truncation:!0}),a=await this.model(r),{problem_type:n,id2label:s}=this.model.config,i=n==="multi_label_classification"?H=>H.sigmoid():H=>new j("float32",St(H.data),H.dims),o=[];for(let H of a.logits){let _=i(H),c=await _n(_,t),l=c[0].tolist(),h=c[1].tolist().map(($,m)=>({label:s?s[$]:`LABEL_${$}`,score:l[m]}));t===1?o.push(...h):o.push(h)}return Array.isArray(e)||t===1?o:o[0]}},K2=class extends rt{async _call(e,{ignore_labels:t=["O"],aggregation_strategy:r="none"}={}){if(r!=="none"&&r!=="simple")throw new Error(`Invalid aggregation_strategy: "${r}". Must be one of "none" or "simple".`);let a=Array.isArray(e),n=this.tokenizer(a?e:[e],{padding:!0,truncation:!0}),i=(await this.model(n)).logits,o=this.model.config.id2label,H=[];for(let _=0;_<i.dims[0];++_){let c=n.input_ids[_].tolist(),l=i[_],d=[];for(let h=0;h<l.dims[0];++h){let $=l[h],m=nt($.data)[1],S=o?o[m]:`LABEL_${m}`;if(t.includes(S))continue;let I=this.tokenizer.decode([c[h]],{skip_special_tokens:!0});if(I==="")continue;let g=St($.data);d.push({entity:S,score:g[m],index:h,word:I})}H.push(r==="simple"?B7(d,c,this.tokenizer):d)}return a?H:H[0]}};V2=class extends rt{async _call(e,t,{top_k:r=1}={}){let a=this.tokenizer(e,{text_pair:t,padding:!0,truncation:!0}),n=Array.isArray(e),{start_logits:s,end_logits:i}=await this.model(a),o=a.input_ids.tolist(),H=a.attention_mask.tolist(),{all_special_ids:_,sep_token_id:c}=this.tokenizer,l=[];for(let d=0;d<s.dims[0];++d){let h=o[d],$=h.findIndex(v=>v==c),m=s[d].tolist(),S=i[d].tolist();for(let v=1;v<m.length;++v)(H[d]==0||v<=$||_.findIndex(k=>k==h[v])!==-1)&&(m[v]=-1/0,S[v]=-1/0);let I=St(m).map((v,k)=>[v,k]),g=St(S).map((v,k)=>[v,k]);I[0][0]=0,g[0][0]=0;let T=xO(I,g).filter(v=>v[0][1]<=v[1][1]).map(v=>[v[0][1],v[1][1],v[0][0]*v[1][0]]).sort((v,k)=>k[2]-v[2]),x=[];for(let v=0;v<Math.min(T.length,r);++v){let[k,L,V]=T[v],K=h.slice(k,L+1),X=this.tokenizer.decode(K,{skip_special_tokens:!0});x.push({answer:X,score:V})}r===1?l.push(...x):l.push(x)}return n?l:l[0]}},j2=class extends rt{async _call(e,{top_k:t=5}={}){let{mask_token_id:r,mask_token:a}=this.tokenizer,n=this.tokenizer(e,{padding:!0,truncation:!0}),{logits:s}=await this.model(n),i=[],o=n.input_ids.tolist();for(let H=0;H<o.length;++H){let _=o[H],c=_.findIndex(m=>m==r);if(c===-1)throw Error(`Mask token (${a}) not found in text.`);let l=s[H][c],d=await _n(new j("float32",St(l.data),l.dims),t),h=d[0].tolist(),$=d[1].tolist();i.push($.map((m,S)=>{let I=_.slice();return I[c]=m,{score:h[S],token:Number(m),token_str:this.tokenizer.decode([m]),sequence:this.tokenizer.decode(I,{skip_special_tokens:!0})}}))}return Array.isArray(e)?i:i[0]}},Rc=class extends rt{_default_generation_config={max_new_tokens:256};_key="generated_text";async _call(e,t={}){Array.isArray(e)||(e=[e]),this.model.config.prefix&&(e=e.map(o=>this.model.config.prefix+o));let r=this.model.config.task_specific_params;r&&r[this.task]&&r[this.task].prefix&&(e=e.map(o=>r[this.task].prefix+o));let a=this.tokenizer,n={padding:!0,truncation:!0},s;this.task==="translation"&&"_build_translation_inputs"in a?s=a._build_translation_inputs(e,n,t):s=a(e,n);let i=await this.model.generate({...s,...this._default_generation_config,...t});return a.batch_decode(i,{skip_special_tokens:!0}).map(o=>({[this._key]:o}))}},q2=class extends Rc{_key="summary_text"},X2=class extends Rc{_key="translation_text"};z2=class extends rt{_default_generation_config={max_new_tokens:256};async _call(e,t={}){let{add_special_tokens:r,return_full_text:a,tools:n,documents:s,chat_template:i,tokenizer_encode_kwargs:o,...H}=t,_=!1,c=!1,l=r??(this.tokenizer.add_bos_token||this.tokenizer.add_eos_token)??!1,d=o,h;if(typeof e=="string")h=e=[e];else if(Array.isArray(e)&&e.every(x=>typeof x=="string"))_=!0,h=e;else{if(wS(e))e=[e];else if(Array.isArray(e)&&e.every(wS))_=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");c=!0;let x={tokenize:!1,add_generation_prompt:!0,...It({tools:n,documents:s,chat_template:i},["tools","documents","chat_template"]),...d};h=e.map(v=>this.tokenizer.apply_chat_template(v,x)),l=!1,d=void 0}let $=c?!1:a??!0;this.tokenizer.padding_side="left";let m=this.tokenizer(h,{add_special_tokens:l,padding:!0,truncation:!0,...d}),S=await this.model.generate({...m,...this._default_generation_config,...H}),I=this.tokenizer.batch_decode(S,{skip_special_tokens:!0}),g;!$&&m.input_ids.dims.at(-1)>0&&(g=this.tokenizer.batch_decode(m.input_ids,{skip_special_tokens:!0}).map(x=>x.length));let T=Array.from({length:e.length},x=>[]);for(let x=0;x<I.length;++x){let v=Math.floor(x/S.dims[0]*e.length);g&&(I[x]=I[x].slice(g[v])),T[v].push({generated_text:c?[...e[v],{role:"assistant",content:I[x]}]:I[x]})}return!_&&T.length===1?T[0]:T}},J2=class extends rt{constructor(e){super(e),this.label2id=Object.fromEntries(Object.entries(this.model.config.label2id).map(([t,r])=>[t.toLowerCase(),r])),this.entailment_id=this.label2id.entailment,this.entailment_id===void 0&&(fe.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&&(fe.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0)}async _call(e,t,{hypothesis_template:r="This example is {}.",multi_label:a=!1}={}){let n=Array.isArray(e);n||(e=[e]),Array.isArray(t)||(t=[t]);let s=t.map(H=>r.replace("{}",H)),i=a||t.length===1,o=[];for(let H of e){let _=[];for(let d of s){let h=this.tokenizer(H,{text_pair:d,padding:!0,truncation:!0}),$=await this.model(h);i?_.push([$.logits.data[this.contradiction_id],$.logits.data[this.entailment_id]]):_.push($.logits.data[this.entailment_id])}let l=(i?_.map(d=>St(d)[1]):St(_)).map((d,h)=>[d,h]).sort((d,h)=>h[0]-d[0]);o.push({sequence:H,labels:l.map(d=>t[d[1]]),scores:l.map(d=>d[0])})}return n?o:o[0]}},Q2=class extends rt{async _call(e,{top_k:t=5}={}){let r=this.processor.feature_extractor.config.sampling_rate,a=await os(e,r),n=this.model.config.id2label,s=[];for(let i of a){let o=await this.processor(i),_=(await this.model(o)).logits[0],c=await _n(new j("float32",St(_.data),_.dims),t),l=c[0].tolist(),h=c[1].tolist().map(($,m)=>({label:n?n[$]:`LABEL_${$}`,score:l[m]}));s.push(h)}return Array.isArray(e)?s:s[0]}},Y2=class extends rt{async _call(e,t,{hypothesis_template:r="This is a sound of {}."}={}){let a=!Array.isArray(e);a&&(e=[e]);let n=t.map(_=>r.replace("{}",_)),s=this.tokenizer(n,{padding:!0,truncation:!0}),i=this.processor.feature_extractor.config.sampling_rate,o=await os(e,i),H=[];for(let _ of o){let c=await this.processor(_),l=await this.model({...s,...c}),d=St(l.logits_per_audio.data);H.push([...d].map((h,$)=>({score:h,label:t[$]})))}return a?H[0]:H}},eB=class extends rt{_default_generation_config={};async _call(e,t={}){switch(t={...this._default_generation_config,...t},this.model.config.model_type){case"whisper":case"lite-whisper":return this._call_whisper(e,t);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":case"parakeet_ctc":return this._call_wav2vec2(e,t);case"moonshine":return this._call_moonshine(e,t);case"cohere_asr":return this._call_cohere_asr(e,t);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(e,t){t.language&&fe.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),t.task&&fe.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');let r=!Array.isArray(e),a=r?[e]:e,n=this.processor.feature_extractor.config.sampling_rate,s=await os(a,n),i=[];for(let o of s){let H=await this.processor(o),c=(await this.model(H)).logits[0],l=[];for(let h of c)l.push(nt(h.data)[1]);let d=this.tokenizer.decode(l,{skip_special_tokens:!0}).trim();i.push({text:d})}return r?i[0]:i}async _call_whisper(e,t){let r=t.return_timestamps??!1,a=t.chunk_length_s??0,n=t.force_full_sequences??!1,s=t.stride_length_s??null,i={...t};r==="word"&&(i.return_token_timestamps=!0,i.return_timestamps=!0);let o=!Array.isArray(e),H=o?[e]:e,_=this.processor.feature_extractor.config,c=_.chunk_length/this.model.config.max_source_positions,l=_.hop_length,d=_.sampling_rate,h=await os(H,d),$=[];for(let m of h){let S=[];if(a>0){if(s===null)s=a/6;else if(a<=s)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");let T=d*a,x=d*s,v=T-2*x,k=0;for(;;){let L=k+T,V=m.subarray(k,L),K=await this.processor(V),X=k===0,Q=L>=m.length;if(S.push({stride:[V.length,X?0:x,Q?0:x],input_features:K.input_features,is_last:Q}),Q)break;k+=v}}else S=[{stride:[m.length,0,0],input_features:(await this.processor(m)).input_features,is_last:!0}];for(let T of S){i.num_frames=Math.floor(T.stride[0]/l);let x=await this.model.generate({inputs:T.input_features,...i});if(r==="word"){let v=x.sequences.tolist()[0],k=x.token_timestamps.tolist()[0],L=this.tokenizer.timestamp_begin,V=Math.max(v.findIndex(K=>Number(K)>=L),0);T.tokens=v.slice(V),T.token_timestamps=k.slice(V).map(K=>ti(K,2))}else T.tokens=x[0].tolist();T.stride=T.stride.map(v=>v/d)}let[I,g]=this.tokenizer._decode_asr(S,{time_precision:c,return_timestamps:r,force_full_sequences:n});$.push({text:I,...g})}return o?$[0]:$}async _call_moonshine(e,t){let r=!Array.isArray(e),a=r?[e]:e,n=this.processor.feature_extractor.config.sampling_rate,s=await os(a,n),i=[];for(let o of s){let H=await this.processor(o),_=Math.floor(o.length/n)*6,c=await this.model.generate({max_new_tokens:_,...t,...H}),l=this.processor.batch_decode(c,{skip_special_tokens:!0})[0];i.push({text:l})}return r?i[0]:i}async _call_cohere_asr(e,t){let r=!Array.isArray(e),a=r?[e]:e,n=this.processor.feature_extractor,s=n.config.sampling_rate,i=await os(a,s),o=t.language??"en",H=this.processor.get_decoder_prompt_ids(o),_=[];for(let c of i){let l=n.split_audio(c),d=[];for(let $ of l){let m=await this.processor($),S=await this.model.generate({...m,decoder_input_ids:H,...t}),I=this.tokenizer.decode(S[0].tolist(),{skip_special_tokens:!0}).trim();d.push(I)}let h=this.processor.constructor.join_chunks(d,o);_.push({text:h})}return r?_[0]:_}},tB=class extends rt{DEFAULT_VOCODER_ID="Xenova/speecht5_hifigan";constructor(e){super(e),this.vocoder=e.vocoder??null}async _prepare_speaker_embeddings(e,t){if((typeof e=="string"||e instanceof URL)&&(e=new Float32Array(await(await ge.fetch(e)).arrayBuffer())),e instanceof Float32Array)e=new j("float32",e,[e.length]);else if(!(e instanceof j))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");if(t>1){if(e.dims[0]===1)e=e.repeat(t,1);else if(e.dims[0]!==t)throw new Error(`Expected speaker embeddings batch size to be 1 or ${t}, but got ${e.dims[0]}.`)}return e}_postprocess_waveform(e,t,r,a=null){let n=t.data,[s,i]=t.dims,o=a?a.data:null,H=[];for(let _=0;_<s;++_){let c=o?Math.min(Math.ceil(o[_]),i):i,l=_*i;H.push(new pg(n.slice(l,l+c),r))}return Array.isArray(e)?H:H[0]}async _call(e,t){return this.processor?this._call_text_to_spectrogram(e,t):this.model.config.model_type==="supertonic"?this._call_supertonic(e,t):this._call_text_to_waveform(e)}async _call_supertonic(e,{speaker_embeddings:t,num_inference_steps:r,speed:a}){if(!t)throw new Error("Speaker embeddings must be provided for Supertonic models.");let{sampling_rate:n,style_dim:s}=this.model.config,i=this.tokenizer(e,{padding:!0,truncation:!0}),o=i.input_ids.dims[0];t=await this._prepare_speaker_embeddings(t,o),t=t.view(o,-1,s);let{waveform:H,durations:_}=await this.model.generate_speech({...i,style:t,num_inference_steps:r,speed:a});return this._postprocess_waveform(e,H,n,_)}async _call_text_to_waveform(e){let t=this.tokenizer(e,{padding:!0,truncation:!0}),{waveform:r}=await this.model(t),a=this.model.config.sampling_rate;return this._postprocess_waveform(e,r,a)}async _call_text_to_spectrogram(e,{speaker_embeddings:t}){this.vocoder||(fe.info("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await is.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"}));let{input_ids:r}=this.tokenizer(e,{padding:!0,truncation:!0}),a=r.dims[0];t=await this._prepare_speaker_embeddings(t,a),t=t.view(a,-1);let{waveform:n}=await this.model.generate_speech(r,t,{vocoder:this.vocoder}),s=this.processor.feature_extractor.config.sampling_rate;return this._postprocess_waveform(e,n,s)}},rB=class extends rt{async _call(e,t={}){let r=Array.isArray(e),a=await gr(e),{pixel_values:n}=await this.processor(a),s=[];for(let i of n){i.dims=[1,...i.dims];let o=await this.model.generate({inputs:i,...t}),H=this.tokenizer.batch_decode(o,{skip_special_tokens:!0}).map(_=>({generated_text:_.trim()}));s.push(H)}return r?s:s[0]}},aB=class extends rt{async _call(e,{top_k:t=5}={}){let r=await gr(e),{pixel_values:a}=await this.processor(r),n=await this.model({pixel_values:a}),{id2label:s}=this.model.config,i=[];for(let o of n.logits){let H=await _n(new j("float32",St(o.data),o.dims),t),_=H[0].tolist(),l=H[1].tolist().map((d,h)=>({label:s?s[d]:`LABEL_${d}`,score:_[h]}));i.push(l)}return Array.isArray(e)?i:i[0]}},NS={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"},rf=class extends rt{async _call(e,{threshold:t=.5,mask_threshold:r=.5,overlap_mask_area_threshold:a=.8,label_ids_to_fuse:n=null,target_sizes:s=null,subtask:i=null}={}){if(Array.isArray(e)&&e.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");let H=await gr(e),_=H.map(I=>[I.height,I.width]),c=await this.processor(H),{inputNames:l,outputNames:d}=this.model.sessions.model;if(!l.includes("pixel_values")){if(l.length!==1)throw Error(`Expected a single input name, but got ${l.length} inputs: ${l}.`);let I=l[0];if(I in c)throw Error(`Input name ${I} already exists in the inputs.`);c[I]=c.pixel_values}let h=await this.model(c),$=null;if(i!==null)$=NS[i];else if(this.processor.image_processor){for(let[I,g]of Object.entries(NS))if(g in this.processor.image_processor){$=this.processor.image_processor[g].bind(this.processor.image_processor),i=I;break}}let m=this.model.config.id2label,S=[];if(i)if(i==="panoptic"||i==="instance"){let I=$(h,t,r,a,n,s??_)[0],g=I.segmentation;for(let T of I.segments_info){let x=new Uint8ClampedArray(g.data.length);for(let k=0;k<g.data.length;++k)g.data[k]===T.id&&(x[k]=255);let v=new Xt(x,g.dims[1],g.dims[0],1);S.push({score:T.score,label:m[T.label_id],mask:v})}}else if(i==="semantic"){let{segmentation:I,labels:g}=$(h,s??_)[0];for(let T of g){let x=new Uint8ClampedArray(I.data.length);for(let k=0;k<I.data.length;++k)I.data[k]===T&&(x[k]=255);let v=new Xt(x,I.dims[1],I.dims[0],1);S.push({score:null,label:m[T],mask:v})}}else throw Error(`Subtask ${i} not supported.`);else{let g=h[d[0]];for(let T=0;T<_.length;++T){let x=_[T],v=g[T];v.data.some(L=>L<-1e-5||L>1+1e-5)&&v.sigmoid_();let k=await Xt.fromTensor(v.mul_(255).to("uint8")).resize(x[1],x[0]);S.push({label:null,score:null,mask:k})}}return S}},nB=class extends rf{async _call(e,t={}){let r=await gr(e),a=await super._call(e,t),n=r.map((s,i)=>{let o=s.clone();return o.putAlpha(a[i].mask),o});return Array.isArray(e)?n:n[0]}},sB=class extends rt{async _call(e,t,{hypothesis_template:r="This is a photo of {}"}={}){let a=Array.isArray(e),n=await gr(e),s=t.map(l=>r.replace("{}",l)),i=this.tokenizer(s,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:o}=await this.processor(n),H=await this.model({...i,pixel_values:o}),_=this.model.config.model_type==="siglip"?l=>l.sigmoid().data:l=>St(l.data),c=[];for(let l of H.logits_per_image){let h=[..._(l)].map(($,m)=>({score:$,label:t[m]}));h.sort(($,m)=>m.score-$.score),c.push(h)}return a?c:c[0]}},iB=class extends rt{async _call(e,{threshold:t=.9,percentage:r=!1}={}){let a=Array.isArray(e);if(a&&e.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");let n=await gr(e),s=r?null:n.map(d=>[d.height,d.width]),{pixel_values:i,pixel_mask:o}=await this.processor(n),H=await this.model({pixel_values:i,pixel_mask:o}),_=this.processor.image_processor.post_process_object_detection(H,t,s),{id2label:c}=this.model.config,l=_.map(d=>d.boxes.map((h,$)=>({score:d.scores[$],label:c[d.classes[$]],box:Ed(h,!r)})));return a?l:l[0]}},oB=class extends rt{async _call(e,t,{threshold:r=.1,top_k:a=null,percentage:n=!1}={}){let s=Array.isArray(e),i=await gr(e),o=this.tokenizer(t,{padding:!0,truncation:!0}),H=await this.processor(i),_=[];for(let c=0;c<i.length;++c){let l=i[c],d=n?null:[[l.height,l.width]],h=H.pixel_values[c].unsqueeze_(0),$=await this.model({...o,pixel_values:h}),m;if("post_process_grounded_object_detection"in this.processor){let S=this.processor.post_process_grounded_object_detection($,o.input_ids,{box_threshold:r,text_threshold:r,target_sizes:d})[0];m=S.boxes.map((I,g)=>({score:S.scores[g],label:S.labels[g],box:Ed(I,!n)}))}else{let S=this.processor.image_processor.post_process_object_detection($,r,d,!0)[0];m=S.boxes.map((I,g)=>({score:S.scores[g],label:t[S.classes[g]],box:Ed(I,!n)}))}m.sort((S,I)=>I.score-S.score),a!==null&&(m=m.slice(0,a)),_.push(m)}return s?_:_[0]}},HB=class extends rt{_default_generation_config={max_new_tokens:256};async _call(e,t,r={}){if(Array.isArray(e)){if(e.length!==1)throw Error("Document Question Answering pipeline currently only supports a batch size of 1.");e=e[0]}let a=(await gr(e))[0],{pixel_values:n}=await this.processor(a),s=`<s_docvqa><s_question>${t}</s_question><s_answer>`,i=this.tokenizer(s,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,o=await this.model.generate({inputs:n,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:i,...this._default_generation_config,...r}),_=this.tokenizer.batch_decode(o)[0].match(/<s_answer>(.*?)<\/s_answer>/),c=null;return _&&_.length>=2&&(c=_[1].trim()),[{answer:c}]}},_B=class extends rt{async _call(e){let t=await gr(e),r=await this.processor(t),a=await this.model(r),n=[];for(let s of a.reconstruction){let i=s.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");n.push(Xt.fromTensor(i))}return Array.isArray(e)?n:n[0]}},cB=class extends rt{async _call(e){let t=await gr(e),r=await this.processor(t),{predicted_depth:a}=await this.model(r),n=[];for(let s=0;s<t.length;++s){let i=a[s],[o,H]=i.dims.slice(-2),[_,c]=t[s].size,l=(await dr(i.view(1,1,o,H),{size:[c,_],mode:"bilinear"})).view(c,_),d=l.min().item(),h=l.max().item(),$=l.sub(d).div_(h-d).mul_(255).to("uint8").unsqueeze(0),m=Xt.fromTensor($);n.push({predicted_depth:l,depth:m})}return Array.isArray(e)?n:n[0]}},lB=class extends rt{async _call(e,{pooling:t="none",normalize:r=!1,quantize:a=!1,precision:n="binary"}={}){let s=this.tokenizer(e,{padding:!0,truncation:!0}),i=await this.model(s),o=i.last_hidden_state??i.logits??i.token_embeddings;switch(t){case"none":break;case"mean":o=HA(o,s.attention_mask);break;case"first_token":case"cls":o=o.slice(null,0);break;case"last_token":case"eos":o=o.slice(null,-1);break;default:throw Error(`Pooling method '${t}' not supported.`)}return r&&(o=o.normalize(2,-1)),a&&(o=cA(o,n)),o}},uB=class extends rt{async _call(e,{pool:t=null}={}){let r=await gr(e),{pixel_values:a}=await this.processor(r),n=await this.model({pixel_values:a}),s;if(t){if(!("pooler_output"in n))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");s=n.pooler_output}else s=n.last_hidden_state??n.logits??n.image_embeds;return s}},mH=Object.freeze({"text-classification":{pipeline:W2,model:dd,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{pipeline:K2,model:x2,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{pipeline:V2,model:N2,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{pipeline:j2,model:w2,default:{model:"onnx-community/ettin-encoder-32m-ONNX",dtype:"fp32"},type:"text"},summarization:{pipeline:q2,model:tH,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{pipeline:X2,model:tH,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{pipeline:Rc,model:tH,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{pipeline:z2,model:C2,default:{model:"onnx-community/Qwen3-0.6B-ONNX",dtype:"q4"},type:"text"},"zero-shot-classification":{pipeline:J2,model:dd,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:Q2,model:O2,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{pipeline:Y2,model:is,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{pipeline:eB,model:[v2,R2],default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{pipeline:tB,model:[D2,y2],default:{model:"onnx-community/Supertonic-TTS-ONNX",dtype:"fp32"},type:"text"},"image-to-text":{pipeline:rB,model:B2,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:aB,model:M2,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:rf,model:[pd,hd,fd],default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"background-removal":{pipeline:nB,model:[pd,hd,fd],default:{model:"Xenova/modnet"},type:"image"},"zero-shot-image-classification":{pipeline:sB,model:is,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:iB,model:P2,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{pipeline:oB,model:k2,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{pipeline:HB,model:G2,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:_B,model:F2,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:cB,model:Z2,default:{model:"onnx-community/depth-anything-v2-small"},type:"image"},"feature-extraction":{pipeline:lB,model:is,default:{model:"onnx-community/all-MiniLM-L6-v2-ONNX",dtype:"fp32"},type:"text"},"image-feature-extraction":{pipeline:uB,model:[U2,is],default:{model:"onnx-community/dinov3-vits16-pretrain-lvd1689m-ONNX",dtype:"fp32"},type:"image"}}),dB=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});P7=e=>e>=19968&&e<=40959||e>=13312&&e<=19903||e>=131072&&e<=173791||e>=173824&&e<=177983||e>=177984&&e<=178207||e>=178208&&e<=183983||e>=63744&&e<=64255||e>=194560&&e<=195103,hB=class{put(e){throw Error("Not implemented")}end(){throw Error("Not implemented")}},BS=Ie.IS_PROCESS_AVAILABLE?e=>process.stdout.write(e):e=>console.log(e),fB=class extends hB{constructor(e,{skip_prompt:t=!1,callback_function:r=null,token_callback_function:a=null,skip_special_tokens:n=!0,decode_kwargs:s={},...i}={}){super(),this.tokenizer=e,this.skip_prompt=t,this.callback_function=r??BS,this.token_callback_function=a,this.decode_kwargs={skip_special_tokens:n,...s,...i},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0,this.special_ids=new Set(this.tokenizer.all_special_ids.map(BigInt))}put(e){if(e.length>1)throw Error("TextStreamer only supports batch size of 1");let t=this.next_tokens_are_prompt;if(t&&(this.next_tokens_are_prompt=!1,this.skip_prompt))return;let r=e[0];if(this.token_callback_function?.(r),r.length===1&&this.special_ids.has(r[0])){if(this.decode_kwargs.skip_special_tokens)return;if(this.token_cache.length>0){let o=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len);this.on_finalized_text(o,!1),this.token_cache=[],this.print_len=0}let s=this.tokenizer.decode(r,this.decode_kwargs);this.on_finalized_text(s,!1);return}this.token_cache=$r(this.token_cache,r);let a=this.tokenizer.decode(this.token_cache,this.decode_kwargs),n;t||a.endsWith(`
44
- `)?(n=a.slice(this.print_len),this.token_cache=[],this.print_len=0):a.length>0&&P7(a.charCodeAt(a.length-1))?(n=a.slice(this.print_len),this.print_len+=n.length):(n=a.slice(this.print_len,a.lastIndexOf(" ")+1),this.print_len+=n.length),this.on_finalized_text(n,!1)}end(){let e;this.token_cache.length>0?(e=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):e="",this.next_tokens_are_prompt=!0,this.on_finalized_text(e,!0)}on_finalized_text(e,t){e.length>0&&this.callback_function?.(e),t&&this.callback_function===BS&&Ie.IS_PROCESS_AVAILABLE&&this.callback_function?.(`
45
- `)}},k7=class extends fB{constructor(e,{skip_prompt:t=!1,callback_function:r=null,token_callback_function:a=null,on_chunk_start:n=null,on_chunk_end:s=null,on_finalize:i=null,time_precision:o=.02,skip_special_tokens:H=!0,decode_kwargs:_={}}={}){super(e,{skip_prompt:t,skip_special_tokens:H,callback_function:r,token_callback_function:a,decode_kwargs:_}),this.timestamp_begin=e.timestamp_begin,this.on_chunk_start=n,this.on_chunk_end=s,this.on_finalize=i,this.time_precision=o,this.waiting_for_timestamp=!1}put(e){if(e.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");let t=e[0];if(t.length===1){let r=Number(t[0])-this.timestamp_begin;if(r>=0){let a=r*this.time_precision;this.waiting_for_timestamp?this.on_chunk_end?.(a):this.on_chunk_start?.(a),this.waiting_for_timestamp=!this.waiting_for_timestamp,this.token_callback_function?.(t);return}}return super.put(e)}end(){super.end(),this.on_finalize?.()}},af=class{constructor(e,t){this.image=e,this.timestamp=t}},EB=class{constructor(e,t){e.length>0&&e[0]instanceof Xt&&(e=e.map((r,a)=>new af(r,(a+1)/(e.length+1)*t))),this.frames=e,this.duration=t}get width(){return this.frames[0].image.width}get height(){return this.frames[0].image.height}get fps(){return this.frames.length/this.duration}};K7=Object.keys(oi);j7=class{static async get_files(e,t={}){return Bi(e,t)}static async get_pipeline_files(e,t,r={}){return Mi(e,t,r)}static async get_model_files(e,t={}){return wp(e,t)}static async get_tokenizer_files(e){return zd(e)}static async get_processor_files(e){return pB(e)}static async get_available_dtypes(e,t={}){return V7(e,t)}static async is_cached(e,t={}){return O7(e,t)}static async is_cached_files(e,t={}){return G7(e,t)}static async is_pipeline_cached(e,t,r={}){return F7(e,t,r)}static async is_pipeline_cached_files(e,t,r={}){return Z7(e,t,r)}static async get_file_metadata(e,t,r={}){return sn(e,t,r)}static async clear_cache(e,t={}){return U7(e,t)}static async clear_pipeline_cache(e,t,r={}){return W7(e,t,r)}};});var oU={};hl(oU,{Runtime:()=>wa,YuktAI:()=>iU,YuktAIWrapper:()=>Gc,aiPlugin:()=>ki,default:()=>Gc,voicePlugin:()=>Ri,wcag:()=>Jt,wcagPlugin:()=>Jt});module.exports=B3(oU);function p1(){let e=window;return e.Rewriter||e.ai?.rewriter||null}async function fl(){try{let e=p1();if(!e)return!1;if(typeof e.availability=="function"){let t=await e.availability();return t==="readily"||t==="available"||t==="downloadable"}return typeof e.capabilities=="function"?(await e.capabilities())?.available!=="no":typeof e.create=="function"}catch{return!1}}async function M3(e){if(!e||e.trim().length<20)return{success:!1,original:e,rewritten:e,error:"Text too short"};try{let t=p1();if(!t)throw new Error("Rewriter API not available");let r=await t.create({tone:"more-casual",format:"plain-text",length:"as-is",outputLanguage:"en"}),a=await r.rewrite(e,{context:"Rewrite this text in simple plain English. Use short sentences. Avoid jargon. Make it easy to understand for everyone."});return r.destroy(),{success:!0,original:e,rewritten:a.trim()}}catch(t){return{success:!1,original:e,rewritten:e,error:t instanceof Error?t.message:"Rewrite failed"}}}async function h1(){if(!await fl())return{fixed:0,error:"Chrome Built-in AI Rewriter not available. Enable via chrome://flags."};let t=document.querySelectorAll("p, h1, h2, h3, h4, h5, h6, li, blockquote, td, th, label, figcaption"),r=0;for(let a of t){let n=a.innerText?.trim();if(!n||n.length<20||a.closest("[data-yuktai-panel]"))continue;let s=await M3(n);s.success&&s.rewritten!==n&&(a.dataset.yuktaiOriginal=n,a.innerText=s.rewritten,r++)}return{fixed:r}}function f1(){let e=document.querySelectorAll("[data-yuktai-original]");for(let t of e){let r=t.dataset.yuktaiOriginal;r&&(t.innerText=r,delete t.dataset.yuktaiOriginal)}}var E1="yuktai-summary-box";function $1(){let e=window;return e.Summarizer||e.ai?.summarizer||null}async function El(){try{let e=$1();if(!e)return!1;if(typeof e.availability=="function"){let t=await e.availability();return t==="readily"||t==="available"||t==="downloadable"}return typeof e.capabilities=="function"?(await e.capabilities())?.available!=="no":typeof e.create=="function"}catch{return!1}}function P3(){let e=document.querySelectorAll("p, h1, h2, h3, h4, h5, h6, li, blockquote, article, section"),t=[];for(let r of e){if(r.closest("[data-yuktai-panel]"))continue;let a=window.getComputedStyle(r);if(a.display==="none"||a.visibility==="hidden")continue;let n=r.innerText?.trim();n&&n.length>10&&t.push(n)}return t.join(" ").slice(0,5e3)}async function m1(){if(!await El())return{success:!1,summary:"",error:"Chrome Built-in AI Summarizer not available. Enable via chrome://flags."};let t=P3();if(!t||t.length<100)return{success:!1,summary:"",error:"Not enough text on this page to summarise."};try{let r=$1();if(!r)throw new Error("Summarizer API not available");let a=await r.create({type:"tl;dr",format:"plain-text",length:"short",outputLanguage:"en"}),n=await a.summarize(t,{context:"Summarise this page in 2-3 simple sentences for a screen reader user who wants to know if this page is relevant to them."});return a.destroy(),k3(n.trim()),{success:!0,summary:n.trim()}}catch(r){return{success:!1,summary:"",error:r instanceof Error?r.message:"Summary failed"}}}function k3(e){Ji();let t=document.createElement("div");t.id=E1,t.setAttribute("data-yuktai-panel","true"),t.setAttribute("role","region"),t.setAttribute("aria-label","Page summary by yuktai"),t.style.cssText=`
6
+ Q: ${e}`,o=await n.prompt(s);return n?.destroy&&n.destroy(),{success:!0,answer:o?.trim()||"No answer found."}}catch(t){return{success:!1,answer:"",error:t instanceof Error?t.message:"Error occurred"}}}var ke=gt(()=>{"use strict"});var ta={};Ce(ta,{Runtime:()=>I,YuktAI:()=>ea,YuktAIWrapper:()=>re,aiPlugin:()=>K,default:()=>re,voicePlugin:()=>Y,wcag:()=>T,wcagPlugin:()=>T});module.exports=bt(ta);function Re(){let e=window;return e.Rewriter||e.ai?.rewriter||null}async function ue(){try{let e=Re();if(!e)return!1;if(typeof e.availability=="function"){let t=await e.availability();return t==="readily"||t==="available"||t==="downloadable"}return typeof e.capabilities=="function"?(await e.capabilities())?.available!=="no":typeof e.create=="function"}catch{return!1}}async function yt(e){if(!e||e.trim().length<20)return{success:!1,original:e,rewritten:e,error:"Text too short"};try{let t=Re();if(!t)throw new Error("Rewriter API not available");let a=await t.create({tone:"more-casual",format:"plain-text",length:"as-is",outputLanguage:"en"}),i=await a.rewrite(e,{context:"Rewrite this text in simple plain English. Use short sentences. Avoid jargon. Make it easy to understand for everyone."});return a.destroy(),{success:!0,original:e,rewritten:i.trim()}}catch(t){return{success:!1,original:e,rewritten:e,error:t instanceof Error?t.message:"Rewrite failed"}}}async function Pe(){if(!await ue())return{fixed:0,error:"Chrome Built-in AI Rewriter not available. Enable via chrome://flags."};let t=document.querySelectorAll("p, h1, h2, h3, h4, h5, h6, li, blockquote, td, th, label, figcaption"),a=0;for(let i of t){let n=i.innerText?.trim();if(!n||n.length<20||i.closest("[data-yuktai-panel]"))continue;let s=await yt(n);s.success&&s.rewritten!==n&&(i.dataset.yuktaiOriginal=n,i.innerText=s.rewritten,a++)}return{fixed:a}}function ze(){let e=document.querySelectorAll("[data-yuktai-original]");for(let t of e){let a=t.dataset.yuktaiOriginal;a&&(t.innerText=a,delete t.dataset.yuktaiOriginal)}}var Ie="yuktai-summary-box";function He(){let e=window;return e.Summarizer||e.ai?.summarizer||null}async function pe(){try{let e=He();if(!e)return!1;if(typeof e.availability=="function"){let t=await e.availability();return t==="readily"||t==="available"||t==="downloadable"}return typeof e.capabilities=="function"?(await e.capabilities())?.available!=="no":typeof e.create=="function"}catch{return!1}}function xt(){let e=document.querySelectorAll("p, h1, h2, h3, h4, h5, h6, li, blockquote, article, section"),t=[];for(let a of e){if(a.closest("[data-yuktai-panel]"))continue;let i=window.getComputedStyle(a);if(i.display==="none"||i.visibility==="hidden")continue;let n=a.innerText?.trim();n&&n.length>10&&t.push(n)}return t.join(" ").slice(0,5e3)}async function We(){if(!await pe())return{success:!1,summary:"",error:"Chrome Built-in AI Summarizer not available. Enable via chrome://flags."};let t=xt();if(!t||t.length<100)return{success:!1,summary:"",error:"Not enough text on this page to summarise."};try{let a=He();if(!a)throw new Error("Summarizer API not available");let i=await a.create({type:"tl;dr",format:"plain-text",length:"short",outputLanguage:"en"}),n=await i.summarize(t,{context:"Summarise this page in 2-3 simple sentences for a screen reader user who wants to know if this page is relevant to them."});return i.destroy(),ht(n.trim()),{success:!0,summary:n.trim()}}catch(a){return{success:!1,summary:"",error:a instanceof Error?a.message:"Summary failed"}}}function ht(e){Q();let t=document.createElement("div");t.id=Ie,t.setAttribute("data-yuktai-panel","true"),t.setAttribute("role","region"),t.setAttribute("aria-label","Page summary by yuktai"),t.style.cssText=`
46
7
  position: fixed;
47
8
  top: 0;
48
9
  left: 0;
@@ -59,11 +20,11 @@ ${this.boa_token}${this.audio_token.repeat(this._compute_audio_num_tokens(i[H++]
59
20
  justify-content: space-between;
60
21
  gap: 12px;
61
22
  box-shadow: 0 2px 8px rgba(0,0,0,0.15);
62
- `;let r=document.createElement("p");r.style.cssText="margin: 0; flex: 1;",r.textContent=`\u{1F4CB} Page summary: ${e}`;let a=document.createElement("button");a.textContent="\xD7",a.setAttribute("aria-label","Close page summary"),a.style.cssText=`
23
+ `;let a=document.createElement("p");a.style.cssText="margin: 0; flex: 1;",a.textContent=`\u{1F4CB} Page summary: ${e}`;let i=document.createElement("button");i.textContent="\xD7",i.setAttribute("aria-label","Close page summary"),i.style.cssText=`
63
24
  background: none; border: none; color: #ffffff;
64
25
  font-size: 20px; cursor: pointer; padding: 0 4px;
65
26
  line-height: 1; flex-shrink: 0;
66
- `,a.addEventListener("click",Ji),t.appendChild(r),t.appendChild(a),document.body.prepend(t)}function Ji(){let e=document.getElementById(E1);e&&e.remove()}var Yi=[{code:"en",label:"English"},{code:"hi",label:"Hindi"},{code:"es",label:"Spanish"},{code:"fr",label:"French"},{code:"de",label:"German"},{code:"it",label:"Italian"},{code:"pt",label:"Portuguese"},{code:"nl",label:"Dutch"},{code:"pl",label:"Polish"},{code:"ru",label:"Russian"},{code:"ja",label:"Japanese"},{code:"ko",label:"Korean"},{code:"zh",label:"Chinese"},{code:"ar",label:"Arabic"},{code:"tr",label:"Turkish"},{code:"vi",label:"Vietnamese"},{code:"bn",label:"Bengali"},{code:"id",label:"Indonesian"}],Qi="en";function R3(){let e=window;return e.Translator||e.translation||null}async function O3(e){try{let t=window;if(!R3())return!1;if(t.Translator&&typeof t.Translator.availability=="function")try{let a=await t.Translator.availability({sourceLanguage:"en",targetLanguage:e});return a==="readily"||a==="available"||a==="downloadable"||a==="after-download"}catch{}return t.Translator&&typeof t.Translator.canTranslate=="function"?await t.Translator.canTranslate({sourceLanguage:"en",targetLanguage:e})!=="no":t.translation&&typeof t.translation.canTranslate=="function"?await t.translation.canTranslate({sourceLanguage:"en",targetLanguage:e})!=="no":!1}catch{return!1}}async function G3(e){let t=window,r={sourceLanguage:"en",targetLanguage:e};if(t.Translator&&typeof t.Translator.create=="function")return await t.Translator.create(r);if(t.translation&&typeof t.translation.createTranslator=="function")return await t.translation.createTranslator(r);throw new Error("Translation API not available")}async function I1(e){if(e===Qi)return{success:!0,language:e,fixed:0};if(e==="en")return $l(),Qi="en",{success:!0,language:"en",fixed:0};if(!await O3(e))return{success:!1,language:e,fixed:0,error:`Translation to ${e} not available. Enable via chrome://flags.`};try{let r=await G3(e),a=document.querySelectorAll("p, h1, h2, h3, h4, h5, h6, li, blockquote, td, th, label, figcaption, span, a"),n=0;for(let s of a){if(s.closest("[data-yuktai-panel]")||s.children.length>0)continue;let i=s.innerText?.trim();if(!i||i.length<2)continue;s.dataset.yuktaiTranslationOriginal||(s.dataset.yuktaiTranslationOriginal=i);let o=await r.translate(i);o&&o!==i&&(s.innerText=o,n++)}return typeof r.destroy=="function"&&r.destroy(),Qi=e,{success:!0,language:e,fixed:n}}catch(r){return{success:!1,language:e,fixed:0,error:r instanceof Error?r.message:"Translation failed"}}}function $l(){let e=document.querySelectorAll("[data-yuktai-translation-original]");for(let t of e){let r=t.dataset.yuktaiTranslationOriginal;r&&(t.innerText=r,delete t.dataset.yuktaiTranslationOriginal)}Qi="en"}var F3=[{phrases:["go to main","skip to main","main content"],action:"focus-main",label:"Jump to main content"},{phrases:["go to navigation","go to nav","open menu"],action:"focus-nav",label:"Jump to navigation"},{phrases:["go to search","search","find"],action:"focus-search",label:"Jump to search"},{phrases:["scroll down","page down","next"],action:"scroll-down",label:"Scroll down"},{phrases:["scroll up","page up","back up"],action:"scroll-up",label:"Scroll up"},{phrases:["go back","previous page"],action:"go-back",label:"Go back"},{phrases:["click","press","select"],action:"click-focused",label:"Click focused element"},{phrases:["next item","tab forward","tab"],action:"tab-forward",label:"Move to next element"},{phrases:["previous item","tab back","shift tab"],action:"tab-back",label:"Move to previous element"},{phrases:["stop listening","stop voice","quiet"],action:"stop-voice",label:"Stop voice control"}],or=null,eo=!1,Cn=null;function ml(){return!!(window.SpeechRecognition||window.webkitSpeechRecognition)}function Z3(e){let t=e.toLowerCase().trim();for(let r of F3)for(let a of r.phrases)if(t.includes(a))return{action:r.action,label:r.label};return null}function U3(e){switch(e){case"focus-main":{let t=document.querySelector("main, [role='main'], #main");t&&(t.focus(),t.scrollIntoView({behavior:"smooth"}));break}case"focus-nav":{let t=document.querySelector("nav, [role='navigation']");t&&(t.focus(),t.scrollIntoView({behavior:"smooth"}));break}case"focus-search":{let t=document.querySelector("input[type='search'], input[role='searchbox'], [aria-label*='search' i]");t&&(t.focus(),t.scrollIntoView({behavior:"smooth"}));break}case"scroll-down":{window.scrollBy({top:400,behavior:"smooth"});break}case"scroll-up":{window.scrollBy({top:-400,behavior:"smooth"});break}case"go-back":{window.history.back();break}case"click-focused":{let t=document.activeElement;t&&t!==document.body&&t.click();break}case"tab-forward":{let t=S1(),r=t.indexOf(document.activeElement),a=t[r+1]||t[0];a&&a.focus();break}case"tab-back":{let t=S1(),r=t.indexOf(document.activeElement),a=t[r-1]||t[t.length-1];a&&a.focus();break}case"stop-voice":{Il();break}}}function S1(){return Array.from(document.querySelectorAll('a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')).filter(e=>!e.closest("[data-yuktai-panel]"))}function L1(e){if(!ml())return!1;if(eo)return!0;e&&(Cn=e);let t=window.SpeechRecognition||window.webkitSpeechRecognition;return or=new t,or.continuous=!0,or.interimResults=!1,or.lang="en-US",or.onresult=r=>{let a=r.results[r.results.length-1][0].transcript,n=Z3(a);if(n){U3(n.action);let s={success:!0,command:a,action:n.label};if(Cn&&Cn(s),n.action==="stop-voice")return}},or.onend=()=>{eo&&or?.start()},or.onerror=r=>{r.error!=="no-speech"&&Cn&&Cn({success:!1,command:"",action:"",error:`Voice error: ${r.error}`})},or.start(),eo=!0,W3(),!0}function Il(){eo=!1,or&&(or.stop(),or=null),Cn=null,g1()}var A1="yuktai-voice-indicator";function W3(){g1();let e=document.createElement("div");e.id=A1,e.setAttribute("data-yuktai-panel","true"),e.setAttribute("aria-live","polite"),e.setAttribute("aria-label","yuktai voice control is listening"),e.style.cssText=`
27
+ `,i.addEventListener("click",Q),t.appendChild(a),t.appendChild(i),document.body.prepend(t)}function Q(){let e=document.getElementById(Ie);e&&e.remove()}var ee=[{code:"en",label:"English"},{code:"hi",label:"Hindi"},{code:"es",label:"Spanish"},{code:"fr",label:"French"},{code:"de",label:"German"},{code:"it",label:"Italian"},{code:"pt",label:"Portuguese"},{code:"nl",label:"Dutch"},{code:"pl",label:"Polish"},{code:"ru",label:"Russian"},{code:"ja",label:"Japanese"},{code:"ko",label:"Korean"},{code:"zh",label:"Chinese"},{code:"ar",label:"Arabic"},{code:"tr",label:"Turkish"},{code:"vi",label:"Vietnamese"},{code:"bn",label:"Bengali"},{code:"id",label:"Indonesian"}],Z="en";function wt(){let e=window;return e.Translator||e.translation||null}async function vt(e){try{let t=window;if(!wt())return!1;if(t.Translator&&typeof t.Translator.availability=="function")try{let i=await t.Translator.availability({sourceLanguage:"en",targetLanguage:e});return i==="readily"||i==="available"||i==="downloadable"||i==="after-download"}catch{}return t.Translator&&typeof t.Translator.canTranslate=="function"?await t.Translator.canTranslate({sourceLanguage:"en",targetLanguage:e})!=="no":t.translation&&typeof t.translation.canTranslate=="function"?await t.translation.canTranslate({sourceLanguage:"en",targetLanguage:e})!=="no":!1}catch{return!1}}async function kt(e){let t=window,a={sourceLanguage:"en",targetLanguage:e};if(t.Translator&&typeof t.Translator.create=="function")return await t.Translator.create(a);if(t.translation&&typeof t.translation.createTranslator=="function")return await t.translation.createTranslator(a);throw new Error("Translation API not available")}async function Fe(e){if(e===Z)return{success:!0,language:e,fixed:0};if(e==="en")return fe(),Z="en",{success:!0,language:"en",fixed:0};if(!await vt(e))return{success:!1,language:e,fixed:0,error:`Translation to ${e} not available. Enable via chrome://flags.`};try{let a=await kt(e),i=document.querySelectorAll("p, h1, h2, h3, h4, h5, h6, li, blockquote, td, th, label, figcaption, span, a"),n=0;for(let s of i){if(s.closest("[data-yuktai-panel]")||s.children.length>0)continue;let o=s.innerText?.trim();if(!o||o.length<2)continue;s.dataset.yuktaiTranslationOriginal||(s.dataset.yuktaiTranslationOriginal=o);let c=await a.translate(o);c&&c!==o&&(s.innerText=c,n++)}return typeof a.destroy=="function"&&a.destroy(),Z=e,{success:!0,language:e,fixed:n}}catch(a){return{success:!1,language:e,fixed:0,error:a instanceof Error?a.message:"Translation failed"}}}function fe(){let e=document.querySelectorAll("[data-yuktai-translation-original]");for(let t of e){let a=t.dataset.yuktaiTranslationOriginal;a&&(t.innerText=a,delete t.dataset.yuktaiTranslationOriginal)}Z="en"}var At=[{phrases:["go to main","skip to main","main content"],action:"focus-main",label:"Jump to main content"},{phrases:["go to navigation","go to nav","open menu"],action:"focus-nav",label:"Jump to navigation"},{phrases:["go to search","search","find"],action:"focus-search",label:"Jump to search"},{phrases:["scroll down","page down","next"],action:"scroll-down",label:"Scroll down"},{phrases:["scroll up","page up","back up"],action:"scroll-up",label:"Scroll up"},{phrases:["go back","previous page"],action:"go-back",label:"Go back"},{phrases:["click","press","select"],action:"click-focused",label:"Click focused element"},{phrases:["next item","tab forward","tab"],action:"tab-forward",label:"Move to next element"},{phrases:["previous item","tab back","shift tab"],action:"tab-back",label:"Move to previous element"},{phrases:["stop listening","stop voice","quiet"],action:"stop-voice",label:"Stop voice control"}],L=null,te=!1,$=null;function me(){return!!(window.SpeechRecognition||window.webkitSpeechRecognition)}function St(e){let t=e.toLowerCase().trim();for(let a of At)for(let i of a.phrases)if(t.includes(i))return{action:a.action,label:a.label};return null}function Tt(e){switch(e){case"focus-main":{let t=document.querySelector("main, [role='main'], #main");t&&(t.focus(),t.scrollIntoView({behavior:"smooth"}));break}case"focus-nav":{let t=document.querySelector("nav, [role='navigation']");t&&(t.focus(),t.scrollIntoView({behavior:"smooth"}));break}case"focus-search":{let t=document.querySelector("input[type='search'], input[role='searchbox'], [aria-label*='search' i]");t&&(t.focus(),t.scrollIntoView({behavior:"smooth"}));break}case"scroll-down":{window.scrollBy({top:400,behavior:"smooth"});break}case"scroll-up":{window.scrollBy({top:-400,behavior:"smooth"});break}case"go-back":{window.history.back();break}case"click-focused":{let t=document.activeElement;t&&t!==document.body&&t.click();break}case"tab-forward":{let t=$e(),a=t.indexOf(document.activeElement),i=t[a+1]||t[0];i&&i.focus();break}case"tab-back":{let t=$e(),a=t.indexOf(document.activeElement),i=t[a-1]||t[t.length-1];i&&i.focus();break}case"stop-voice":{ge();break}}}function $e(){return Array.from(document.querySelectorAll('a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')).filter(e=>!e.closest("[data-yuktai-panel]"))}function Be(e){if(!me())return!1;if(te)return!0;e&&($=e);let t=window.SpeechRecognition||window.webkitSpeechRecognition;return L=new t,L.continuous=!0,L.interimResults=!1,L.lang="en-US",L.onresult=a=>{let i=a.results[a.results.length-1][0].transcript,n=St(i);if(n){Tt(n.action);let s={success:!0,command:i,action:n.label};if($&&$(s),n.action==="stop-voice")return}},L.onend=()=>{te&&L?.start()},L.onerror=a=>{a.error!=="no-speech"&&$&&$({success:!1,command:"",action:"",error:`Voice error: ${a.error}`})},L.start(),te=!0,Et(),!0}function ge(){te=!1,L&&(L.stop(),L=null),$=null,Oe()}var Ne="yuktai-voice-indicator";function Et(){Oe();let e=document.createElement("div");e.id=Ne,e.setAttribute("data-yuktai-panel","true"),e.setAttribute("aria-live","polite"),e.setAttribute("aria-label","yuktai voice control is listening"),e.style.cssText=`
67
28
  position: fixed;
68
29
  bottom: 80px;
69
30
  left: 50%;
@@ -88,12 +49,12 @@ ${this.boa_token}${this.audio_token.repeat(this._compute_audio_num_tokens(i[H++]
88
49
  background: #ffffff;
89
50
  animation: yuktai-pulse 1.2s infinite;
90
51
  flex-shrink: 0;
91
- `,!document.getElementById("yuktai-pulse-style")){let a=document.createElement("style");a.id="yuktai-pulse-style",a.textContent=`
52
+ `,!document.getElementById("yuktai-pulse-style")){let i=document.createElement("style");i.id="yuktai-pulse-style",i.textContent=`
92
53
  @keyframes yuktai-pulse {
93
54
  0%, 100% { opacity: 1; transform: scale(1); }
94
55
  50% { opacity: 0.4; transform: scale(0.7); }
95
56
  }
96
- `,document.head.appendChild(a)}let r=document.createElement("span");r.textContent="Listening for commands...",e.appendChild(t),e.appendChild(r),document.body.appendChild(e)}function g1(){let e=document.getElementById(A1);e&&e.remove()}var K3=["button:not([aria-label]):not([aria-labelledby])","a:not([aria-label]):not([aria-labelledby])","input:not([aria-label]):not([aria-labelledby]):not([id])","select:not([aria-label]):not([aria-labelledby])","textarea:not([aria-label]):not([aria-labelledby])","[role='button']:not([aria-label])","[role='link']:not([aria-label])","[role='checkbox']:not([aria-label])","[role='tab']:not([aria-label])"].join(", ");function b1(){let e=window;return e.Writer||e.ai?.writer||null}async function Sl(){try{let e=b1();if(!e)return!1;if(typeof e.availability=="function"){let t=await e.availability();return t==="readily"||t==="available"||t==="downloadable"}return typeof e.capabilities=="function"?(await e.capabilities())?.available!=="no":typeof e.create=="function"}catch{return!1}}function V3(e){let t=[],r=e.innerText?.trim();r&&t.push(`element text: "${r}"`);let a=e.placeholder?.trim();a&&t.push(`placeholder: "${a}"`);let n=e.getAttribute("name")?.trim();n&&t.push(`name: "${n}"`);let s=e.getAttribute("type")?.trim();s&&t.push(`type: "${s}"`);let i=e.id;if(i){let _=document.querySelector(`label[for="${i}"]`);_&&t.push(`label: "${_.innerText?.trim()}"`)}let o=e.parentElement?.innerText?.trim().slice(0,60);o&&t.push(`parent context: "${o}"`),t.push(`tag: ${e.tagName.toLowerCase()}`);let H=e.getAttribute("role");return H&&t.push(`role: ${H}`),t.join(". ")}async function j3(e,t){let r=`
57
+ `,document.head.appendChild(i)}let a=document.createElement("span");a.textContent="Listening for commands...",e.appendChild(t),e.appendChild(a),document.body.appendChild(e)}function Oe(){let e=document.getElementById(Ne);e&&e.remove()}var Ct=["button:not([aria-label]):not([aria-labelledby])","a:not([aria-label]):not([aria-labelledby])","input:not([aria-label]):not([aria-labelledby]):not([id])","select:not([aria-label]):not([aria-labelledby])","textarea:not([aria-label]):not([aria-labelledby])","[role='button']:not([aria-label])","[role='link']:not([aria-label])","[role='checkbox']:not([aria-label])","[role='tab']:not([aria-label])"].join(", ");function qe(){let e=window;return e.Writer||e.ai?.writer||null}async function be(){try{let e=qe();if(!e)return!1;if(typeof e.availability=="function"){let t=await e.availability();return t==="readily"||t==="available"||t==="downloadable"}return typeof e.capabilities=="function"?(await e.capabilities())?.available!=="no":typeof e.create=="function"}catch{return!1}}function Lt(e){let t=[],a=e.innerText?.trim();a&&t.push(`element text: "${a}"`);let i=e.placeholder?.trim();i&&t.push(`placeholder: "${i}"`);let n=e.getAttribute("name")?.trim();n&&t.push(`name: "${n}"`);let s=e.getAttribute("type")?.trim();s&&t.push(`type: "${s}"`);let o=e.id;if(o){let u=document.querySelector(`label[for="${o}"]`);u&&t.push(`label: "${u.innerText?.trim()}"`)}let c=e.parentElement?.innerText?.trim().slice(0,60);c&&t.push(`parent context: "${c}"`),t.push(`tag: ${e.tagName.toLowerCase()}`);let g=e.getAttribute("role");return g&&t.push(`role: ${g}`),t.join(". ")}async function Mt(e,t){let a=`
97
58
  Generate a short, clear aria-label for an HTML element.
98
59
  The label must be 2-6 words maximum.
99
60
  The label must describe what the element does or what it is.
@@ -104,7 +65,7 @@ ${this.boa_token}${this.audio_token.repeat(this._compute_audio_num_tokens(i[H++]
104
65
  ${t}
105
66
 
106
67
  Output only the label. Nothing else.
107
- `.trim();return(await e.write(r)).trim().replace(/^["']|["']$/g,"").replace(/\.$/,"").trim()}async function T1(){if(!await Sl())return{success:!1,fixed:0,elements:[],error:"Chrome Built-in AI Writer not available. Enable via chrome://flags."};let t=document.querySelectorAll(K3);if(t.length===0)return{success:!0,fixed:0,elements:[]};try{let r=b1();if(!r)throw new Error("Writer API not available");let a=await r.create({tone:"neutral",format:"plain-text",length:"short",outputLanguage:"en"}),n=0,s=[];for(let i of t){if(i.closest("[data-yuktai-panel]"))continue;let o=window.getComputedStyle(i);if(o.display==="none"||o.visibility==="hidden")continue;let H=V3(i),_=await j3(a,H);_&&_.length>0&&(i.dataset.yuktaiLabelOriginal=i.getAttribute("aria-label")||"",i.setAttribute("aria-label",_),n++,s.push({tag:i.tagName.toLowerCase(),label:_}))}return a.destroy(),{success:!0,fixed:n,elements:s}}catch(r){return{success:!1,fixed:0,elements:[],error:r instanceof Error?r.message:"Label generation failed"}}}function x1(){let e=document.querySelectorAll("[data-yuktai-label-original]");for(let t of e){let r=t.dataset.yuktaiLabelOriginal;r?t.setAttribute("aria-label",r):t.removeAttribute("aria-label"),delete t.dataset.yuktaiLabelOriginal}}var ao=null,v1=null;var y1=null,Ll=null,at=null,wn=null,to=null,Al=null,Nn=null,ro={deuteranopia:"yuktai-cb-d",protanopia:"yuktai-cb-p",tritanopia:"yuktai-cb-t"};var D1=new Set(["input","select","textarea"]);var gl={nav:"navigation",header:"banner",footer:"contentinfo",main:"main",aside:"complementary"};function bl(e,t="polite"){if(typeof window>"u"||!Nn?.speechEnabled||!window.speechSynthesis)return;window.speechSynthesis.cancel();let r=new SpeechSynthesisUtterance(e);r.rate=1,r.pitch=1,r.volume=1;let a=window.speechSynthesis.getVoices();a.length>0&&(r.voice=a[0]),window.speechSynthesis.speak(r)}function k1(e,t="info"){if(typeof document>"u")return;let a={success:{bg:"#0f9d58",border:"#0a7a44",icon:"\u2713"},error:{bg:"#d93025",border:"#b52a1c",icon:"\u2715"},warning:{bg:"#f29900",border:"#c67c00",icon:"\u26A0"},info:{bg:"#1a73e8",border:"#1557b0",icon:"\u2139"}}[t];at||(at=document.createElement("div"),at.setAttribute("role","alert"),at.setAttribute("aria-live","assertive"),at.setAttribute("aria-atomic","true"),at.style.cssText=`
68
+ `.trim();return(await e.write(a)).trim().replace(/^["']|["']$/g,"").replace(/\.$/,"").trim()}async function Ge(){if(!await be())return{success:!1,fixed:0,elements:[],error:"Chrome Built-in AI Writer not available. Enable via chrome://flags."};let t=document.querySelectorAll(Ct);if(t.length===0)return{success:!0,fixed:0,elements:[]};try{let a=qe();if(!a)throw new Error("Writer API not available");let i=await a.create({tone:"neutral",format:"plain-text",length:"short",outputLanguage:"en"}),n=0,s=[];for(let o of t){if(o.closest("[data-yuktai-panel]"))continue;let c=window.getComputedStyle(o);if(c.display==="none"||c.visibility==="hidden")continue;let g=Lt(o),u=await Mt(i,g);u&&u.length>0&&(o.dataset.yuktaiLabelOriginal=o.getAttribute("aria-label")||"",o.setAttribute("aria-label",u),n++,s.push({tag:o.tagName.toLowerCase(),label:u}))}return i.destroy(),{success:!0,fixed:n,elements:s}}catch(a){return{success:!1,fixed:0,elements:[],error:a instanceof Error?a.message:"Label generation failed"}}}function De(){let e=document.querySelectorAll("[data-yuktai-label-original]");for(let t of e){let a=t.dataset.yuktaiLabelOriginal;a?t.setAttribute("aria-label",a):t.removeAttribute("aria-label"),delete t.dataset.yuktaiLabelOriginal}}var oe=null,_e=null;var Ve=null,ye=null,b=null,B=null,ae=null,xe=null,N=null,ne={deuteranopia:"yuktai-cb-d",protanopia:"yuktai-cb-p",tritanopia:"yuktai-cb-t"};var je=new Set(["input","select","textarea"]);var he={nav:"navigation",header:"banner",footer:"contentinfo",main:"main",aside:"complementary"};function we(e,t="polite"){if(typeof window>"u"||!N?.speechEnabled||!window.speechSynthesis)return;window.speechSynthesis.cancel();let a=new SpeechSynthesisUtterance(e);a.rate=1,a.pitch=1,a.volume=1;let i=window.speechSynthesis.getVoices();i.length>0&&(a.voice=i[0]),window.speechSynthesis.speak(a)}function Ze(e,t="info"){if(typeof document>"u")return;let i={success:{bg:"#0f9d58",border:"#0a7a44",icon:"\u2713"},error:{bg:"#d93025",border:"#b52a1c",icon:"\u2715"},warning:{bg:"#f29900",border:"#c67c00",icon:"\u26A0"},info:{bg:"#1a73e8",border:"#1557b0",icon:"\u2139"}}[t];b||(b=document.createElement("div"),b.setAttribute("role","alert"),b.setAttribute("aria-live","assertive"),b.setAttribute("aria-atomic","true"),b.style.cssText=`
108
69
  position: fixed;
109
70
  top: 80px;
110
71
  right: 16px;
@@ -123,14 +84,14 @@ ${this.boa_token}${this.audio_token.repeat(this._compute_audio_num_tokens(i[H++]
123
84
  transition: transform 0.3s, opacity 0.3s;
124
85
  transform: translateX(120%);
125
86
  opacity: 0;
126
- `,document.body.appendChild(at)),at.style.background=a.bg,at.style.border=`1px solid ${a.border}`,at.style.color="#fff",at.innerHTML=`
127
- <span style="font-size:18px;font-weight:700">${a.icon}</span>
87
+ `,document.body.appendChild(b)),b.style.background=i.bg,b.style.border=`1px solid ${i.border}`,b.style.color="#fff",b.innerHTML=`
88
+ <span style="font-size:18px;font-weight:700">${i.icon}</span>
128
89
  <span style="flex:1;line-height:1.4">${e}</span>
129
90
  <button
130
91
  onclick="this.parentElement.style.transform='translateX(120%)';this.parentElement.style.opacity='0'"
131
92
  style="background:none;border:none;color:#fff;cursor:pointer;font-size:18px;padding:0;line-height:1"
132
93
  aria-label="Close notification">\xD7</button>
133
- `,window.innerWidth<=480&&(at.style.right="8px",at.style.left="8px",at.style.maxWidth="none",at.style.width="auto"),requestAnimationFrame(()=>{at&&(at.style.transform="translateX(0)",at.style.opacity="1")}),setTimeout(()=>{at&&(at.style.transform="translateX(120%)",at.style.opacity="0")},5e3)}function Oe(e,t="info",r=!0){ao&&(ao.textContent=e),k1(e,t),r&&bl(e,t==="error"?"assertive":"polite")}function q3(){if(typeof document>"u"||y1)return;let e=[{label:"Skip to main content",selector:"main,[role='main'],#main,#main-content"},{label:"Skip to navigation",selector:"nav,[role='navigation'],#nav,#navigation"},{label:"Skip to search",selector:"[role='search'],#search,input[type='search']"}],t=document.createElement("div");t.setAttribute("data-yuktai-skip-bar","true"),t.setAttribute("role","navigation"),t.setAttribute("aria-label","Skip links"),t.style.cssText=`
94
+ `,window.innerWidth<=480&&(b.style.right="8px",b.style.left="8px",b.style.maxWidth="none",b.style.width="auto"),requestAnimationFrame(()=>{b&&(b.style.transform="translateX(0)",b.style.opacity="1")}),setTimeout(()=>{b&&(b.style.transform="translateX(120%)",b.style.opacity="0")},5e3)}function f(e,t="info",a=!0){oe&&(oe.textContent=e),Ze(e,t),a&&we(e,t==="error"?"assertive":"polite")}function Rt(){if(typeof document>"u"||Ve)return;let e=[{label:"Skip to main content",selector:"main,[role='main'],#main,#main-content"},{label:"Skip to navigation",selector:"nav,[role='navigation'],#nav,#navigation"},{label:"Skip to search",selector:"[role='search'],#search,input[type='search']"}],t=document.createElement("div");t.setAttribute("data-yuktai-skip-bar","true"),t.setAttribute("role","navigation"),t.setAttribute("aria-label","Skip links"),t.style.cssText=`
134
95
  position: fixed;
135
96
  top: 0;
136
97
  left: 0;
@@ -144,7 +105,7 @@ ${this.boa_token}${this.audio_token.repeat(this._compute_audio_num_tokens(i[H++]
144
105
  transform: translateY(-100%);
145
106
  transition: transform 0.2s ease;
146
107
  font-family: system-ui, sans-serif;
147
- `;let r=!1;if(e.forEach(({label:n,selector:s})=>{let i=document.querySelector(s);if(!i)return;r=!0,i.getAttribute("tabindex")||i.setAttribute("tabindex","-1");let o=document.createElement("a");o.href="#",o.textContent=n,o.style.cssText=`
108
+ `;let a=!1;if(e.forEach(({label:n,selector:s})=>{let o=document.querySelector(s);if(!o)return;a=!0,o.getAttribute("tabindex")||o.setAttribute("tabindex","-1");let c=document.createElement("a");c.href="#",c.textContent=n,c.style.cssText=`
148
109
  color: #fff;
149
110
  background: #1a73e8;
150
111
  padding: 8px 14px;
@@ -155,7 +116,7 @@ ${this.boa_token}${this.audio_token.repeat(this._compute_audio_num_tokens(i[H++]
155
116
  white-space: nowrap;
156
117
  border: 2px solid transparent;
157
118
  transition: background 0.15s, border-color 0.15s;
158
- `,o.addEventListener("focus",()=>{t.style.transform="translateY(0)"}),o.addEventListener("blur",()=>{setTimeout(()=>{t.matches(":focus-within")||(t.style.transform="translateY(-100%)")},2e3)}),o.addEventListener("click",H=>{H.preventDefault(),i.focus(),i.scrollIntoView({behavior:"smooth",block:"start"}),Oe(`Jumped to ${n.replace("Skip to ","")}`,"info"),t.style.transform="translateY(-100%)"}),t.appendChild(o)}),!r)return;window.innerWidth<768&&(t.style.transform="translateY(0)",t.style.position="sticky"),window.addEventListener("resize",()=>{window.innerWidth<768&&(t.style.transform="translateY(0)")}),document.body.insertBefore(t,document.body.firstChild),y1=t}function X3(){if(typeof document>"u"||document.querySelector("[data-yuktai-focus-style]"))return;let e=document.createElement("style");e.setAttribute("data-yuktai-focus-style","true"),e.textContent=`
119
+ `,c.addEventListener("focus",()=>{t.style.transform="translateY(0)"}),c.addEventListener("blur",()=>{setTimeout(()=>{t.matches(":focus-within")||(t.style.transform="translateY(-100%)")},2e3)}),c.addEventListener("click",g=>{g.preventDefault(),o.focus(),o.scrollIntoView({behavior:"smooth",block:"start"}),f(`Jumped to ${n.replace("Skip to ","")}`,"info"),t.style.transform="translateY(-100%)"}),t.appendChild(c)}),!a)return;window.innerWidth<768&&(t.style.transform="translateY(0)",t.style.position="sticky"),window.addEventListener("resize",()=>{window.innerWidth<768&&(t.style.transform="translateY(0)")}),document.body.insertBefore(t,document.body.firstChild),Ve=t}function Pt(){if(typeof document>"u"||document.querySelector("[data-yuktai-focus-style]"))return;let e=document.createElement("style");e.setAttribute("data-yuktai-focus-style","true"),e.textContent=`
159
120
 
160
121
  /* \u2500\u2500 Focus indicator \u2014 WCAG 2.4.11 minimum 2px solid \u2500\u2500 */
161
122
  [data-yuktai-a11y] *:focus-visible {
@@ -301,7 +262,7 @@ ${this.boa_token}${this.audio_token.repeat(this._compute_audio_num_tokens(i[H++]
301
262
  width: auto !important;
302
263
  }
303
264
  }
304
- `,document.head.appendChild(e),document.documentElement.setAttribute("data-yuktai-a11y","true")}function z3(){typeof document>"u"||document.querySelector("[data-yuktai-kb-init]")||(document.documentElement.setAttribute("data-yuktai-kb-init","true"),document.addEventListener("keydown",e=>{let t=document.activeElement;if(!t)return;let r=t.getAttribute("role")||"";if(e.key==="Escape"){let a=t.closest("[role='dialog'],[role='alertdialog']");if(a){a.style.display="none",Oe("Dialog closed","info");return}let n=t.closest("[role='menu'],[role='menubar']");n&&(n.style.display="none",Oe("Menu closed","info"))}if(r==="menuitem"||t.closest("[role='menu'],[role='menubar']")){let a=t.closest("[role='menu'],[role='menubar']");if(!a)return;let n=Array.from(a.querySelectorAll("[role='menuitem']:not([disabled])")),s=n.indexOf(t);e.key==="ArrowDown"||e.key==="ArrowRight"?(e.preventDefault(),n[(s+1)%n.length]?.focus()):e.key==="ArrowUp"||e.key==="ArrowLeft"?(e.preventDefault(),n[(s-1+n.length)%n.length]?.focus()):e.key==="Home"?(e.preventDefault(),n[0]?.focus()):e.key==="End"&&(e.preventDefault(),n[n.length-1]?.focus())}if(r==="tab"||t.closest("[role='tablist']")){let a=t.closest("[role='tablist']");if(!a)return;let n=Array.from(a.querySelectorAll("[role='tab']:not([disabled])")),s=n.indexOf(t);if(e.key==="ArrowRight"||e.key==="ArrowDown"){e.preventDefault();let i=n[(s+1)%n.length];i?.focus(),i?.click()}else if(e.key==="ArrowLeft"||e.key==="ArrowUp"){e.preventDefault();let i=n[(s-1+n.length)%n.length];i?.focus(),i?.click()}}if(r==="option"||t.closest("[role='listbox']")){let a=t.closest("[role='listbox']");if(!a)return;let n=Array.from(a.querySelectorAll("[role='option']:not([aria-disabled='true'])")),s=n.indexOf(t);e.key==="ArrowDown"?(e.preventDefault(),n[(s+1)%n.length]?.focus()):e.key==="ArrowUp"?(e.preventDefault(),n[(s-1+n.length)%n.length]?.focus()):(e.key==="Enter"||e.key===" ")&&(e.preventDefault(),t.setAttribute("aria-selected","true"),n.forEach(i=>{i!==t&&i.setAttribute("aria-selected","false")}),Oe(`Selected: ${t.textContent?.trim()}`,"success"))}e.altKey&&e.key==="a"&&(e.preventDefault(),J3()),e.key==="Tab"&&Nn?.speechEnabled&&setTimeout(()=>{let a=document.activeElement;if(!a)return;let n=a.getAttribute("aria-label")||a.getAttribute("title")||a.textContent?.trim()||a.tagName.toLowerCase(),s=a.getAttribute("role")||a.tagName.toLowerCase();bl(`${n}, ${s}`)},100)}))}function no(e){let t=e.querySelectorAll('button:not([disabled]),a[href],input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex="-1"]),[role="button"]');if(t.length===0)return;let r=t[0],a=t[t.length-1];r.focus(),e.addEventListener("keydown",n=>{n.key==="Tab"&&(n.shiftKey?document.activeElement===r&&(n.preventDefault(),a.focus()):document.activeElement===a&&(n.preventDefault(),r.focus()))})}function J3(){if(typeof document>"u")return;if(wn){wn.remove(),wn=null;return}let e=document.createElement("div");e.setAttribute("role","dialog"),e.setAttribute("aria-label","Keyboard shortcuts"),e.setAttribute("aria-modal","true"),e.setAttribute("data-yuktai-cheatsheet","true"),e.style.cssText=`
265
+ `,document.head.appendChild(e),document.documentElement.setAttribute("data-yuktai-a11y","true")}function zt(){typeof document>"u"||document.querySelector("[data-yuktai-kb-init]")||(document.documentElement.setAttribute("data-yuktai-kb-init","true"),document.addEventListener("keydown",e=>{let t=document.activeElement;if(!t)return;let a=t.getAttribute("role")||"";if(e.key==="Escape"){let i=t.closest("[role='dialog'],[role='alertdialog']");if(i){i.style.display="none",f("Dialog closed","info");return}let n=t.closest("[role='menu'],[role='menubar']");n&&(n.style.display="none",f("Menu closed","info"))}if(a==="menuitem"||t.closest("[role='menu'],[role='menubar']")){let i=t.closest("[role='menu'],[role='menubar']");if(!i)return;let n=Array.from(i.querySelectorAll("[role='menuitem']:not([disabled])")),s=n.indexOf(t);e.key==="ArrowDown"||e.key==="ArrowRight"?(e.preventDefault(),n[(s+1)%n.length]?.focus()):e.key==="ArrowUp"||e.key==="ArrowLeft"?(e.preventDefault(),n[(s-1+n.length)%n.length]?.focus()):e.key==="Home"?(e.preventDefault(),n[0]?.focus()):e.key==="End"&&(e.preventDefault(),n[n.length-1]?.focus())}if(a==="tab"||t.closest("[role='tablist']")){let i=t.closest("[role='tablist']");if(!i)return;let n=Array.from(i.querySelectorAll("[role='tab']:not([disabled])")),s=n.indexOf(t);if(e.key==="ArrowRight"||e.key==="ArrowDown"){e.preventDefault();let o=n[(s+1)%n.length];o?.focus(),o?.click()}else if(e.key==="ArrowLeft"||e.key==="ArrowUp"){e.preventDefault();let o=n[(s-1+n.length)%n.length];o?.focus(),o?.click()}}if(a==="option"||t.closest("[role='listbox']")){let i=t.closest("[role='listbox']");if(!i)return;let n=Array.from(i.querySelectorAll("[role='option']:not([aria-disabled='true'])")),s=n.indexOf(t);e.key==="ArrowDown"?(e.preventDefault(),n[(s+1)%n.length]?.focus()):e.key==="ArrowUp"?(e.preventDefault(),n[(s-1+n.length)%n.length]?.focus()):(e.key==="Enter"||e.key===" ")&&(e.preventDefault(),t.setAttribute("aria-selected","true"),n.forEach(o=>{o!==t&&o.setAttribute("aria-selected","false")}),f(`Selected: ${t.textContent?.trim()}`,"success"))}e.altKey&&e.key==="a"&&(e.preventDefault(),It()),e.key==="Tab"&&N?.speechEnabled&&setTimeout(()=>{let i=document.activeElement;if(!i)return;let n=i.getAttribute("aria-label")||i.getAttribute("title")||i.textContent?.trim()||i.tagName.toLowerCase(),s=i.getAttribute("role")||i.tagName.toLowerCase();we(`${n}, ${s}`)},100)}))}function ie(e){let t=e.querySelectorAll('button:not([disabled]),a[href],input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex="-1"]),[role="button"]');if(t.length===0)return;let a=t[0],i=t[t.length-1];a.focus(),e.addEventListener("keydown",n=>{n.key==="Tab"&&(n.shiftKey?document.activeElement===a&&(n.preventDefault(),i.focus()):document.activeElement===i&&(n.preventDefault(),a.focus()))})}function It(){if(typeof document>"u")return;if(B){B.remove(),B=null;return}let e=document.createElement("div");e.setAttribute("role","dialog"),e.setAttribute("aria-label","Keyboard shortcuts"),e.setAttribute("aria-modal","true"),e.setAttribute("data-yuktai-cheatsheet","true"),e.style.cssText=`
305
266
  position: fixed;
306
267
  top: 50%;
307
268
  left: 50%;
@@ -325,18 +286,18 @@ ${this.boa_token}${this.audio_token.repeat(this._compute_audio_num_tokens(i[H++]
325
286
  style="background:none;border:none;color:#aaa;cursor:pointer;font-size:20px;padding:0;line-height:1"
326
287
  aria-label="Close shortcuts">\xD7</button>
327
288
  </div>
328
- ${t.map(([a,n])=>`
289
+ ${t.map(([i,n])=>`
329
290
  <div style="display:flex;justify-content:space-between;align-items:center;padding:6px 0;border-bottom:1px solid #2a2a4a">
330
- <kbd style="background:#2a2a4a;color:#74c0fc;padding:3px 8px;border-radius:4px;font-size:12px;font-family:monospace;border:1px solid #3a3a6a">${a}</kbd>
291
+ <kbd style="background:#2a2a4a;color:#74c0fc;padding:3px 8px;border-radius:4px;font-size:12px;font-family:monospace;border:1px solid #3a3a6a">${i}</kbd>
331
292
  <span style="font-size:12px;color:#ccc;text-align:right;flex:1;margin-left:12px">${n}</span>
332
293
  </div>
333
294
  `).join("")}
334
- `,e.querySelector("[data-yuktai-close]")?.addEventListener("click",()=>{e.remove(),wn=null}),e.addEventListener("keydown",a=>{a.key==="Escape"&&(e.remove(),wn=null)}),document.body.appendChild(e),wn=e,no(e),Oe("Keyboard shortcuts opened. Press Escape to close.","info")}function Q3(e){if(typeof document>"u"||!Nn?.showAuditBadge||typeof window<"u"&&!window.location.hostname.includes("localhost")&&!window.location.hostname.includes("127.0.0.1"))return;Ll&&Ll.remove();let t=e.score,r=t>=90?"#0f9d58":t>=70?"#f29900":"#d93025",a=t>=90?"\u267F":t>=70?"\u26A0":"\u2715",n=document.createElement("button");n.setAttribute("aria-label",`Accessibility score: ${t} out of 100`),n.setAttribute("data-yuktai-badge","true"),n.style.cssText=`
295
+ `,e.querySelector("[data-yuktai-close]")?.addEventListener("click",()=>{e.remove(),B=null}),e.addEventListener("keydown",i=>{i.key==="Escape"&&(e.remove(),B=null)}),document.body.appendChild(e),B=e,ie(e),f("Keyboard shortcuts opened. Press Escape to close.","info")}function Ht(e){if(typeof document>"u"||!N?.showAuditBadge||typeof window<"u"&&!window.location.hostname.includes("localhost")&&!window.location.hostname.includes("127.0.0.1"))return;ye&&ye.remove();let t=e.score,a=t>=90?"#0f9d58":t>=70?"#f29900":"#d93025",i=t>=90?"\u267F":t>=70?"\u26A0":"\u2715",n=document.createElement("button");n.setAttribute("aria-label",`Accessibility score: ${t} out of 100`),n.setAttribute("data-yuktai-badge","true"),n.style.cssText=`
335
296
  position: fixed;
336
297
  bottom: 16px;
337
298
  left: 16px;
338
299
  z-index: 999998;
339
- background: ${r};
300
+ background: ${a};
340
301
  color: #fff;
341
302
  border: none;
342
303
  border-radius: 20px;
@@ -350,7 +311,7 @@ ${this.boa_token}${this.audio_token.repeat(this._compute_audio_num_tokens(i[H++]
350
311
  align-items: center;
351
312
  gap: 6px;
352
313
  transition: transform 0.15s;
353
- `,n.innerHTML=`${a} ${t}/100 <span style="font-weight:400;opacity:0.85">${e.details.length} issues</span>`,n.addEventListener("click",()=>Y3(e)),document.body.appendChild(n),Ll=n}function Y3(e){let t=document.querySelector("[data-yuktai-audit-details]");if(t){t.remove();return}let r=document.createElement("div");r.setAttribute("data-yuktai-audit-details","true"),r.setAttribute("role","dialog"),r.setAttribute("aria-label","Accessibility audit details"),r.style.cssText=`
314
+ `,n.innerHTML=`${i} ${t}/100 <span style="font-weight:400;opacity:0.85">${e.details.length} issues</span>`,n.addEventListener("click",()=>Wt(e)),document.body.appendChild(n),ye=n}function Wt(e){let t=document.querySelector("[data-yuktai-audit-details]");if(t){t.remove();return}let a=document.createElement("div");a.setAttribute("data-yuktai-audit-details","true"),a.setAttribute("role","dialog"),a.setAttribute("aria-label","Accessibility audit details"),a.style.cssText=`
354
315
  position: fixed;
355
316
  bottom: 56px;
356
317
  left: 16px;
@@ -367,7 +328,7 @@ ${this.boa_token}${this.audio_token.repeat(this._compute_audio_num_tokens(i[H++]
367
328
  box-shadow: 0 8px 32px rgba(0,0,0,0.5);
368
329
  font-family: system-ui, sans-serif;
369
330
  font-size: 12px;
370
- `;let a={critical:"#d93025",serious:"#f29900",moderate:"#1a73e8",minor:"#0f9d58"};r.innerHTML=`
331
+ `;let i={critical:"#d93025",serious:"#f29900",moderate:"#1a73e8",minor:"#0f9d58"};a.innerHTML=`
371
332
  <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px">
372
333
  <strong style="font-size:14px;color:#74c0fc">Audit report</strong>
373
334
  <span style="color:#aaa">${e.fixed} fixed \xB7 ${e.renderTime}ms</span>
@@ -375,14 +336,14 @@ ${this.boa_token}${this.audio_token.repeat(this._compute_audio_num_tokens(i[H++]
375
336
  ${e.details.slice(0,20).map(n=>`
376
337
  <div style="padding:6px 0;border-bottom:1px solid #2a2a4a">
377
338
  <div style="display:flex;gap:6px;align-items:center">
378
- <span style="background:${a[n.severity]};color:#fff;padding:1px 6px;border-radius:4px;font-size:10px;font-weight:700;text-transform:uppercase">${n.severity}</span>
339
+ <span style="background:${i[n.severity]};color:#fff;padding:1px 6px;border-radius:4px;font-size:10px;font-weight:700;text-transform:uppercase">${n.severity}</span>
379
340
  <code style="color:#74c0fc">&lt;${n.tag}&gt;</code>
380
341
  </div>
381
342
  <div style="color:#ccc;margin-top:3px">${n.fix}</div>
382
343
  </div>
383
344
  `).join("")}
384
345
  ${e.details.length>20?`<div style="color:#888;padding:8px 0;text-align:center">+${e.details.length-20} more issues</div>`:""}
385
- `,r.addEventListener("keydown",n=>{n.key==="Escape"&&r.remove()}),document.body.appendChild(r),no(r)}function R1(e){typeof document>"u"||(Al&&clearTimeout(Al),Al=setTimeout(()=>{if(to)return;let t=document.createElement("div");t.setAttribute("role","alertdialog"),t.setAttribute("aria-label","Session timeout warning"),t.setAttribute("aria-modal","true"),t.setAttribute("data-yuktai-timeout","true"),t.style.cssText=`
346
+ `,a.addEventListener("keydown",n=>{n.key==="Escape"&&a.remove()}),document.body.appendChild(a),ie(a)}function et(e){typeof document>"u"||(xe&&clearTimeout(xe),xe=setTimeout(()=>{if(ae)return;let t=document.createElement("div");t.setAttribute("role","alertdialog"),t.setAttribute("aria-label","Session timeout warning"),t.setAttribute("aria-modal","true"),t.setAttribute("data-yuktai-timeout","true"),t.style.cssText=`
386
347
  position: fixed;
387
348
  top: 50%;
388
349
  left: 50%;
@@ -411,50 +372,19 @@ ${this.boa_token}${this.audio_token.repeat(this._compute_audio_num_tokens(i[H++]
411
372
  No, sign out
412
373
  </button>
413
374
  </div>
414
- `;let r=t.querySelector("[data-yuktai-extend]"),a=t.querySelector("[data-yuktai-dismiss]");r?.addEventListener("click",()=>{t.remove(),to=null,Oe("Session extended. You have more time.","success"),Nn?.timeoutWarning&&R1(Nn.timeoutWarning)}),a?.addEventListener("click",()=>{t.remove(),to=null}),document.body.appendChild(t),to=t,no(t),Oe("Warning: Your session will expire soon. Do you need more time?","warning")},e*1e3))}function e5(e){if(typeof document>"u")return;let t=document.documentElement;if(t.toggleAttribute("data-yuktai-high-contrast",!!e.highContrast),t.toggleAttribute("data-yuktai-dark",!!e.darkMode),t.toggleAttribute("data-yuktai-reduce-motion",!!e.reduceMotion),t.toggleAttribute("data-yuktai-large-targets",!!e.largeTargets),t.toggleAttribute("data-yuktai-keyboard",!!e.keyboardHints),t.toggleAttribute("data-yuktai-dyslexia",!!e.dyslexiaFont),e.localFont?document.body.style.fontFamily=`"${e.localFont}", system-ui, sans-serif`:e.dyslexiaFont||(document.body.style.fontFamily=""),e.fontSizeMultiplier&&e.fontSizeMultiplier!==1?document.documentElement.style.fontSize=`${e.fontSizeMultiplier*100}%`:document.documentElement.style.fontSize="",e.colorBlindMode&&e.colorBlindMode!=="none"){let r=e.colorBlindMode==="achromatopsia"?"grayscale(100%)":`url(#${ro[e.colorBlindMode]})`;document.body.style.filter=r}else document.body.style.filter=""}function t5(e){try{let t=localStorage.getItem("yuktai-a11y-prefs");t&&Object.assign(e,JSON.parse(t))}catch{}}async function C1(e){if(e){if(!await fl()){Oe("Plain English requires Chrome 127+","warning");return}Oe("Rewriting page in plain English...","info",!1);let r=await h1();Oe(r.error?`Plain English failed: ${r.error}`:`${r.fixed} sections rewritten in plain English`,r.error?"error":"success",!1)}else f1(),Oe("Original text restored","info",!1)}async function w1(e){if(e){if(!await El()){Oe("Page summariser requires Chrome 127+","warning");return}Oe("Generating page summary...","info",!1);let r=await m1();Oe(r.error?`Summary failed: ${r.error}`:"Page summary added at top",r.error?"error":"success",!1)}else Ji(),Oe("Page summary removed","info",!1)}async function N1(e){if(e==="en"){$l(),Oe("Page restored to English","info",!1);return}Oe(`Translating page to ${e}...`,"info",!1);let t=await I1(e);Oe(t.error?`Translation failed: ${t.error}`:`Page translated to ${e}`,t.error?"error":"success",!1)}async function B1(e){if(e){if(!ml()){Oe("Voice control not supported in this browser","warning");return}L1(t=>{t.success&&Oe(`Voice: ${t.action}`,"info",!1)}),Oe("Voice control started. Say a command.","success",!1)}else Il(),Oe("Voice control stopped","info",!1)}async function M1(e){if(e){if(!await Sl()){Oe("Smart labels requires Chrome 127+","warning");return}Oe("Generating smart labels...","info",!1);let r=await T1();Oe(r.error?`Smart labels failed: ${r.error}`:`${r.fixed} elements labelled`,r.error?"error":"success",!1)}else x1(),Oe("Smart labels removed","info",!1)}function r5(){if(typeof document>"u"||ao)return;let e=document.createElement("div");e.setAttribute("aria-live","polite"),e.setAttribute("aria-atomic","true"),e.setAttribute("aria-relevant","text"),e.style.cssText="position:absolute;left:-9999px;width:1px;height:1px;overflow:hidden;clip:rect(0,0,0,0);",document.body.appendChild(e),ao=e}function a5(){if(typeof document>"u"||v1)return;let e=document.createElementNS("http://www.w3.org/2000/svg","svg");e.setAttribute("aria-hidden","true"),e.style.cssText="position:absolute;width:0;height:0;overflow:hidden;",e.innerHTML=`
375
+ `;let a=t.querySelector("[data-yuktai-extend]"),i=t.querySelector("[data-yuktai-dismiss]");a?.addEventListener("click",()=>{t.remove(),ae=null,f("Session extended. You have more time.","success"),N?.timeoutWarning&&et(N.timeoutWarning)}),i?.addEventListener("click",()=>{t.remove(),ae=null}),document.body.appendChild(t),ae=t,ie(t),f("Warning: Your session will expire soon. Do you need more time?","warning")},e*1e3))}function Ft(e){if(typeof document>"u")return;let t=document.documentElement;if(t.toggleAttribute("data-yuktai-high-contrast",!!e.highContrast),t.toggleAttribute("data-yuktai-dark",!!e.darkMode),t.toggleAttribute("data-yuktai-reduce-motion",!!e.reduceMotion),t.toggleAttribute("data-yuktai-large-targets",!!e.largeTargets),t.toggleAttribute("data-yuktai-keyboard",!!e.keyboardHints),t.toggleAttribute("data-yuktai-dyslexia",!!e.dyslexiaFont),e.localFont?document.body.style.fontFamily=`"${e.localFont}", system-ui, sans-serif`:e.dyslexiaFont||(document.body.style.fontFamily=""),e.fontSizeMultiplier&&e.fontSizeMultiplier!==1?document.documentElement.style.fontSize=`${e.fontSizeMultiplier*100}%`:document.documentElement.style.fontSize="",e.colorBlindMode&&e.colorBlindMode!=="none"){let a=e.colorBlindMode==="achromatopsia"?"grayscale(100%)":`url(#${ne[e.colorBlindMode]})`;document.body.style.filter=a}else document.body.style.filter=""}function $t(e){try{let t=localStorage.getItem("yuktai-a11y-prefs");t&&Object.assign(e,JSON.parse(t))}catch{}}async function Ke(e){if(e){if(!await ue()){f("Plain English requires Chrome 127+","warning");return}f("Rewriting page in plain English...","info",!1);let a=await Pe();f(a.error?`Plain English failed: ${a.error}`:`${a.fixed} sections rewritten in plain English`,a.error?"error":"success",!1)}else ze(),f("Original text restored","info",!1)}async function Ye(e){if(e){if(!await pe()){f("Page summariser requires Chrome 127+","warning");return}f("Generating page summary...","info",!1);let a=await We();f(a.error?`Summary failed: ${a.error}`:"Page summary added at top",a.error?"error":"success",!1)}else Q(),f("Page summary removed","info",!1)}async function Ue(e){if(e==="en"){fe(),f("Page restored to English","info",!1);return}f(`Translating page to ${e}...`,"info",!1);let t=await Fe(e);f(t.error?`Translation failed: ${t.error}`:`Page translated to ${e}`,t.error?"error":"success",!1)}async function Je(e){if(e){if(!me()){f("Voice control not supported in this browser","warning");return}Be(t=>{t.success&&f(`Voice: ${t.action}`,"info",!1)}),f("Voice control started. Say a command.","success",!1)}else ge(),f("Voice control stopped","info",!1)}async function Xe(e){if(e){if(!await be()){f("Smart labels requires Chrome 127+","warning");return}f("Generating smart labels...","info",!1);let a=await Ge();f(a.error?`Smart labels failed: ${a.error}`:`${a.fixed} elements labelled`,a.error?"error":"success",!1)}else De(),f("Smart labels removed","info",!1)}function Bt(){if(typeof document>"u"||oe)return;let e=document.createElement("div");e.setAttribute("aria-live","polite"),e.setAttribute("aria-atomic","true"),e.setAttribute("aria-relevant","text"),e.style.cssText="position:absolute;left:-9999px;width:1px;height:1px;overflow:hidden;clip:rect(0,0,0,0);",document.body.appendChild(e),oe=e}function Nt(){if(typeof document>"u"||_e)return;let e=document.createElementNS("http://www.w3.org/2000/svg","svg");e.setAttribute("aria-hidden","true"),e.style.cssText="position:absolute;width:0;height:0;overflow:hidden;",e.innerHTML=`
415
376
  <defs>
416
- <filter id="${ro.deuteranopia}">
377
+ <filter id="${ne.deuteranopia}">
417
378
  <feColorMatrix type="matrix"
418
379
  values="0.625 0.375 0 0 0 0.7 0.3 0 0 0 0 0.3 0.7 0 0 0 0 0 1 0"/>
419
380
  </filter>
420
- <filter id="${ro.protanopia}">
381
+ <filter id="${ne.protanopia}">
421
382
  <feColorMatrix type="matrix"
422
383
  values="0.567 0.433 0 0 0 0.558 0.442 0 0 0 0 0.242 0.758 0 0 0 0 0 1 0"/>
423
384
  </filter>
424
- <filter id="${ro.tritanopia}">
385
+ <filter id="${ne.tritanopia}">
425
386
  <feColorMatrix type="matrix"
426
387
  values="0.95 0.05 0 0 0 0 0.433 0.567 0 0 0 0.475 0.525 0 0 0 0 0 1 0"/>
427
388
  </filter>
428
389
  </defs>
429
- `,document.body.appendChild(e),v1=e}function P1(e){let t={critical:20,serious:10,moderate:5,minor:2},r=e.details.reduce((a,n)=>a+(t[n.severity]||0),0);return Math.max(0,Math.min(100,100-r))}var Jt={name:"yuktai-a11y",version:"4.0.0",observer:null,async execute(e){if(!e.enabled)return this.stopObserver(),"yuktai: disabled.";Nn=e,t5(e),r5(),a5(),X3(),z3(),e.showSkipLinks!==!1&&q3(),e.showPreferencePanel,e5(e);let t=this.applyFixes(e);t.score=P1(t),e.showAuditBadge&&Q3(t),e.timeoutWarning&&R1(e.timeoutWarning),e.autoFix&&this.startObserver(e),e.plainEnglish&&await C1(!0),e.summarisePage&&await w1(!0),e.translateLanguage&&e.translateLanguage!=="en"&&await N1(e.translateLanguage),e.voiceControl&&await B1(!0),e.smartLabels&&await M1(!0);let r=`${t.fixed} fixes applied. Score: ${t.score}/100.`;return Oe(r,t.score>=90?"success":"info",!1),`yuktai v4.0.0: ${r} Scanned ${t.scanned} elements in ${t.renderTime}ms.`},applyFixes(e){let t={fixed:0,scanned:0,renderTime:0,score:100,details:[]};if(typeof document>"u")return t;let r=performance.now(),a=document.querySelectorAll("*");t.scanned=a.length;let n=(s,i,o,H)=>{t.details.push({tag:s,fix:i,severity:o,element:H.outerHTML.slice(0,100)}),t.fixed++};return a.forEach(s=>{let i=s,o=i.tagName.toLowerCase();if(o==="html"&&!i.getAttribute("lang")&&(i.setAttribute("lang","en"),n(o,'lang="en" added',"critical",i)),o==="meta"){let _=i.getAttribute("name"),c=i.getAttribute("content")||"";_==="viewport"&&c.includes("user-scalable=no")&&(i.setAttribute("content",c.replace("user-scalable=no","user-scalable=yes")),n(o,"user-scalable=yes restored","serious",i)),_==="viewport"&&/maximum-scale=1(?:[^0-9]|$)/.test(c)&&(i.setAttribute("content",c.replace(/maximum-scale=1(?=[^0-9]|$)/,"maximum-scale=5")),n(o,"maximum-scale=5 restored","serious",i))}if(o==="main"&&!i.getAttribute("tabindex")&&(i.setAttribute("tabindex","-1"),i.getAttribute("id")||i.setAttribute("id","main-content")),o==="img"&&(i.hasAttribute("alt")||(i.setAttribute("alt",""),i.setAttribute("aria-hidden","true"),n(o,'alt="" aria-hidden="true"',"serious",i))),o==="svg"&&(!i.getAttribute("aria-hidden")&&!i.getAttribute("aria-label")&&!s.querySelector("title")&&(i.setAttribute("aria-hidden","true"),n(o,'aria-hidden="true" (decorative svg)',"minor",i)),i.getAttribute("focusable")||i.setAttribute("focusable","false")),o==="iframe"&&!i.getAttribute("title")&&!i.getAttribute("aria-label")&&(i.setAttribute("title","embedded content"),i.setAttribute("aria-label","embedded content"),n(o,"title + aria-label added","serious",i)),o==="button"){if(!i.innerText?.trim()&&!i.getAttribute("aria-label")){let _=i.getAttribute("title")||"button";i.setAttribute("aria-label",_),n(o,`aria-label="${_}" (empty button)`,"critical",i)}i.hasAttribute("disabled")&&!i.getAttribute("aria-disabled")&&(i.setAttribute("aria-disabled","true"),t.fixed++)}if(o==="a"){let _=i;!i.innerText?.trim()&&!i.getAttribute("aria-label")&&(i.setAttribute("aria-label",i.getAttribute("title")||"link"),n(o,"aria-label added (empty link)","critical",i)),_.target==="_blank"&&!_.rel?.includes("noopener")&&(_.rel="noopener noreferrer",t.fixed++)}if(D1.has(o)){let _=i;if(!i.getAttribute("aria-label")&&!i.getAttribute("aria-labelledby")){let c=i.getAttribute("placeholder")||i.getAttribute("name")||o;i.setAttribute("aria-label",c),n(o,`aria-label="${c}"`,"serious",i)}if(i.hasAttribute("required")&&!i.getAttribute("aria-required")&&(i.setAttribute("aria-required","true"),t.fixed++),o==="input"&&!_.autocomplete){let c=_.name||"";_.type==="email"||c.includes("email")?_.autocomplete="email":_.type==="tel"||c.includes("tel")?_.autocomplete="tel":_.type==="password"&&(_.autocomplete="current-password"),t.fixed++}}o==="th"&&!i.getAttribute("scope")&&(i.setAttribute("scope",i.closest("thead")?"col":"row"),n(o,"scope added to <th>","moderate",i)),gl[o]&&!i.getAttribute("role")&&(i.setAttribute("role",gl[o]),n(o,`role="${gl[o]}"`,"minor",i));let H=i.getAttribute("role")||"";H==="tab"&&!i.getAttribute("aria-selected")&&(i.setAttribute("aria-selected","false"),t.fixed++),["alert","status","log"].includes(H)&&!i.getAttribute("aria-live")&&(i.setAttribute("aria-live",H==="alert"?"assertive":"polite"),n(o,`aria-live added on role=${H}`,"moderate",i)),H==="combobox"&&!i.getAttribute("aria-expanded")&&(i.setAttribute("aria-expanded","false"),n(o,'aria-expanded="false" on combobox',"serious",i)),(H==="checkbox"||H==="radio")&&!i.getAttribute("aria-checked")&&(i.setAttribute("aria-checked","false"),n(o,`aria-checked="false" on role=${H}`,"serious",i))}),t.renderTime=parseFloat((performance.now()-r).toFixed(2)),t},scan(){let e={fixed:0,scanned:0,renderTime:0,score:100,details:[]};if(typeof document>"u")return e;let t=performance.now(),r=document.querySelectorAll("*");e.scanned=r.length;let a=(n,s,i,o)=>e.details.push({tag:n,fix:s,severity:i,element:o.outerHTML.slice(0,100)});return r.forEach(n=>{let s=n,i=s.tagName.toLowerCase();(i==="a"||i==="button")&&!s.innerText?.trim()&&!s.getAttribute("aria-label")&&a(i,"needs aria-label (empty)","critical",s),i==="img"&&!s.hasAttribute("alt")&&a(i,"needs alt text","serious",s),D1.has(i)&&!s.getAttribute("aria-label")&&!s.getAttribute("aria-labelledby")&&a(i,"needs aria-label","serious",s),i==="iframe"&&!s.getAttribute("title")&&!s.getAttribute("aria-label")&&a(i,"iframe needs title","serious",s)}),e.fixed=e.details.length,e.score=P1(e),e.renderTime=parseFloat((performance.now()-t).toFixed(2)),e},startObserver(e){this.observer||typeof document>"u"||(this.observer=new MutationObserver(()=>this.applyFixes(e)),this.observer.observe(document.body,{childList:!0,subtree:!0,attributes:!1}))},stopObserver(){this.observer?.disconnect(),this.observer=null},announce:Oe,speak:bl,showVisualAlert:k1,trapFocus:no,handlePlainEnglish:C1,handleSummarisePage:w1,handleTranslate:N1,handleVoiceControl:B1,handleSmartLabels:M1,SUPPORTED_LANGUAGES:Yi};var Je=Dr(require("react"));var jt=require("react");xl();var AB=null,gB=null,xs=!1,nf=!1;async function q7(){if(!nf){if(xs){for(;xs;)await new Promise(e=>setTimeout(e,200));return}xs=!0;try{let{pipeline:e}=await Promise.resolve().then(()=>(SB(),IB));AB=await e("feature-extraction","Xenova/all-MiniLM-L6-v2",{device:"webgpu"}),gB=await e("question-answering","Xenova/distilbert-base-cased-distilled-squad",{device:"webgpu"}),nf=!0,xs=!1,console.log("yuktai: Transformers.js models loaded \u2705")}catch(e){throw xs=!1,console.error("yuktai: Transformers.js model load failed",e),e}}}function X7(){return new Promise(e=>{let t=setTimeout(e,1500),r=new MutationObserver(()=>{clearTimeout(t),t=setTimeout(()=>{r.disconnect(),e()},500)});r.observe(document.body,{childList:!0,subtree:!0})})}function z7(){let e=[],t=document.querySelectorAll("*");for(let r of t){if(r.closest("[data-yuktai-panel]"))continue;let a=r.innerText?.trim();a&&a.length>30&&e.push(a);let n=r.getAttribute("aria-label");n&&n.length>10&&e.push(n),(r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement)&&r.placeholder&&e.push(r.placeholder)}return e.join(" ").slice(0,8e3)}function J7(e,t=200,r=50){let a=e.split(/\s+/),n=[];for(let s=0;s<a.length;s+=t-r){let i=a.slice(s,s+t).join(" ");i.trim().length>20&&n.push(i)}return n}function Q7(e,t){let r=0,a=0,n=0;for(let s=0;s<e.length;s++)r+=e[s]*t[s],a+=e[s]*e[s],n+=t[s]*t[s];return r/(Math.sqrt(a)*Math.sqrt(n)+1e-8)}async function LB(e){let t=await AB(e,{pooling:"mean",normalize:!0});return Array.from(t.data)}async function Y7(e,t,r=3){let a=await LB(e),n=await Promise.all(t.map(async s=>{let i=await LB(s),o=Q7(a,i);return{chunk:s,score:o}}));return n.sort((s,i)=>i.score-s.score),n.slice(0,r).map(s=>s.chunk)}async function bB(e){if(!e.trim())return{success:!1,answer:"",error:"Please type a question."};try{await q7(),await X7();let t=z7();if(!t||t.length<50)return{success:!1,answer:"",error:"Not enough content on this page to answer from."};let r=J7(t);if(r.length===0)return{success:!1,answer:"",error:"Could not process page content."};let n=(await Y7(e,r,3)).join(" ... "),s=await gB({question:e,context:n});return!s?.answer||s.answer.trim().length===0?{success:!0,answer:"I could not find a specific answer on this page."}:{success:!0,answer:s.answer.trim()}}catch(t){return console.error("yuktai: Transformers RAG error",t),{success:!1,answer:"",error:t instanceof Error?t.message:"Transformers.js error \u2014 please try again."}}}function TB(){try{return typeof WebAssembly<"u"&&typeof Worker<"u"}catch{return!1}}function xB(){return nf?"ready":xs?"loading":"idle"}var W=require("react/jsx-runtime"),sf={highContrast:!1,reduceMotion:!1,autoFix:!0,dyslexiaFont:!1,fontScale:100,localFont:"",darkMode:!1,largeTargets:!1,speechEnabled:!1,colorBlindMode:"none",showAuditBadge:!1,timeoutWarning:void 0,plainEnglish:!1,summarisePage:!1,translateLanguage:"en",voiceControl:!1,smartLabels:!1},vs=[80,90,100,110,120,130],eU=[{value:"none",label:"None"},{value:"deuteranopia",label:"Deuteranopia"},{value:"protanopia",label:"Protanopia"},{value:"tritanopia",label:"Tritanopia"},{value:"achromatopsia",label:"Greyscale"}],tU=["Prompt API for Gemini Nano","Summarization API for Gemini Nano","Writer API for Gemini Nano","Rewriter API for Gemini Nano","Translation API"];function rU(){let[e,t]=(0,jt.useState)(typeof window<"u"?window.innerWidth:1024);return(0,jt.useEffect)(()=>{let r=()=>t(window.innerWidth);return window.addEventListener("resize",r),()=>window.removeEventListener("resize",r)},[]),{isMobile:e<=480,isTablet:e>480&&e<=768}}function aU({checked:e,onChange:t,label:r,disabled:a=!1}){return(0,W.jsxs)("label",{"aria-label":r,style:{position:"relative",display:"inline-flex",width:"40px",height:"24px",cursor:a?"not-allowed":"pointer",flexShrink:0,opacity:a?.4:1},children:[(0,W.jsx)("input",{type:"checkbox",checked:e,disabled:a,onChange:n=>t(n.target.checked),style:{opacity:0,width:0,height:0,position:"absolute"}}),(0,W.jsx)("span",{style:{position:"absolute",inset:0,borderRadius:"99px",background:e?"#0d9488":"#cbd5e1",transition:"background 0.2s"}}),(0,W.jsx)("span",{style:{position:"absolute",top:"3px",left:e?"19px":"3px",width:"18px",height:"18px",background:"#fff",borderRadius:"50%",transition:"left 0.2s",boxShadow:"0 1px 3px rgba(0,0,0,0.2)",pointerEvents:"none"}})]})}function ys({label:e,color:t="#64748b",badge:r,concept:a}){return(0,W.jsxs)("div",{style:{margin:"10px 18px 4px"},children:[(0,W.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[(0,W.jsx)("p",{style:{margin:0,fontSize:"10px",fontWeight:600,color:t,letterSpacing:"0.06em",textTransform:"uppercase"},children:e}),r&&(0,W.jsx)("span",{style:{fontSize:"9px",fontWeight:500,padding:"1px 7px",borderRadius:"99px",background:"#f5f3ff",color:"#7c3aed",border:"0.5px solid #c4b5fd",whiteSpace:"nowrap"},children:r})]}),a&&(0,W.jsx)("p",{style:{margin:"2px 0 0",fontSize:"9px",color:"#94a3b8",fontStyle:"italic"},children:a})]})}function br({icon:e,label:t,desc:r,checked:a,onChange:n,disabled:s=!1,disabledReason:i,tip:o}){return(0,W.jsxs)("div",{title:s?i:o,style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 18px",gap:"12px"},children:[(0,W.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"10px",flex:1,minWidth:0},children:[(0,W.jsx)("span",{"aria-hidden":"true",style:{width:"32px",height:"32px",borderRadius:"8px",background:s?"#f1f5f9":"#f0fdfa",color:s?"#94a3b8":"#0d9488",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"15px",flexShrink:0,fontWeight:700},children:e}),(0,W.jsxs)("div",{style:{minWidth:0},children:[(0,W.jsx)("p",{style:{margin:0,fontSize:"13px",fontWeight:500,color:s?"#94a3b8":"#0f172a",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:t}),(0,W.jsx)("p",{style:{margin:0,fontSize:"10px",color:"#94a3b8"},children:s?i:r})]})]}),(0,W.jsx)(aU,{checked:a,onChange:n,label:`Toggle ${t}`,disabled:s})]})}function Vt(){return(0,W.jsx)("div",{style:{height:"1px",background:"#f1f5f9"}})}function Pi({steps:e}){return(0,W.jsxs)("div",{style:{margin:"0 18px 8px",padding:"8px 10px",background:"#f8fafc",borderRadius:"8px",border:"0.5px solid #e2e8f0"},children:[(0,W.jsx)("p",{style:{margin:"0 0 4px",fontSize:"9px",fontWeight:600,color:"#64748b",textTransform:"uppercase",letterSpacing:"0.05em"},children:"How to use"}),e.map((t,r)=>(0,W.jsxs)("p",{style:{margin:"0 0 2px",fontSize:"10px",color:"#475569"},children:[r+1,". ",t]},r))]})}var of=(0,jt.forwardRef)(({position:e,settings:t,report:r,isActive:a,aiSupported:n,voiceSupported:s,set:i,onApply:o,onReset:H,onClose:_},c)=>{let{isMobile:l,isTablet:d}=rU(),[h,$]=(0,jt.useState)([]),[m,S]=(0,jt.useState)(""),[I,g]=(0,jt.useState)(""),[T,x]=(0,jt.useState)(!1),[v,k]=(0,jt.useState)(null),[L,V]=(0,jt.useState)("idle");(0,jt.useEffect)(()=>{let M=window;!!(M.LanguageModel||M.ai?.languageModel)&&n?k("gemini"):TB()&&k("transformers")},[n]),(0,jt.useEffect)(()=>{if(v!=="transformers")return;let M=setInterval(()=>{V(xB())},500);return()=>clearInterval(M)},[v]);let K=async()=>{if(!(!m.trim()||T)){if(!v){g("\u26A0\uFE0F No AI engine available on this device.");return}x(!0),g("");try{let M;v==="gemini"?M=await Tl(m):(V("loading"),M=await bB(m),V("ready")),g(M.success&&M.answer?M.answer.replace(/\*\*(.*?)\*\*/g,"$1").replace(/\*(.*?)\*/g,"$1").replace(/#+\s/g,"").trim():"\u26A0\uFE0F "+(M.error||"No answer found on this page"))}catch{g("\u26A0\uFE0F Failed to get answer. Please try again.")}x(!1)}};(0,jt.useEffect)(()=>{(async()=>{try{let F=window;if(!F.queryLocalFonts)return;let N=await F.queryLocalFonts(),G=[...new Set(N.map(te=>te.family))].sort();$(G.slice(0,50))}catch{}})()},[]);let X=v==="gemini"?"Gemini Nano":v==="transformers"?"Transformers.js \xB7 All devices":"Detecting...",Q=v==="transformers"&&L==="loading"?"Loading AI model... (first time only)":"...",z=l?{position:"fixed",bottom:0,left:0,right:0,zIndex:9999,background:"#fff",border:"1px solid #e2e8f0",borderRadius:"16px 16px 0 0",boxShadow:"0 -8px 32px rgba(0,0,0,0.12)",maxHeight:"90vh",overflowY:"auto",fontFamily:"system-ui,-apple-system,sans-serif",width:"100%"}:{position:"fixed",bottom:"84px",[e]:"24px",zIndex:9999,width:d?"300px":"320px",maxWidth:"calc(100vw - 48px)",background:"#fff",border:"1px solid #e2e8f0",borderRadius:"16px",boxShadow:"0 8px 32px rgba(0,0,0,0.12)",maxHeight:"80vh",overflowY:"auto",fontFamily:"system-ui,-apple-system,sans-serif"};return(0,W.jsxs)("div",{ref:c,role:"dialog","aria-modal":"true","aria-label":"yuktai accessibility preferences","data-yuktai-panel":"true",style:z,children:[(0,W.jsxs)("div",{style:{padding:"14px 18px 12px",borderBottom:"1px solid #f1f5f9",display:"flex",alignItems:"flex-start",justifyContent:"space-between",position:"sticky",top:0,background:"#fff",zIndex:1},children:[(0,W.jsxs)("div",{children:[(0,W.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"7px",marginBottom:"4px",flexWrap:"wrap"},children:[(0,W.jsx)("span",{style:{fontSize:"10px",fontWeight:700,padding:"2px 7px",borderRadius:"99px",background:"#f0fdfa",color:"#0d9488",letterSpacing:"0.05em",fontFamily:"monospace"},children:"@yuktishaalaa/yuktai v2.1.0"}),a&&(0,W.jsx)("span",{style:{fontSize:"10px",fontWeight:700,padding:"2px 7px",borderRadius:"99px",background:"#f0fdfa",color:"#0f766e",border:"1px solid #99f6e4"},children:"\u25CF ACTIVE"})]}),(0,W.jsx)("p",{style:{margin:"0 0 1px",fontSize:"15px",fontWeight:600,color:"#0f172a"},children:"Accessibility"}),(0,W.jsx)("p",{style:{margin:0,fontSize:"11px",color:"#64748b"},children:"WCAG 2.2 \xB7 Open source \xB7 Zero cost \xB7 All devices"})]}),(0,W.jsx)("button",{onClick:_,"aria-label":"Close accessibility panel",style:{background:"none",border:"none",cursor:"pointer",padding:"4px",color:"#94a3b8",fontSize:"20px",lineHeight:1,borderRadius:"6px",flexShrink:0,minWidth:l?"44px":"auto",minHeight:l?"44px":"auto",display:"flex",alignItems:"center",justifyContent:"center"},children:"\xD7"})]}),(0,W.jsx)(ys,{label:"\u267F Core Accessibility",concept:"Rule-based engine \u2014 works on all browsers and devices"}),(0,W.jsx)(Pi,{steps:["Toggle any feature on","Click Apply settings","Preferences saved automatically"]}),(0,W.jsx)(br,{icon:"\u{1F527}",label:"Auto-fix ARIA",desc:"Injects missing labels and roles automatically",checked:t.autoFix,onChange:M=>i("autoFix",M),tip:"Fixes aria-label, alt text, roles on every element"}),(0,W.jsx)(Vt,{}),(0,W.jsx)(br,{icon:"\u{1F50A}",label:"Speak on focus",desc:"Browser reads elements aloud as you tab",checked:t.speechEnabled,onChange:M=>i("speechEnabled",M),tip:"Uses browser SpeechSynthesis \u2014 no install needed"}),(0,W.jsx)(Vt,{}),(0,W.jsx)(br,{icon:"\u{1F399}\uFE0F",label:"Voice control",desc:"Say commands to navigate the page",checked:t.voiceControl,onChange:M=>i("voiceControl",M),disabled:!s,disabledReason:"Not supported in this browser",tip:'Say "scroll down", "go to main", "click"'}),(0,W.jsx)(Vt,{}),(0,W.jsx)(ys,{label:"\u{1F916} AI Features",color:"#7c3aed",badge:"Gemini Nano",concept:"Large Language Model running privately on your device \u2014 Chrome 127+ only"}),(0,W.jsx)("div",{style:{margin:"4px 18px 6px",padding:"8px 10px",background:n?"#f0fdfa":"#f5f3ff",borderRadius:"8px",border:`0.5px solid ${n?"#99f6e4":"#c4b5fd"}`,fontSize:"10px",color:n?"#0f766e":"#7c3aed",lineHeight:1.5},children:n?"\u2705 Gemini Nano detected \u2014 AI features ready. Runs privately on your device.":"\u2699\uFE0F AI features need one-time setup \u2014 see guide below."}),!n&&(0,W.jsxs)("div",{style:{margin:"0 18px 8px",padding:"10px 12px",background:"#fafafa",borderRadius:"8px",border:"0.5px solid #e2e8f0",fontSize:"11px",color:"#475569",lineHeight:1.7},children:[(0,W.jsx)("p",{style:{margin:"0 0 6px",fontWeight:600,color:"#0f172a",fontSize:"11px"},children:"\u{1F6E0} One-time setup \u2014 5 steps:"}),(0,W.jsxs)("p",{style:{margin:"0 0 3px"},children:["1. Open Chrome \u2192 ",(0,W.jsx)("code",{style:{background:"#f1f5f9",padding:"1px 5px",borderRadius:"4px",fontSize:"10px",color:"#0d9488",fontFamily:"monospace"},children:"chrome://flags"})]}),(0,W.jsx)("p",{style:{margin:"0 0 3px"},children:"2. Enable each flag:"}),(0,W.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:"2px",margin:"4px 0 6px 10px"},children:tU.map(M=>(0,W.jsxs)("span",{style:{fontSize:"10px",color:"#7c3aed",fontFamily:"monospace"},children:["\u2192 ",M]},M))}),(0,W.jsxs)("p",{style:{margin:"0 0 3px"},children:["3. Click ",(0,W.jsx)("strong",{style:{color:"#0f172a"},children:"Relaunch"})]}),(0,W.jsxs)("p",{style:{margin:"0 0 3px"},children:["4. ",(0,W.jsx)("code",{style:{background:"#f1f5f9",padding:"1px 5px",borderRadius:"4px",fontSize:"10px",color:"#0d9488",fontFamily:"monospace"},children:"chrome://components"})," \u2192 Optimization Guide On Device Model \u2192 Check for update"]}),(0,W.jsx)("p",{style:{margin:"0"},children:"5. Refresh \u2014 AI features unlock automatically \u2705"})]}),(0,W.jsx)(br,{icon:"\u{1F4DD}",label:"Plain English mode",desc:"Rewrites complex text in simple language",checked:t.plainEnglish,onChange:M=>i("plainEnglish",M),disabled:!n,disabledReason:"Enable Gemini Nano \u2014 see setup above",tip:"AI concept: LLM text rewriting"}),(0,W.jsx)(Vt,{}),(0,W.jsx)(br,{icon:"\u{1F4CB}",label:"Summarise page",desc:"3-sentence summary appears at top",checked:t.summarisePage,onChange:M=>i("summarisePage",M),disabled:!n,disabledReason:"Enable Gemini Nano \u2014 see setup above",tip:"AI concept: Abstractive summarisation"}),(0,W.jsx)(Vt,{}),(0,W.jsx)(br,{icon:"\u{1F3F7}\uFE0F",label:"Smart aria-labels",desc:"AI generates meaningful labels for elements",checked:t.smartLabels,onChange:M=>i("smartLabels",M),disabled:!n,disabledReason:"Enable Gemini Nano \u2014 see setup above",tip:"AI concept: Context-aware label generation"}),(0,W.jsx)(Vt,{}),(0,W.jsx)(ys,{label:"\u{1F441}\uFE0F Visual",concept:"CSS filter-based \u2014 works on all browsers and devices"}),(0,W.jsx)(Pi,{steps:["Toggle any visual mode","Changes apply instantly","Works on mobile and desktop"]}),(0,W.jsx)(br,{icon:"\u25D1",label:"High contrast",desc:"Boosts contrast for low vision users",checked:t.highContrast,onChange:M=>i("highContrast",M),tip:"CSS filter: contrast()"}),(0,W.jsx)(Vt,{}),(0,W.jsx)(br,{icon:"\u{1F319}",label:"Dark mode",desc:"Inverts colours \u2014 easy on eyes at night",checked:t.darkMode,onChange:M=>i("darkMode",M),tip:"CSS filter: invert + hue-rotate"}),(0,W.jsx)(Vt,{}),(0,W.jsx)(br,{icon:"\u23F8\uFE0F",label:"Reduce motion",desc:"Disables all animations",checked:t.reduceMotion,onChange:M=>i("reduceMotion",M),tip:"WCAG 2.3.3 \u2014 vestibular disorders"}),(0,W.jsx)(Vt,{}),(0,W.jsx)(br,{icon:"\u{1F446}",label:"Large targets",desc:"44\xD744px minimum touch targets",checked:t.largeTargets,onChange:M=>i("largeTargets",M),tip:"WCAG 2.5.8 \u2014 motor impaired users"}),(0,W.jsx)(Vt,{}),(0,W.jsxs)("div",{style:{padding:"10px 18px"},children:[(0,W.jsx)("p",{style:{margin:"0 0 2px",fontSize:"12px",fontWeight:500,color:"#0f172a"},children:"\u{1F3A8} Colour blindness"}),(0,W.jsx)("p",{style:{margin:"0 0 8px",fontSize:"10px",color:"#94a3b8"},children:"SVG colour matrix filters \u2014 all devices"}),(0,W.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:"6px"},children:eU.map(M=>(0,W.jsx)("button",{onClick:()=>i("colorBlindMode",M.value),"aria-pressed":t.colorBlindMode===M.value,style:{padding:"4px 10px",borderRadius:"20px",fontSize:"11px",fontWeight:500,border:`1px solid ${t.colorBlindMode===M.value?"#0d9488":"#e2e8f0"}`,background:t.colorBlindMode===M.value?"#f0fdfa":"#fff",color:t.colorBlindMode===M.value?"#0d9488":"#64748b",cursor:"pointer",minHeight:l?"36px":"auto"},children:M.label},M.value))})]}),(0,W.jsx)(Vt,{}),(0,W.jsx)(ys,{label:"\u{1F524} Font",concept:"Browser Font API + CSS \u2014 Chrome 103+"}),(0,W.jsx)(Pi,{steps:["Toggle dyslexia font or pick from device","Adjust size with + / \u2212","Saved across visits"]}),(0,W.jsx)(br,{icon:"Aa",label:"Dyslexia-friendly font",desc:"Atkinson Hyperlegible \u2014 research-backed",checked:t.dyslexiaFont,onChange:M=>i("dyslexiaFont",M),tip:"By Braille Institute \u2014 free and open source"}),(0,W.jsx)(Vt,{}),(0,W.jsxs)("div",{style:{padding:"10px 18px"},children:[(0,W.jsx)("p",{style:{margin:"0 0 2px",fontSize:"12px",fontWeight:500,color:"#0f172a"},children:"\u{1F5A5}\uFE0F Local font"}),(0,W.jsx)("p",{style:{margin:"0 0 8px",fontSize:"10px",color:"#94a3b8"},children:"window.queryLocalFonts() \u2014 Chrome 103+"}),h.length>0?(0,W.jsxs)("select",{value:t.localFont,onChange:M=>i("localFont",M.target.value),"aria-label":"Choose a font from your device",style:{width:"100%",padding:"8px 10px",borderRadius:"8px",border:"1px solid #e2e8f0",fontSize:"13px",color:"#0f172a",background:"#fff",cursor:"pointer",height:l?"44px":"36px"},children:[(0,W.jsx)("option",{value:"",children:"System default"}),h.map(M=>(0,W.jsx)("option",{value:M,style:{fontFamily:M},children:M},M))]}):(0,W.jsx)("p",{style:{margin:0,fontSize:"11px",color:"#94a3b8"},children:"Allow font access when Chrome prompts you."})]}),(0,W.jsx)(Vt,{}),(0,W.jsxs)("div",{style:{padding:"10px 18px 14px"},children:[(0,W.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"10px"},children:[(0,W.jsxs)("div",{children:[(0,W.jsx)("p",{style:{margin:0,fontSize:"12px",fontWeight:500,color:"#0f172a"},children:"\u{1F4CF} Text size"}),(0,W.jsx)("p",{style:{margin:0,fontSize:"10px",color:"#94a3b8"},children:"Scales all text on the page"})]}),(0,W.jsxs)("span",{style:{fontSize:"12px",fontWeight:600,color:"#0d9488",background:"#f0fdfa",padding:"2px 8px",borderRadius:"99px"},children:[t.fontScale,"%"]})]}),(0,W.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[(0,W.jsx)("button",{onClick:()=>{let M=vs.indexOf(t.fontScale);M>0&&i("fontScale",vs[M-1])},disabled:t.fontScale<=80,"aria-label":"Decrease text size",style:{width:l?"44px":"30px",height:l?"44px":"30px",borderRadius:"8px",border:"1px solid #e2e8f0",background:"#fff",cursor:t.fontScale<=80?"not-allowed":"pointer",fontSize:"16px",color:t.fontScale<=80?"#cbd5e1":"#0f172a",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:"\u2212"}),(0,W.jsx)("div",{style:{flex:1,display:"flex",gap:"3px"},children:vs.map(M=>(0,W.jsx)("button",{onClick:()=>i("fontScale",M),"aria-label":`Set text size to ${M}%`,style:{flex:1,height:"6px",borderRadius:"99px",border:"none",cursor:"pointer",padding:0,background:M<=t.fontScale?"#0d9488":"#e2e8f0",transition:"background 0.15s"}},M))}),(0,W.jsx)("button",{onClick:()=>{let M=vs.indexOf(t.fontScale);M<vs.length-1&&i("fontScale",vs[M+1])},disabled:t.fontScale>=130,"aria-label":"Increase text size",style:{width:l?"44px":"30px",height:l?"44px":"30px",borderRadius:"8px",border:"1px solid #e2e8f0",background:"#fff",cursor:t.fontScale>=130?"not-allowed":"pointer",fontSize:"16px",color:t.fontScale>=130?"#cbd5e1":"#0f172a",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:"+"})]})]}),(0,W.jsx)(Vt,{}),(0,W.jsx)(ys,{label:"\u{1F310} Translate",color:"#7c3aed",badge:"Gemini Nano",concept:"Chrome Translation API \u2014 on device, no internet after setup"}),(0,W.jsx)(Pi,{steps:["Enable Gemini Nano first","Pick your language","Full page translates instantly"]}),(0,W.jsxs)("div",{style:{padding:"6px 18px 12px"},children:[(0,W.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:"6px"},children:Yi.slice(0,l?8:18).map(M=>(0,W.jsx)("button",{onClick:()=>i("translateLanguage",M.code),"aria-pressed":t.translateLanguage===M.code,disabled:!n,style:{padding:"4px 10px",borderRadius:"20px",fontSize:"11px",fontWeight:500,border:`1px solid ${t.translateLanguage===M.code?"#7c3aed":"#e2e8f0"}`,background:t.translateLanguage===M.code?"#f5f3ff":"#fff",color:t.translateLanguage===M.code?"#7c3aed":"#64748b",cursor:n?"pointer":"not-allowed",opacity:n?1:.5,minHeight:l?"36px":"auto"},children:M.label},M.code))}),!n&&(0,W.jsx)("p",{style:{margin:"6px 0 0",fontSize:"10px",color:"#94a3b8"},children:"Enable Gemini Nano using the setup guide above."})]}),(0,W.jsx)(Vt,{}),(0,W.jsx)(ys,{label:"\u{1F4AC} Ask This Page",color:"#0d9488",badge:X,concept:"RAG \u2014 Retrieval Augmented Generation. Works on all devices including mobile."}),(0,W.jsx)(Pi,{steps:["Type any question about this page","Press Ask or hit Enter",v==="transformers"?"Transformers.js answers \u2014 works on mobile, offline":"Gemini Nano reads page and answers privately","Zero cost. No data leaves your device."]}),(0,W.jsxs)("div",{style:{margin:"0 18px 8px",padding:"6px 10px",background:v==="gemini"?"#f0fdfa":v==="transformers"?"#f5f3ff":"#f8fafc",borderRadius:"8px",border:`0.5px solid ${v==="gemini"?"#99f6e4":v==="transformers"?"#c4b5fd":"#e2e8f0"}`,fontSize:"10px",color:v==="gemini"?"#0f766e":v==="transformers"?"#7c3aed":"#94a3b8"},children:[v==="gemini"&&"\u2705 Using Gemini Nano \u2014 on device, private, instant",v==="transformers"&&"\u2705 Using Transformers.js \u2014 works on mobile and all browsers",!v&&"\u23F3 Detecting AI engine...",v==="transformers"&&L==="loading"&&" \xB7 Loading model...",v==="transformers"&&L==="ready"&&" \xB7 Model ready \u2705"]}),(0,W.jsxs)("div",{style:{padding:"0 18px 14px"},children:[(0,W.jsxs)("div",{style:{display:"flex",gap:"6px",marginBottom:"8px"},children:[(0,W.jsx)("input",{type:"text",value:m,onChange:M=>S(M.target.value),onKeyDown:M=>{M.key==="Enter"&&K()},placeholder:"e.g. What does this page do?",disabled:T||!v,"aria-label":"Ask a question about this page",style:{flex:1,padding:"8px 10px",borderRadius:"8px",border:"1px solid #e2e8f0",fontSize:"12px",color:"#0f172a",background:v?"#fff":"#f8fafc",outline:"none",height:l?"44px":"36px"}}),(0,W.jsx)("button",{onClick:K,disabled:T||!m.trim()||!v,"aria-label":"Ask question",style:{padding:"8px 14px",borderRadius:"8px",border:"none",background:v&&m.trim()&&!T?"#0d9488":"#e2e8f0",color:v&&m.trim()&&!T?"#fff":"#94a3b8",fontSize:"12px",fontWeight:600,cursor:v&&m.trim()&&!T?"pointer":"not-allowed",flexShrink:0,height:l?"44px":"36px",minWidth:"52px",transition:"background 0.2s"},children:T?Q:"Ask"})]}),I&&(0,W.jsxs)("div",{role:"status","aria-live":"polite",style:{padding:"10px 12px",background:"#f0fdfa",border:"1px solid #99f6e4",borderRadius:"8px",fontSize:"12px",color:"#0f766e",lineHeight:1.6,maxHeight:"180px",overflowY:"auto"},children:[(0,W.jsx)("strong",{style:{display:"block",marginBottom:"4px",fontSize:"11px",color:"#0d9488"},children:"\u{1F4AC} Answer"}),I,(0,W.jsx)("button",{onClick:()=>{g(""),S("")},style:{display:"block",marginTop:"6px",background:"none",border:"none",color:"#94a3b8",fontSize:"10px",cursor:"pointer",padding:0},children:"Clear"})]})]}),r&&(0,W.jsx)("div",{role:"status",style:{margin:"0 14px 10px",padding:"8px 12px",background:"#f0fdfa",border:"1px solid #99f6e4",borderRadius:"8px",fontSize:"12px",color:"#0f766e",fontWeight:500,fontFamily:"monospace"},children:r.fixed>0?`\u2713 ${r.fixed} fixes \xB7 ${r.scanned} nodes \xB7 ${r.renderTime}ms \xB7 Score: ${r.score}/100`:`\u2713 0 auto-fixes needed \xB7 ${r.scanned} nodes \xB7 ${r.renderTime}ms`}),(0,W.jsxs)("div",{style:{display:"flex",gap:"8px",padding:"12px 14px 14px",position:l?"sticky":"relative",bottom:l?0:"auto",background:"#fff",borderTop:"1px solid #f1f5f9"},children:[(0,W.jsx)("button",{onClick:H,style:{flex:1,padding:l?"12px 0":"8px 0",fontSize:"13px",fontWeight:500,borderRadius:"9px",border:"1px solid #e2e8f0",background:"#fff",color:"#64748b",cursor:"pointer"},children:"Reset"}),(0,W.jsx)("button",{onClick:o,style:{flex:2,padding:l?"12px 0":"8px 0",fontSize:"13px",fontWeight:600,borderRadius:"9px",border:"none",background:"#0d9488",color:"#fff",cursor:"pointer"},children:"Apply settings"})]})]})});of.displayName="WidgetPanel";var st=require("react/jsx-runtime");async function nU(){try{if(typeof window>"u")return!1;let e=window;if(e.LanguageModel)try{if(typeof e.LanguageModel.availability=="function"){let r=await e.LanguageModel.availability();if(console.log("yuktai: LanguageModel.availability() =",r),r==="readily"||r==="available"||r==="downloadable")return!0}else return!0}catch{}if(e.Summarizer)try{if(typeof e.Summarizer.availability=="function"){let r=await e.Summarizer.availability();if(r==="readily"||r==="available")return!0}else return!0}catch{}if(e.Rewriter)try{if(typeof e.Rewriter.availability=="function"){let r=await e.Rewriter.availability();if(r==="readily"||r==="available")return!0}else return!0}catch{}if(e.Writer)try{if(typeof e.Writer.availability=="function"){let r=await e.Writer.availability();if(r==="readily"||r==="available")return!0}else return!0}catch{}let t=e.ai||globalThis.ai;if(t){if(t.languageModel?.availability)try{let r=await t.languageModel.availability();if(r==="readily"||r==="downloadable"||r==="available")return!0}catch{}if(t.languageModel?.capabilities)try{let r=await t.languageModel.capabilities();if(r?.available==="readily"||r?.available==="after-download")return!0}catch{}if(t.languageModel&&typeof t.languageModel.create=="function")return!0;if(t.summarizer?.capabilities)try{if((await t.summarizer.capabilities())?.available!=="no")return!0}catch{}if(t.rewriter?.capabilities)try{if((await t.rewriter.capabilities())?.available!=="no")return!0}catch{}if(t.writer?.capabilities)try{if((await t.writer.capabilities())?.available!=="no")return!0}catch{}if(t.summarizer||t.rewriter||t.writer||t.languageModel)return!0}return!!(e.Translator||e.translation?.canTranslate)}catch{return!1}}function Gc({position:e="left",children:t,config:r={},showRag:a=!1}){let[n,s]=(0,Je.useState)(!1),[i,o]=(0,Je.useState)(sf),[H,_]=(0,Je.useState)(null),[c,l]=(0,Je.useState)(!1),[d,h]=(0,Je.useState)(!1),[$,m]=(0,Je.useState)(!1),S=Je.default.useRef(null),[I,g]=(0,Je.useState)(!1),[T,x]=(0,Je.useState)(""),[v,k]=(0,Je.useState)(""),[L,V]=(0,Je.useState)(!1),K=(0,Je.useCallback)(async()=>{if(!(!T.trim()||L||!d)){V(!0),k("");try{let{askPage:G}=await Promise.resolve().then(()=>(xl(),O1)),te=await G(T);k(te.success?te.answer.replace(/\*\*(.*?)\*\*/g,"$1").replace(/\*(.*?)\*/g,"$1").replace(/#+\s/g,"").trim():"\u26A0\uFE0F "+(te.error||"No answer found."))}catch{k("\u26A0\uFE0F Something went wrong.")}V(!1)}},[T,L,d]);(0,Je.useEffect)(()=>{if(typeof window>"u")return;let te=setTimeout(async()=>{let B=window;console.log("yuktai: Checking AI APIs..."),console.log("yuktai: window.ai =",B.ai),console.log("yuktai: window.LanguageModel =",B.LanguageModel),console.log("yuktai: window.Summarizer =",B.Summarizer),console.log("yuktai: window.Rewriter =",B.Rewriter),console.log("yuktai: window.Writer =",B.Writer);let O=await nU();h(O),O?console.log("yuktai: Chrome Built-in AI detected \u2705"):(console.log("yuktai: Chrome Built-in AI not detected \u274C"),console.log("yuktai: Enable flags at chrome://flags and download model at chrome://components"));let U=!!(B.SpeechRecognition||B.webkitSpeechRecognition);m(U)},800);return()=>clearTimeout(te)},[]),(0,Je.useEffect)(()=>{if(!(typeof window>"u"))try{let G=localStorage.getItem("yuktai-a11y-prefs");if(G){let te=JSON.parse(G);o(B=>({...B,...te}))}}catch{}},[]);let X=(0,Je.useCallback)(async G=>{let te={enabled:!0,highContrast:G.highContrast,darkMode:G.darkMode,reduceMotion:G.reduceMotion,largeTargets:G.largeTargets,speechEnabled:G.speechEnabled,autoFix:G.autoFix,dyslexiaFont:G.dyslexiaFont,localFont:G.localFont,fontSizeMultiplier:G.fontScale/100,colorBlindMode:G.colorBlindMode,showAuditBadge:G.showAuditBadge,showSkipLinks:!0,showPreferencePanel:!1,plainEnglish:G.plainEnglish,summarisePage:G.summarisePage,translateLanguage:G.translateLanguage,voiceControl:G.voiceControl,smartLabels:G.smartLabels,...r};await Jt.execute(te);let B=Jt.applyFixes(te);_(B),l(!0)},[r]),Q=(0,Je.useCallback)(async()=>{try{localStorage.setItem("yuktai-a11y-prefs",JSON.stringify(i))}catch{}await X(i),s(!1)},[i,X]),z=(0,Je.useCallback)(()=>{o(sf);try{localStorage.removeItem("yuktai-a11y-prefs")}catch{}let G=document.documentElement;["data-yuktai-high-contrast","data-yuktai-dark","data-yuktai-reduce-motion","data-yuktai-large-targets","data-yuktai-keyboard","data-yuktai-dyslexia"].forEach(te=>G.removeAttribute(te)),document.body.style.filter="",document.body.style.fontFamily="",document.documentElement.style.fontSize="",_(null),l(!1)},[]),M=(0,Je.useCallback)((G,te)=>{o(B=>({...B,[G]:te}))},[]);(0,Je.useEffect)(()=>{let G=te=>{te.key==="Escape"&&(n&&s(!1),I&&g(!1))};return window.addEventListener("keydown",G),()=>window.removeEventListener("keydown",G)},[n,I]),(0,Je.useEffect)(()=>{n&&S.current&&Jt.trapFocus(S.current)},[n]);let F={position:"fixed",bottom:"24px",[e]:"24px",zIndex:9998,width:"52px",height:"52px",borderRadius:"50%",background:c?"#0d9488":"#1a73e8",color:"#fff",border:"none",cursor:"pointer",fontSize:"22px",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 4px 16px rgba(0,0,0,0.25)",transition:"transform 0.15s, background 0.2s"},N={position:"fixed",bottom:"84px",[e]:"24px",zIndex:9998,width:"52px",height:"52px",borderRadius:"50%",background:I?"#7c3aed":"#6d28d9",color:"#fff",border:"none",cursor:"pointer",fontSize:"22px",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 4px 16px rgba(0,0,0,0.25)",transition:"transform 0.15s, background 0.2s"};return(0,st.jsxs)(st.Fragment,{children:[t,a&&(0,st.jsx)("button",{style:N,"aria-label":"Ask a question about this page","aria-haspopup":"dialog","aria-expanded":I,onClick:()=>{g(G=>!G),s(!1)},onMouseEnter:G=>{G.currentTarget.style.transform="scale(1.08)"},onMouseLeave:G=>{G.currentTarget.style.transform="scale(1)"},children:"\u{1F4AC}"}),a&&I&&(0,st.jsxs)("div",{role:"dialog","aria-modal":"true","aria-label":"Ask this page","data-yuktai-panel":"true",style:{position:"fixed",bottom:"148px",[e]:"24px",zIndex:9999,width:"300px",maxWidth:"calc(100vw - 48px)",background:"#fff",border:"1px solid #e2e8f0",borderRadius:"16px",boxShadow:"0 8px 32px rgba(0,0,0,0.12)",fontFamily:"system-ui,-apple-system,sans-serif",padding:"14px"},children:[(0,st.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",marginBottom:"10px"},children:[(0,st.jsxs)("div",{children:[(0,st.jsx)("p",{style:{margin:"0 0 2px",fontSize:"13px",fontWeight:600,color:"#0f172a"},children:"\u{1F4AC} Ask this page"}),(0,st.jsx)("p",{style:{margin:0,fontSize:"10px",color:"#7c3aed"},children:"Gemini Nano \xB7 On device \xB7 Zero cost"})]}),(0,st.jsx)("button",{onClick:()=>g(!1),"aria-label":"Close ask panel",style:{background:"none",border:"none",cursor:"pointer",color:"#94a3b8",fontSize:"18px",lineHeight:1,padding:"2px",borderRadius:"4px"},children:"\xD7"})]}),(0,st.jsxs)("div",{style:{display:"flex",gap:"6px",marginBottom:"8px"},children:[(0,st.jsx)("input",{type:"text",value:T,onChange:G=>x(G.target.value),onKeyDown:G=>{G.key==="Enter"&&K()},placeholder:"e.g. What does this page do?",disabled:!d||L,"aria-label":"Ask a question about this page",style:{flex:1,padding:"8px 10px",borderRadius:"8px",border:"1px solid #e2e8f0",fontSize:"12px",color:"#0f172a",background:d?"#fff":"#f8fafc",outline:"none",height:"36px"}}),(0,st.jsx)("button",{onClick:K,disabled:!d||L||!T.trim(),"aria-label":"Submit question",style:{padding:"8px 12px",borderRadius:"8px",border:"none",background:d&&T.trim()&&!L?"#7c3aed":"#e2e8f0",color:d&&T.trim()&&!L?"#fff":"#94a3b8",fontSize:"12px",fontWeight:600,cursor:d&&T.trim()&&!L?"pointer":"not-allowed",height:"36px",minWidth:"48px",transition:"background 0.2s"},children:L?"...":"Ask"})]}),v&&(0,st.jsxs)("div",{style:{padding:"10px",background:"#f5f3ff",borderRadius:"8px",fontSize:"12px",color:"#4c1d95",lineHeight:1.6,maxHeight:"180px",overflowY:"auto"},children:[(0,st.jsx)("strong",{style:{display:"block",marginBottom:"4px",fontSize:"11px",color:"#7c3aed"},children:"\u{1F4AC} Answer"}),v,(0,st.jsx)("button",{onClick:()=>{k(""),x("")},style:{display:"block",marginTop:"6px",background:"none",border:"none",color:"#94a3b8",fontSize:"10px",cursor:"pointer",padding:0},children:"Clear"})]}),!d&&(0,st.jsx)("p",{style:{margin:"4px 0 0",fontSize:"10px",color:"#94a3b8"},children:"Enable Gemini Nano via chrome://flags to use this feature."})]}),(0,st.jsx)("button",{style:F,"aria-label":"Open accessibility preferences","aria-haspopup":"dialog","aria-expanded":n,"data-yuktai-pref-toggle":"true",onClick:()=>{s(G=>!G),g(!1)},onMouseEnter:G=>{G.currentTarget.style.transform="scale(1.08)"},onMouseLeave:G=>{G.currentTarget.style.transform="scale(1)"},children:"\u267F"}),n&&(0,st.jsx)(of,{ref:S,position:e,settings:i,report:H,isActive:c,aiSupported:d,voiceSupported:$,set:M,onApply:Q,onReset:z,onClose:()=>s(!1)})]})}var ki={name:"ai.text",async execute(e){return`\u{1F916} YuktAI says: ${e}`}};var Ri={name:"voice.text",async execute(e){return!e||e.trim()===""?"\u{1F3A4} No speech detected":`\u{1F3A4} You said: ${e}`}};var wa=class{plugins=new Map;register(t,r){if(!r||typeof r.execute!="function")throw new Error(`Invalid plugin: ${t}`);this.plugins.set(t,r)}use(t){return this.plugins.get(t)}async run(t,r){try{let a=this.use(t);if(!a)throw new Error(`Plugin not found: ${t}`);return await a.execute(r)}catch(a){throw console.error(`[YuktAI Runtime Error in ${t}]:`,a),a}}getPlugins(){return Array.from(this.plugins.keys())}};function sU(){if(typeof globalThis>"u")return new wa;if(!globalThis.__yuktai_runtime__){let e=new wa;e.register(Jt.name,Jt),e.register(ki.name,ki),e.register(Ri.name,Ri),globalThis.__yuktai_runtime__=e}return globalThis.__yuktai_runtime__}var vB=typeof window<"u"?sU():new wa,iU={wcagPlugin:Jt,list(){return vB.getPlugins()},use(e){return vB.use(e)},fix(e){return Jt.applyFixes({enabled:!0,autoFix:!0,...e})},scan(){return Jt.scan()}};0&&(module.exports={Runtime,YuktAI,YuktAIWrapper,aiPlugin,voicePlugin,wcag,wcagPlugin});
430
- /*! Bundled license information:
431
-
432
- sharp/lib/is.js:
433
- sharp/lib/libvips.js:
434
- sharp/lib/sharp.js:
435
- sharp/lib/constructor.js:
436
- sharp/lib/input.js:
437
- sharp/lib/resize.js:
438
- sharp/lib/composite.js:
439
- sharp/lib/operation.js:
440
- sharp/lib/colour.js:
441
- sharp/lib/channel.js:
442
- sharp/lib/output.js:
443
- sharp/lib/utility.js:
444
- sharp/lib/index.js:
445
- (*!
446
- Copyright 2013 Lovell Fuller and others.
447
- SPDX-License-Identifier: Apache-2.0
448
- *)
449
-
450
- @huggingface/transformers/dist/transformers.node.mjs:
451
- (*! Bundled license information:
452
-
453
- onnxruntime-web/dist/ort.webgpu.bundle.min.mjs:
454
- (*!
455
- * ONNX Runtime Web v1.26.0-dev.20260416-b7804b056c
456
- * Copyright (c) Microsoft Corporation. All rights reserved.
457
- * Licensed under the MIT License.
458
- *)
459
- *)
460
- */
390
+ `,document.body.appendChild(e),_e=e}function Qe(e){let t={critical:20,serious:10,moderate:5,minor:2},a=e.details.reduce((i,n)=>i+(t[n.severity]||0),0);return Math.max(0,Math.min(100,100-a))}var T={name:"yuktai-a11y",version:"4.0.0",observer:null,async execute(e){if(!e.enabled)return this.stopObserver(),"yuktai: disabled.";N=e,$t(e),Bt(),Nt(),Pt(),zt(),e.showSkipLinks!==!1&&Rt(),e.showPreferencePanel,Ft(e);let t=this.applyFixes(e);t.score=Qe(t),e.showAuditBadge&&Ht(t),e.timeoutWarning&&et(e.timeoutWarning),e.autoFix&&this.startObserver(e),e.plainEnglish&&await Ke(!0),e.summarisePage&&await Ye(!0),e.translateLanguage&&e.translateLanguage!=="en"&&await Ue(e.translateLanguage),e.voiceControl&&await Je(!0),e.smartLabels&&await Xe(!0);let a=`${t.fixed} fixes applied. Score: ${t.score}/100.`;return f(a,t.score>=90?"success":"info",!1),`yuktai v4.0.0: ${a} Scanned ${t.scanned} elements in ${t.renderTime}ms.`},applyFixes(e){let t={fixed:0,scanned:0,renderTime:0,score:100,details:[]};if(typeof document>"u")return t;let a=performance.now(),i=document.querySelectorAll("*");t.scanned=i.length;let n=(s,o,c,g)=>{t.details.push({tag:s,fix:o,severity:c,element:g.outerHTML.slice(0,100)}),t.fixed++};return i.forEach(s=>{let o=s,c=o.tagName.toLowerCase();if(c==="html"&&!o.getAttribute("lang")&&(o.setAttribute("lang","en"),n(c,'lang="en" added',"critical",o)),c==="meta"){let u=o.getAttribute("name"),v=o.getAttribute("content")||"";u==="viewport"&&v.includes("user-scalable=no")&&(o.setAttribute("content",v.replace("user-scalable=no","user-scalable=yes")),n(c,"user-scalable=yes restored","serious",o)),u==="viewport"&&/maximum-scale=1(?:[^0-9]|$)/.test(v)&&(o.setAttribute("content",v.replace(/maximum-scale=1(?=[^0-9]|$)/,"maximum-scale=5")),n(c,"maximum-scale=5 restored","serious",o))}if(c==="main"&&!o.getAttribute("tabindex")&&(o.setAttribute("tabindex","-1"),o.getAttribute("id")||o.setAttribute("id","main-content")),c==="img"&&(o.hasAttribute("alt")||(o.setAttribute("alt",""),o.setAttribute("aria-hidden","true"),n(c,'alt="" aria-hidden="true"',"serious",o))),c==="svg"&&(!o.getAttribute("aria-hidden")&&!o.getAttribute("aria-label")&&!s.querySelector("title")&&(o.setAttribute("aria-hidden","true"),n(c,'aria-hidden="true" (decorative svg)',"minor",o)),o.getAttribute("focusable")||o.setAttribute("focusable","false")),c==="iframe"&&!o.getAttribute("title")&&!o.getAttribute("aria-label")&&(o.setAttribute("title","embedded content"),o.setAttribute("aria-label","embedded content"),n(c,"title + aria-label added","serious",o)),c==="button"){if(!o.innerText?.trim()&&!o.getAttribute("aria-label")){let u=o.getAttribute("title")||"button";o.setAttribute("aria-label",u),n(c,`aria-label="${u}" (empty button)`,"critical",o)}o.hasAttribute("disabled")&&!o.getAttribute("aria-disabled")&&(o.setAttribute("aria-disabled","true"),t.fixed++)}if(c==="a"){let u=o;!o.innerText?.trim()&&!o.getAttribute("aria-label")&&(o.setAttribute("aria-label",o.getAttribute("title")||"link"),n(c,"aria-label added (empty link)","critical",o)),u.target==="_blank"&&!u.rel?.includes("noopener")&&(u.rel="noopener noreferrer",t.fixed++)}if(je.has(c)){let u=o;if(!o.getAttribute("aria-label")&&!o.getAttribute("aria-labelledby")){let v=o.getAttribute("placeholder")||o.getAttribute("name")||c;o.setAttribute("aria-label",v),n(c,`aria-label="${v}"`,"serious",o)}if(o.hasAttribute("required")&&!o.getAttribute("aria-required")&&(o.setAttribute("aria-required","true"),t.fixed++),c==="input"&&!u.autocomplete){let v=u.name||"";u.type==="email"||v.includes("email")?u.autocomplete="email":u.type==="tel"||v.includes("tel")?u.autocomplete="tel":u.type==="password"&&(u.autocomplete="current-password"),t.fixed++}}c==="th"&&!o.getAttribute("scope")&&(o.setAttribute("scope",o.closest("thead")?"col":"row"),n(c,"scope added to <th>","moderate",o)),he[c]&&!o.getAttribute("role")&&(o.setAttribute("role",he[c]),n(c,`role="${he[c]}"`,"minor",o));let g=o.getAttribute("role")||"";g==="tab"&&!o.getAttribute("aria-selected")&&(o.setAttribute("aria-selected","false"),t.fixed++),["alert","status","log"].includes(g)&&!o.getAttribute("aria-live")&&(o.setAttribute("aria-live",g==="alert"?"assertive":"polite"),n(c,`aria-live added on role=${g}`,"moderate",o)),g==="combobox"&&!o.getAttribute("aria-expanded")&&(o.setAttribute("aria-expanded","false"),n(c,'aria-expanded="false" on combobox',"serious",o)),(g==="checkbox"||g==="radio")&&!o.getAttribute("aria-checked")&&(o.setAttribute("aria-checked","false"),n(c,`aria-checked="false" on role=${g}`,"serious",o))}),t.renderTime=parseFloat((performance.now()-a).toFixed(2)),t},scan(){let e={fixed:0,scanned:0,renderTime:0,score:100,details:[]};if(typeof document>"u")return e;let t=performance.now(),a=document.querySelectorAll("*");e.scanned=a.length;let i=(n,s,o,c)=>e.details.push({tag:n,fix:s,severity:o,element:c.outerHTML.slice(0,100)});return a.forEach(n=>{let s=n,o=s.tagName.toLowerCase();(o==="a"||o==="button")&&!s.innerText?.trim()&&!s.getAttribute("aria-label")&&i(o,"needs aria-label (empty)","critical",s),o==="img"&&!s.hasAttribute("alt")&&i(o,"needs alt text","serious",s),je.has(o)&&!s.getAttribute("aria-label")&&!s.getAttribute("aria-labelledby")&&i(o,"needs aria-label","serious",s),o==="iframe"&&!s.getAttribute("title")&&!s.getAttribute("aria-label")&&i(o,"iframe needs title","serious",s)}),e.fixed=e.details.length,e.score=Qe(e),e.renderTime=parseFloat((performance.now()-t).toFixed(2)),e},startObserver(e){this.observer||typeof document>"u"||(this.observer=new MutationObserver(()=>this.applyFixes(e)),this.observer.observe(document.body,{childList:!0,subtree:!0,attributes:!1}))},stopObserver(){this.observer?.disconnect(),this.observer=null},announce:f,speak:we,showVisualAlert:Ze,trapFocus:ie,handlePlainEnglish:Ke,handleSummarisePage:Ye,handleTranslate:Ue,handleVoiceControl:Je,handleSmartLabels:Xe,SUPPORTED_LANGUAGES:ee};var m=Me(require("react"));var A=require("react");ke();var nt=null,ot=null,O=!1,Ae=!1;async function Gt(){if(!Ae){if(O){for(;O;)await new Promise(e=>setTimeout(e,200));return}O=!0;try{let{pipeline:e}=await import("@xenova/transformers");nt=await e("feature-extraction","Xenova/all-MiniLM-L6-v2",{device:"webgpu"}),ot=await e("question-answering","Xenova/distilbert-base-cased-distilled-squad",{device:"webgpu"}),Ae=!0,O=!1,console.log("yuktai: Transformers.js models loaded \u2705")}catch(e){throw O=!1,console.error("yuktai: Transformers.js model load failed",e),e}}}function Dt(){return new Promise(e=>{let t=setTimeout(e,1500),a=new MutationObserver(()=>{clearTimeout(t),t=setTimeout(()=>{a.disconnect(),e()},500)});a.observe(document.body,{childList:!0,subtree:!0})})}function _t(){let e=[],t=document.querySelectorAll("*");for(let a of t){if(a.closest("[data-yuktai-panel]"))continue;let i=a.innerText?.trim();i&&i.length>30&&e.push(i);let n=a.getAttribute("aria-label");n&&n.length>10&&e.push(n),(a instanceof HTMLInputElement||a instanceof HTMLTextAreaElement)&&a.placeholder&&e.push(a.placeholder)}return e.join(" ").slice(0,8e3)}function Vt(e,t=200,a=50){let i=e.split(/\s+/),n=[];for(let s=0;s<i.length;s+=t-a){let o=i.slice(s,s+t).join(" ");o.trim().length>20&&n.push(o)}return n}function jt(e,t){let a=0,i=0,n=0;for(let s=0;s<e.length;s++)a+=e[s]*t[s],i+=e[s]*e[s],n+=t[s]*t[s];return a/(Math.sqrt(i)*Math.sqrt(n)+1e-8)}async function at(e){let t=await nt(e,{pooling:"mean",normalize:!0});return Array.from(t.data)}async function Kt(e,t,a=3){let i=await at(e),n=await Promise.all(t.map(async s=>{let o=await at(s),c=jt(i,o);return{chunk:s,score:c}}));return n.sort((s,o)=>o.score-s.score),n.slice(0,a).map(s=>s.chunk)}async function it(e){if(!e.trim())return{success:!1,answer:"",error:"Please type a question."};try{await Gt(),await Dt();let t=_t();if(!t||t.length<50)return{success:!1,answer:"",error:"Not enough content on this page to answer from."};let a=Vt(t);if(a.length===0)return{success:!1,answer:"",error:"Could not process page content."};let n=(await Kt(e,a,3)).join(" ... "),s=await ot({question:e,context:n});return!s?.answer||s.answer.trim().length===0?{success:!0,answer:"I could not find a specific answer on this page."}:{success:!0,answer:s.answer.trim()}}catch(t){return console.error("yuktai: Transformers RAG error",t),{success:!1,answer:"",error:t instanceof Error?t.message:"Transformers.js error \u2014 please try again."}}}function rt(){try{return typeof WebAssembly<"u"&&typeof Worker<"u"}catch{return!1}}function st(){return Ae?"ready":O?"loading":"idle"}var r=require("react/jsx-runtime"),Se={highContrast:!1,reduceMotion:!1,autoFix:!0,dyslexiaFont:!1,fontScale:100,localFont:"",darkMode:!1,largeTargets:!1,speechEnabled:!1,colorBlindMode:"none",showAuditBadge:!1,timeoutWarning:void 0,plainEnglish:!1,summarisePage:!1,translateLanguage:"en",voiceControl:!1,smartLabels:!1},q=[80,90,100,110,120,130],Yt=[{value:"none",label:"None"},{value:"deuteranopia",label:"Deuteranopia"},{value:"protanopia",label:"Protanopia"},{value:"tritanopia",label:"Tritanopia"},{value:"achromatopsia",label:"Greyscale"}],Ut=["Prompt API for Gemini Nano","Summarization API for Gemini Nano","Writer API for Gemini Nano","Rewriter API for Gemini Nano","Translation API"];function Jt(){let[e,t]=(0,A.useState)(typeof window<"u"?window.innerWidth:1024);return(0,A.useEffect)(()=>{let a=()=>t(window.innerWidth);return window.addEventListener("resize",a),()=>window.removeEventListener("resize",a)},[]),{isMobile:e<=480,isTablet:e>480&&e<=768}}function Xt({checked:e,onChange:t,label:a,disabled:i=!1}){return(0,r.jsxs)("label",{"aria-label":a,style:{position:"relative",display:"inline-flex",width:"40px",height:"24px",cursor:i?"not-allowed":"pointer",flexShrink:0,opacity:i?.4:1},children:[(0,r.jsx)("input",{type:"checkbox",checked:e,disabled:i,onChange:n=>t(n.target.checked),style:{opacity:0,width:0,height:0,position:"absolute"}}),(0,r.jsx)("span",{style:{position:"absolute",inset:0,borderRadius:"99px",background:e?"#0d9488":"#cbd5e1",transition:"background 0.2s"}}),(0,r.jsx)("span",{style:{position:"absolute",top:"3px",left:e?"19px":"3px",width:"18px",height:"18px",background:"#fff",borderRadius:"50%",transition:"left 0.2s",boxShadow:"0 1px 3px rgba(0,0,0,0.2)",pointerEvents:"none"}})]})}function G({label:e,color:t="#64748b",badge:a,concept:i}){return(0,r.jsxs)("div",{style:{margin:"10px 18px 4px"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:"10px",fontWeight:600,color:t,letterSpacing:"0.06em",textTransform:"uppercase"},children:e}),a&&(0,r.jsx)("span",{style:{fontSize:"9px",fontWeight:500,padding:"1px 7px",borderRadius:"99px",background:"#f5f3ff",color:"#7c3aed",border:"0.5px solid #c4b5fd",whiteSpace:"nowrap"},children:a})]}),i&&(0,r.jsx)("p",{style:{margin:"2px 0 0",fontSize:"9px",color:"#94a3b8",fontStyle:"italic"},children:i})]})}function M({icon:e,label:t,desc:a,checked:i,onChange:n,disabled:s=!1,disabledReason:o,tip:c}){return(0,r.jsxs)("div",{title:s?o:c,style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 18px",gap:"12px"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"10px",flex:1,minWidth:0},children:[(0,r.jsx)("span",{"aria-hidden":"true",style:{width:"32px",height:"32px",borderRadius:"8px",background:s?"#f1f5f9":"#f0fdfa",color:s?"#94a3b8":"#0d9488",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"15px",flexShrink:0,fontWeight:700},children:e}),(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:"13px",fontWeight:500,color:s?"#94a3b8":"#0f172a",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:t}),(0,r.jsx)("p",{style:{margin:0,fontSize:"10px",color:"#94a3b8"},children:s?o:a})]})]}),(0,r.jsx)(Xt,{checked:i,onChange:n,label:`Toggle ${t}`,disabled:s})]})}function k(){return(0,r.jsx)("div",{style:{height:"1px",background:"#f1f5f9"}})}function j({steps:e}){return(0,r.jsxs)("div",{style:{margin:"0 18px 8px",padding:"8px 10px",background:"#f8fafc",borderRadius:"8px",border:"0.5px solid #e2e8f0"},children:[(0,r.jsx)("p",{style:{margin:"0 0 4px",fontSize:"9px",fontWeight:600,color:"#64748b",textTransform:"uppercase",letterSpacing:"0.05em"},children:"How to use"}),e.map((t,a)=>(0,r.jsxs)("p",{style:{margin:"0 0 2px",fontSize:"10px",color:"#475569"},children:[a+1,". ",t]},a))]})}var Te=(0,A.forwardRef)(({position:e,settings:t,report:a,isActive:i,aiSupported:n,voiceSupported:s,set:o,onApply:c,onReset:g,onClose:u},v)=>{let{isMobile:x,isTablet:E}=Jt(),[U,se]=(0,A.useState)([]),[R,W]=(0,A.useState)(""),[z,P]=(0,A.useState)(""),[w,D]=(0,A.useState)(!1),[p,H]=(0,A.useState)(null),[C,F]=(0,A.useState)("idle");(0,A.useEffect)(()=>{let l=window;!!(l.LanguageModel||l.ai?.languageModel)&&n?H("gemini"):rt()&&H("transformers")},[n]),(0,A.useEffect)(()=>{if(p!=="transformers")return;let l=setInterval(()=>{F(st())},500);return()=>clearInterval(l)},[p]);let _=async()=>{if(!(!R.trim()||w)){if(!p){P("\u26A0\uFE0F No AI engine available on this device.");return}D(!0),P("");try{let l;p==="gemini"?l=await ve(R):(F("loading"),l=await it(R),F("ready")),P(l.success&&l.answer?l.answer.replace(/\*\*(.*?)\*\*/g,"$1").replace(/\*(.*?)\*/g,"$1").replace(/#+\s/g,"").trim():"\u26A0\uFE0F "+(l.error||"No answer found on this page"))}catch{P("\u26A0\uFE0F Failed to get answer. Please try again.")}D(!1)}};(0,A.useEffect)(()=>{(async()=>{try{let V=window;if(!V.queryLocalFonts)return;let de=await V.queryLocalFonts(),d=[...new Set(de.map(h=>h.family))].sort();se(d.slice(0,50))}catch{}})()},[]);let J=p==="gemini"?"Gemini Nano":p==="transformers"?"Transformers.js \xB7 All devices":"Detecting...",le=p==="transformers"&&C==="loading"?"Loading AI model... (first time only)":"...",ce=x?{position:"fixed",bottom:0,left:0,right:0,zIndex:9999,background:"#fff",border:"1px solid #e2e8f0",borderRadius:"16px 16px 0 0",boxShadow:"0 -8px 32px rgba(0,0,0,0.12)",maxHeight:"90vh",overflowY:"auto",fontFamily:"system-ui,-apple-system,sans-serif",width:"100%"}:{position:"fixed",bottom:"84px",[e]:"24px",zIndex:9999,width:E?"300px":"320px",maxWidth:"calc(100vw - 48px)",background:"#fff",border:"1px solid #e2e8f0",borderRadius:"16px",boxShadow:"0 8px 32px rgba(0,0,0,0.12)",maxHeight:"80vh",overflowY:"auto",fontFamily:"system-ui,-apple-system,sans-serif"};return(0,r.jsxs)("div",{ref:v,role:"dialog","aria-modal":"true","aria-label":"yuktai accessibility preferences","data-yuktai-panel":"true",style:ce,children:[(0,r.jsxs)("div",{style:{padding:"14px 18px 12px",borderBottom:"1px solid #f1f5f9",display:"flex",alignItems:"flex-start",justifyContent:"space-between",position:"sticky",top:0,background:"#fff",zIndex:1},children:[(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"7px",marginBottom:"4px",flexWrap:"wrap"},children:[(0,r.jsx)("span",{style:{fontSize:"10px",fontWeight:700,padding:"2px 7px",borderRadius:"99px",background:"#f0fdfa",color:"#0d9488",letterSpacing:"0.05em",fontFamily:"monospace"},children:"@yuktishaalaa/yuktai v2.1.0"}),i&&(0,r.jsx)("span",{style:{fontSize:"10px",fontWeight:700,padding:"2px 7px",borderRadius:"99px",background:"#f0fdfa",color:"#0f766e",border:"1px solid #99f6e4"},children:"\u25CF ACTIVE"})]}),(0,r.jsx)("p",{style:{margin:"0 0 1px",fontSize:"15px",fontWeight:600,color:"#0f172a"},children:"Accessibility"}),(0,r.jsx)("p",{style:{margin:0,fontSize:"11px",color:"#64748b"},children:"WCAG 2.2 \xB7 Open source \xB7 Zero cost \xB7 All devices"})]}),(0,r.jsx)("button",{onClick:u,"aria-label":"Close accessibility panel",style:{background:"none",border:"none",cursor:"pointer",padding:"4px",color:"#94a3b8",fontSize:"20px",lineHeight:1,borderRadius:"6px",flexShrink:0,minWidth:x?"44px":"auto",minHeight:x?"44px":"auto",display:"flex",alignItems:"center",justifyContent:"center"},children:"\xD7"})]}),(0,r.jsx)(G,{label:"\u267F Core Accessibility",concept:"Rule-based engine \u2014 works on all browsers and devices"}),(0,r.jsx)(j,{steps:["Toggle any feature on","Click Apply settings","Preferences saved automatically"]}),(0,r.jsx)(M,{icon:"\u{1F527}",label:"Auto-fix ARIA",desc:"Injects missing labels and roles automatically",checked:t.autoFix,onChange:l=>o("autoFix",l),tip:"Fixes aria-label, alt text, roles on every element"}),(0,r.jsx)(k,{}),(0,r.jsx)(M,{icon:"\u{1F50A}",label:"Speak on focus",desc:"Browser reads elements aloud as you tab",checked:t.speechEnabled,onChange:l=>o("speechEnabled",l),tip:"Uses browser SpeechSynthesis \u2014 no install needed"}),(0,r.jsx)(k,{}),(0,r.jsx)(M,{icon:"\u{1F399}\uFE0F",label:"Voice control",desc:"Say commands to navigate the page",checked:t.voiceControl,onChange:l=>o("voiceControl",l),disabled:!s,disabledReason:"Not supported in this browser",tip:'Say "scroll down", "go to main", "click"'}),(0,r.jsx)(k,{}),(0,r.jsx)(G,{label:"\u{1F916} AI Features",color:"#7c3aed",badge:"Gemini Nano",concept:"Large Language Model running privately on your device \u2014 Chrome 127+ only"}),(0,r.jsx)("div",{style:{margin:"4px 18px 6px",padding:"8px 10px",background:n?"#f0fdfa":"#f5f3ff",borderRadius:"8px",border:`0.5px solid ${n?"#99f6e4":"#c4b5fd"}`,fontSize:"10px",color:n?"#0f766e":"#7c3aed",lineHeight:1.5},children:n?"\u2705 Gemini Nano detected \u2014 AI features ready. Runs privately on your device.":"\u2699\uFE0F AI features need one-time setup \u2014 see guide below."}),!n&&(0,r.jsxs)("div",{style:{margin:"0 18px 8px",padding:"10px 12px",background:"#fafafa",borderRadius:"8px",border:"0.5px solid #e2e8f0",fontSize:"11px",color:"#475569",lineHeight:1.7},children:[(0,r.jsx)("p",{style:{margin:"0 0 6px",fontWeight:600,color:"#0f172a",fontSize:"11px"},children:"\u{1F6E0} One-time setup \u2014 5 steps:"}),(0,r.jsxs)("p",{style:{margin:"0 0 3px"},children:["1. Open Chrome \u2192 ",(0,r.jsx)("code",{style:{background:"#f1f5f9",padding:"1px 5px",borderRadius:"4px",fontSize:"10px",color:"#0d9488",fontFamily:"monospace"},children:"chrome://flags"})]}),(0,r.jsx)("p",{style:{margin:"0 0 3px"},children:"2. Enable each flag:"}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:"2px",margin:"4px 0 6px 10px"},children:Ut.map(l=>(0,r.jsxs)("span",{style:{fontSize:"10px",color:"#7c3aed",fontFamily:"monospace"},children:["\u2192 ",l]},l))}),(0,r.jsxs)("p",{style:{margin:"0 0 3px"},children:["3. Click ",(0,r.jsx)("strong",{style:{color:"#0f172a"},children:"Relaunch"})]}),(0,r.jsxs)("p",{style:{margin:"0 0 3px"},children:["4. ",(0,r.jsx)("code",{style:{background:"#f1f5f9",padding:"1px 5px",borderRadius:"4px",fontSize:"10px",color:"#0d9488",fontFamily:"monospace"},children:"chrome://components"})," \u2192 Optimization Guide On Device Model \u2192 Check for update"]}),(0,r.jsx)("p",{style:{margin:"0"},children:"5. Refresh \u2014 AI features unlock automatically \u2705"})]}),(0,r.jsx)(M,{icon:"\u{1F4DD}",label:"Plain English mode",desc:"Rewrites complex text in simple language",checked:t.plainEnglish,onChange:l=>o("plainEnglish",l),disabled:!n,disabledReason:"Enable Gemini Nano \u2014 see setup above",tip:"AI concept: LLM text rewriting"}),(0,r.jsx)(k,{}),(0,r.jsx)(M,{icon:"\u{1F4CB}",label:"Summarise page",desc:"3-sentence summary appears at top",checked:t.summarisePage,onChange:l=>o("summarisePage",l),disabled:!n,disabledReason:"Enable Gemini Nano \u2014 see setup above",tip:"AI concept: Abstractive summarisation"}),(0,r.jsx)(k,{}),(0,r.jsx)(M,{icon:"\u{1F3F7}\uFE0F",label:"Smart aria-labels",desc:"AI generates meaningful labels for elements",checked:t.smartLabels,onChange:l=>o("smartLabels",l),disabled:!n,disabledReason:"Enable Gemini Nano \u2014 see setup above",tip:"AI concept: Context-aware label generation"}),(0,r.jsx)(k,{}),(0,r.jsx)(G,{label:"\u{1F441}\uFE0F Visual",concept:"CSS filter-based \u2014 works on all browsers and devices"}),(0,r.jsx)(j,{steps:["Toggle any visual mode","Changes apply instantly","Works on mobile and desktop"]}),(0,r.jsx)(M,{icon:"\u25D1",label:"High contrast",desc:"Boosts contrast for low vision users",checked:t.highContrast,onChange:l=>o("highContrast",l),tip:"CSS filter: contrast()"}),(0,r.jsx)(k,{}),(0,r.jsx)(M,{icon:"\u{1F319}",label:"Dark mode",desc:"Inverts colours \u2014 easy on eyes at night",checked:t.darkMode,onChange:l=>o("darkMode",l),tip:"CSS filter: invert + hue-rotate"}),(0,r.jsx)(k,{}),(0,r.jsx)(M,{icon:"\u23F8\uFE0F",label:"Reduce motion",desc:"Disables all animations",checked:t.reduceMotion,onChange:l=>o("reduceMotion",l),tip:"WCAG 2.3.3 \u2014 vestibular disorders"}),(0,r.jsx)(k,{}),(0,r.jsx)(M,{icon:"\u{1F446}",label:"Large targets",desc:"44\xD744px minimum touch targets",checked:t.largeTargets,onChange:l=>o("largeTargets",l),tip:"WCAG 2.5.8 \u2014 motor impaired users"}),(0,r.jsx)(k,{}),(0,r.jsxs)("div",{style:{padding:"10px 18px"},children:[(0,r.jsx)("p",{style:{margin:"0 0 2px",fontSize:"12px",fontWeight:500,color:"#0f172a"},children:"\u{1F3A8} Colour blindness"}),(0,r.jsx)("p",{style:{margin:"0 0 8px",fontSize:"10px",color:"#94a3b8"},children:"SVG colour matrix filters \u2014 all devices"}),(0,r.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:"6px"},children:Yt.map(l=>(0,r.jsx)("button",{onClick:()=>o("colorBlindMode",l.value),"aria-pressed":t.colorBlindMode===l.value,style:{padding:"4px 10px",borderRadius:"20px",fontSize:"11px",fontWeight:500,border:`1px solid ${t.colorBlindMode===l.value?"#0d9488":"#e2e8f0"}`,background:t.colorBlindMode===l.value?"#f0fdfa":"#fff",color:t.colorBlindMode===l.value?"#0d9488":"#64748b",cursor:"pointer",minHeight:x?"36px":"auto"},children:l.label},l.value))})]}),(0,r.jsx)(k,{}),(0,r.jsx)(G,{label:"\u{1F524} Font",concept:"Browser Font API + CSS \u2014 Chrome 103+"}),(0,r.jsx)(j,{steps:["Toggle dyslexia font or pick from device","Adjust size with + / \u2212","Saved across visits"]}),(0,r.jsx)(M,{icon:"Aa",label:"Dyslexia-friendly font",desc:"Atkinson Hyperlegible \u2014 research-backed",checked:t.dyslexiaFont,onChange:l=>o("dyslexiaFont",l),tip:"By Braille Institute \u2014 free and open source"}),(0,r.jsx)(k,{}),(0,r.jsxs)("div",{style:{padding:"10px 18px"},children:[(0,r.jsx)("p",{style:{margin:"0 0 2px",fontSize:"12px",fontWeight:500,color:"#0f172a"},children:"\u{1F5A5}\uFE0F Local font"}),(0,r.jsx)("p",{style:{margin:"0 0 8px",fontSize:"10px",color:"#94a3b8"},children:"window.queryLocalFonts() \u2014 Chrome 103+"}),U.length>0?(0,r.jsxs)("select",{value:t.localFont,onChange:l=>o("localFont",l.target.value),"aria-label":"Choose a font from your device",style:{width:"100%",padding:"8px 10px",borderRadius:"8px",border:"1px solid #e2e8f0",fontSize:"13px",color:"#0f172a",background:"#fff",cursor:"pointer",height:x?"44px":"36px"},children:[(0,r.jsx)("option",{value:"",children:"System default"}),U.map(l=>(0,r.jsx)("option",{value:l,style:{fontFamily:l},children:l},l))]}):(0,r.jsx)("p",{style:{margin:0,fontSize:"11px",color:"#94a3b8"},children:"Allow font access when Chrome prompts you."})]}),(0,r.jsx)(k,{}),(0,r.jsxs)("div",{style:{padding:"10px 18px 14px"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"10px"},children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("p",{style:{margin:0,fontSize:"12px",fontWeight:500,color:"#0f172a"},children:"\u{1F4CF} Text size"}),(0,r.jsx)("p",{style:{margin:0,fontSize:"10px",color:"#94a3b8"},children:"Scales all text on the page"})]}),(0,r.jsxs)("span",{style:{fontSize:"12px",fontWeight:600,color:"#0d9488",background:"#f0fdfa",padding:"2px 8px",borderRadius:"99px"},children:[t.fontScale,"%"]})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[(0,r.jsx)("button",{onClick:()=>{let l=q.indexOf(t.fontScale);l>0&&o("fontScale",q[l-1])},disabled:t.fontScale<=80,"aria-label":"Decrease text size",style:{width:x?"44px":"30px",height:x?"44px":"30px",borderRadius:"8px",border:"1px solid #e2e8f0",background:"#fff",cursor:t.fontScale<=80?"not-allowed":"pointer",fontSize:"16px",color:t.fontScale<=80?"#cbd5e1":"#0f172a",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:"\u2212"}),(0,r.jsx)("div",{style:{flex:1,display:"flex",gap:"3px"},children:q.map(l=>(0,r.jsx)("button",{onClick:()=>o("fontScale",l),"aria-label":`Set text size to ${l}%`,style:{flex:1,height:"6px",borderRadius:"99px",border:"none",cursor:"pointer",padding:0,background:l<=t.fontScale?"#0d9488":"#e2e8f0",transition:"background 0.15s"}},l))}),(0,r.jsx)("button",{onClick:()=>{let l=q.indexOf(t.fontScale);l<q.length-1&&o("fontScale",q[l+1])},disabled:t.fontScale>=130,"aria-label":"Increase text size",style:{width:x?"44px":"30px",height:x?"44px":"30px",borderRadius:"8px",border:"1px solid #e2e8f0",background:"#fff",cursor:t.fontScale>=130?"not-allowed":"pointer",fontSize:"16px",color:t.fontScale>=130?"#cbd5e1":"#0f172a",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:"+"})]})]}),(0,r.jsx)(k,{}),(0,r.jsx)(G,{label:"\u{1F310} Translate",color:"#7c3aed",badge:"Gemini Nano",concept:"Chrome Translation API \u2014 on device, no internet after setup"}),(0,r.jsx)(j,{steps:["Enable Gemini Nano first","Pick your language","Full page translates instantly"]}),(0,r.jsxs)("div",{style:{padding:"6px 18px 12px"},children:[(0,r.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:"6px"},children:ee.slice(0,x?8:18).map(l=>(0,r.jsx)("button",{onClick:()=>o("translateLanguage",l.code),"aria-pressed":t.translateLanguage===l.code,disabled:!n,style:{padding:"4px 10px",borderRadius:"20px",fontSize:"11px",fontWeight:500,border:`1px solid ${t.translateLanguage===l.code?"#7c3aed":"#e2e8f0"}`,background:t.translateLanguage===l.code?"#f5f3ff":"#fff",color:t.translateLanguage===l.code?"#7c3aed":"#64748b",cursor:n?"pointer":"not-allowed",opacity:n?1:.5,minHeight:x?"36px":"auto"},children:l.label},l.code))}),!n&&(0,r.jsx)("p",{style:{margin:"6px 0 0",fontSize:"10px",color:"#94a3b8"},children:"Enable Gemini Nano using the setup guide above."})]}),(0,r.jsx)(k,{}),(0,r.jsx)(G,{label:"\u{1F4AC} Ask This Page",color:"#0d9488",badge:J,concept:"RAG \u2014 Retrieval Augmented Generation. Works on all devices including mobile."}),(0,r.jsx)(j,{steps:["Type any question about this page","Press Ask or hit Enter",p==="transformers"?"Transformers.js answers \u2014 works on mobile, offline":"Gemini Nano reads page and answers privately","Zero cost. No data leaves your device."]}),(0,r.jsxs)("div",{style:{margin:"0 18px 8px",padding:"6px 10px",background:p==="gemini"?"#f0fdfa":p==="transformers"?"#f5f3ff":"#f8fafc",borderRadius:"8px",border:`0.5px solid ${p==="gemini"?"#99f6e4":p==="transformers"?"#c4b5fd":"#e2e8f0"}`,fontSize:"10px",color:p==="gemini"?"#0f766e":p==="transformers"?"#7c3aed":"#94a3b8"},children:[p==="gemini"&&"\u2705 Using Gemini Nano \u2014 on device, private, instant",p==="transformers"&&"\u2705 Using Transformers.js \u2014 works on mobile and all browsers",!p&&"\u23F3 Detecting AI engine...",p==="transformers"&&C==="loading"&&" \xB7 Loading model...",p==="transformers"&&C==="ready"&&" \xB7 Model ready \u2705"]}),(0,r.jsxs)("div",{style:{padding:"0 18px 14px"},children:[(0,r.jsxs)("div",{style:{display:"flex",gap:"6px",marginBottom:"8px"},children:[(0,r.jsx)("input",{type:"text",value:R,onChange:l=>W(l.target.value),onKeyDown:l=>{l.key==="Enter"&&_()},placeholder:"e.g. What does this page do?",disabled:w||!p,"aria-label":"Ask a question about this page",style:{flex:1,padding:"8px 10px",borderRadius:"8px",border:"1px solid #e2e8f0",fontSize:"12px",color:"#0f172a",background:p?"#fff":"#f8fafc",outline:"none",height:x?"44px":"36px"}}),(0,r.jsx)("button",{onClick:_,disabled:w||!R.trim()||!p,"aria-label":"Ask question",style:{padding:"8px 14px",borderRadius:"8px",border:"none",background:p&&R.trim()&&!w?"#0d9488":"#e2e8f0",color:p&&R.trim()&&!w?"#fff":"#94a3b8",fontSize:"12px",fontWeight:600,cursor:p&&R.trim()&&!w?"pointer":"not-allowed",flexShrink:0,height:x?"44px":"36px",minWidth:"52px",transition:"background 0.2s"},children:w?le:"Ask"})]}),z&&(0,r.jsxs)("div",{role:"status","aria-live":"polite",style:{padding:"10px 12px",background:"#f0fdfa",border:"1px solid #99f6e4",borderRadius:"8px",fontSize:"12px",color:"#0f766e",lineHeight:1.6,maxHeight:"180px",overflowY:"auto"},children:[(0,r.jsx)("strong",{style:{display:"block",marginBottom:"4px",fontSize:"11px",color:"#0d9488"},children:"\u{1F4AC} Answer"}),z,(0,r.jsx)("button",{onClick:()=>{P(""),W("")},style:{display:"block",marginTop:"6px",background:"none",border:"none",color:"#94a3b8",fontSize:"10px",cursor:"pointer",padding:0},children:"Clear"})]})]}),a&&(0,r.jsx)("div",{role:"status",style:{margin:"0 14px 10px",padding:"8px 12px",background:"#f0fdfa",border:"1px solid #99f6e4",borderRadius:"8px",fontSize:"12px",color:"#0f766e",fontWeight:500,fontFamily:"monospace"},children:a.fixed>0?`\u2713 ${a.fixed} fixes \xB7 ${a.scanned} nodes \xB7 ${a.renderTime}ms \xB7 Score: ${a.score}/100`:`\u2713 0 auto-fixes needed \xB7 ${a.scanned} nodes \xB7 ${a.renderTime}ms`}),(0,r.jsxs)("div",{style:{display:"flex",gap:"8px",padding:"12px 14px 14px",position:x?"sticky":"relative",bottom:x?0:"auto",background:"#fff",borderTop:"1px solid #f1f5f9"},children:[(0,r.jsx)("button",{onClick:g,style:{flex:1,padding:x?"12px 0":"8px 0",fontSize:"13px",fontWeight:500,borderRadius:"9px",border:"1px solid #e2e8f0",background:"#fff",color:"#64748b",cursor:"pointer"},children:"Reset"}),(0,r.jsx)("button",{onClick:c,style:{flex:2,padding:x?"12px 0":"8px 0",fontSize:"13px",fontWeight:600,borderRadius:"9px",border:"none",background:"#0d9488",color:"#fff",cursor:"pointer"},children:"Apply settings"})]})]})});Te.displayName="WidgetPanel";var y=require("react/jsx-runtime");async function Qt(){try{if(typeof window>"u")return!1;let e=window;if(e.LanguageModel)try{if(typeof e.LanguageModel.availability=="function"){let a=await e.LanguageModel.availability();if(console.log("yuktai: LanguageModel.availability() =",a),a==="readily"||a==="available"||a==="downloadable")return!0}else return!0}catch{}if(e.Summarizer)try{if(typeof e.Summarizer.availability=="function"){let a=await e.Summarizer.availability();if(a==="readily"||a==="available")return!0}else return!0}catch{}if(e.Rewriter)try{if(typeof e.Rewriter.availability=="function"){let a=await e.Rewriter.availability();if(a==="readily"||a==="available")return!0}else return!0}catch{}if(e.Writer)try{if(typeof e.Writer.availability=="function"){let a=await e.Writer.availability();if(a==="readily"||a==="available")return!0}else return!0}catch{}let t=e.ai||globalThis.ai;if(t){if(t.languageModel?.availability)try{let a=await t.languageModel.availability();if(a==="readily"||a==="downloadable"||a==="available")return!0}catch{}if(t.languageModel?.capabilities)try{let a=await t.languageModel.capabilities();if(a?.available==="readily"||a?.available==="after-download")return!0}catch{}if(t.languageModel&&typeof t.languageModel.create=="function")return!0;if(t.summarizer?.capabilities)try{if((await t.summarizer.capabilities())?.available!=="no")return!0}catch{}if(t.rewriter?.capabilities)try{if((await t.rewriter.capabilities())?.available!=="no")return!0}catch{}if(t.writer?.capabilities)try{if((await t.writer.capabilities())?.available!=="no")return!0}catch{}if(t.summarizer||t.rewriter||t.writer||t.languageModel)return!0}return!!(e.Translator||e.translation?.canTranslate)}catch{return!1}}function re({position:e="left",children:t,config:a={},showRag:i=!1}){let[n,s]=(0,m.useState)(!1),[o,c]=(0,m.useState)(Se),[g,u]=(0,m.useState)(null),[v,x]=(0,m.useState)(!1),[E,U]=(0,m.useState)(!1),[se,R]=(0,m.useState)(!1),W=m.default.useRef(null),[z,P]=(0,m.useState)(!1),[w,D]=(0,m.useState)(""),[p,H]=(0,m.useState)(""),[C,F]=(0,m.useState)(!1),_=(0,m.useCallback)(async()=>{if(!(!w.trim()||C||!E)){F(!0),H("");try{let{askPage:d}=await Promise.resolve().then(()=>(ke(),tt)),h=await d(w);H(h.success?h.answer.replace(/\*\*(.*?)\*\*/g,"$1").replace(/\*(.*?)\*/g,"$1").replace(/#+\s/g,"").trim():"\u26A0\uFE0F "+(h.error||"No answer found."))}catch{H("\u26A0\uFE0F Something went wrong.")}F(!1)}},[w,C,E]);(0,m.useEffect)(()=>{if(typeof window>"u")return;let h=setTimeout(async()=>{let S=window;console.log("yuktai: Checking AI APIs..."),console.log("yuktai: window.ai =",S.ai),console.log("yuktai: window.LanguageModel =",S.LanguageModel),console.log("yuktai: window.Summarizer =",S.Summarizer),console.log("yuktai: window.Rewriter =",S.Rewriter),console.log("yuktai: window.Writer =",S.Writer);let Ee=await Qt();U(Ee),Ee?console.log("yuktai: Chrome Built-in AI detected \u2705"):(console.log("yuktai: Chrome Built-in AI not detected \u274C"),console.log("yuktai: Enable flags at chrome://flags and download model at chrome://components"));let ct=!!(S.SpeechRecognition||S.webkitSpeechRecognition);R(ct)},800);return()=>clearTimeout(h)},[]),(0,m.useEffect)(()=>{if(!(typeof window>"u"))try{let d=localStorage.getItem("yuktai-a11y-prefs");if(d){let h=JSON.parse(d);c(S=>({...S,...h}))}}catch{}},[]);let J=(0,m.useCallback)(async d=>{let h={enabled:!0,highContrast:d.highContrast,darkMode:d.darkMode,reduceMotion:d.reduceMotion,largeTargets:d.largeTargets,speechEnabled:d.speechEnabled,autoFix:d.autoFix,dyslexiaFont:d.dyslexiaFont,localFont:d.localFont,fontSizeMultiplier:d.fontScale/100,colorBlindMode:d.colorBlindMode,showAuditBadge:d.showAuditBadge,showSkipLinks:!0,showPreferencePanel:!1,plainEnglish:d.plainEnglish,summarisePage:d.summarisePage,translateLanguage:d.translateLanguage,voiceControl:d.voiceControl,smartLabels:d.smartLabels,...a};await T.execute(h);let S=T.applyFixes(h);u(S),x(!0)},[a]),le=(0,m.useCallback)(async()=>{try{localStorage.setItem("yuktai-a11y-prefs",JSON.stringify(o))}catch{}await J(o),s(!1)},[o,J]),ce=(0,m.useCallback)(()=>{c(Se);try{localStorage.removeItem("yuktai-a11y-prefs")}catch{}let d=document.documentElement;["data-yuktai-high-contrast","data-yuktai-dark","data-yuktai-reduce-motion","data-yuktai-large-targets","data-yuktai-keyboard","data-yuktai-dyslexia"].forEach(h=>d.removeAttribute(h)),document.body.style.filter="",document.body.style.fontFamily="",document.documentElement.style.fontSize="",u(null),x(!1)},[]),l=(0,m.useCallback)((d,h)=>{c(S=>({...S,[d]:h}))},[]);(0,m.useEffect)(()=>{let d=h=>{h.key==="Escape"&&(n&&s(!1),z&&P(!1))};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[n,z]),(0,m.useEffect)(()=>{n&&W.current&&T.trapFocus(W.current)},[n]);let V={position:"fixed",bottom:"24px",[e]:"24px",zIndex:9998,width:"52px",height:"52px",borderRadius:"50%",background:v?"#0d9488":"#1a73e8",color:"#fff",border:"none",cursor:"pointer",fontSize:"22px",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 4px 16px rgba(0,0,0,0.25)",transition:"transform 0.15s, background 0.2s"},de={position:"fixed",bottom:"84px",[e]:"24px",zIndex:9998,width:"52px",height:"52px",borderRadius:"50%",background:z?"#7c3aed":"#6d28d9",color:"#fff",border:"none",cursor:"pointer",fontSize:"22px",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 4px 16px rgba(0,0,0,0.25)",transition:"transform 0.15s, background 0.2s"};return(0,y.jsxs)(y.Fragment,{children:[t,i&&(0,y.jsx)("button",{style:de,"aria-label":"Ask a question about this page","aria-haspopup":"dialog","aria-expanded":z,onClick:()=>{P(d=>!d),s(!1)},onMouseEnter:d=>{d.currentTarget.style.transform="scale(1.08)"},onMouseLeave:d=>{d.currentTarget.style.transform="scale(1)"},children:"\u{1F4AC}"}),i&&z&&(0,y.jsxs)("div",{role:"dialog","aria-modal":"true","aria-label":"Ask this page","data-yuktai-panel":"true",style:{position:"fixed",bottom:"148px",[e]:"24px",zIndex:9999,width:"300px",maxWidth:"calc(100vw - 48px)",background:"#fff",border:"1px solid #e2e8f0",borderRadius:"16px",boxShadow:"0 8px 32px rgba(0,0,0,0.12)",fontFamily:"system-ui,-apple-system,sans-serif",padding:"14px"},children:[(0,y.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",marginBottom:"10px"},children:[(0,y.jsxs)("div",{children:[(0,y.jsx)("p",{style:{margin:"0 0 2px",fontSize:"13px",fontWeight:600,color:"#0f172a"},children:"\u{1F4AC} Ask this page"}),(0,y.jsx)("p",{style:{margin:0,fontSize:"10px",color:"#7c3aed"},children:"Gemini Nano \xB7 On device \xB7 Zero cost"})]}),(0,y.jsx)("button",{onClick:()=>P(!1),"aria-label":"Close ask panel",style:{background:"none",border:"none",cursor:"pointer",color:"#94a3b8",fontSize:"18px",lineHeight:1,padding:"2px",borderRadius:"4px"},children:"\xD7"})]}),(0,y.jsxs)("div",{style:{display:"flex",gap:"6px",marginBottom:"8px"},children:[(0,y.jsx)("input",{type:"text",value:w,onChange:d=>D(d.target.value),onKeyDown:d=>{d.key==="Enter"&&_()},placeholder:"e.g. What does this page do?",disabled:!E||C,"aria-label":"Ask a question about this page",style:{flex:1,padding:"8px 10px",borderRadius:"8px",border:"1px solid #e2e8f0",fontSize:"12px",color:"#0f172a",background:E?"#fff":"#f8fafc",outline:"none",height:"36px"}}),(0,y.jsx)("button",{onClick:_,disabled:!E||C||!w.trim(),"aria-label":"Submit question",style:{padding:"8px 12px",borderRadius:"8px",border:"none",background:E&&w.trim()&&!C?"#7c3aed":"#e2e8f0",color:E&&w.trim()&&!C?"#fff":"#94a3b8",fontSize:"12px",fontWeight:600,cursor:E&&w.trim()&&!C?"pointer":"not-allowed",height:"36px",minWidth:"48px",transition:"background 0.2s"},children:C?"...":"Ask"})]}),p&&(0,y.jsxs)("div",{style:{padding:"10px",background:"#f5f3ff",borderRadius:"8px",fontSize:"12px",color:"#4c1d95",lineHeight:1.6,maxHeight:"180px",overflowY:"auto"},children:[(0,y.jsx)("strong",{style:{display:"block",marginBottom:"4px",fontSize:"11px",color:"#7c3aed"},children:"\u{1F4AC} Answer"}),p,(0,y.jsx)("button",{onClick:()=>{H(""),D("")},style:{display:"block",marginTop:"6px",background:"none",border:"none",color:"#94a3b8",fontSize:"10px",cursor:"pointer",padding:0},children:"Clear"})]}),!E&&(0,y.jsx)("p",{style:{margin:"4px 0 0",fontSize:"10px",color:"#94a3b8"},children:"Enable Gemini Nano via chrome://flags to use this feature."})]}),(0,y.jsx)("button",{style:V,"aria-label":"Open accessibility preferences","aria-haspopup":"dialog","aria-expanded":n,"data-yuktai-pref-toggle":"true",onClick:()=>{s(d=>!d),P(!1)},onMouseEnter:d=>{d.currentTarget.style.transform="scale(1.08)"},onMouseLeave:d=>{d.currentTarget.style.transform="scale(1)"},children:"\u267F"}),n&&(0,y.jsx)(Te,{ref:W,position:e,settings:o,report:g,isActive:v,aiSupported:E,voiceSupported:se,set:l,onApply:le,onReset:ce,onClose:()=>s(!1)})]})}var K={name:"ai.text",async execute(e){return`\u{1F916} YuktAI says: ${e}`}};var Y={name:"voice.text",async execute(e){return!e||e.trim()===""?"\u{1F3A4} No speech detected":`\u{1F3A4} You said: ${e}`}};var I=class{plugins=new Map;register(t,a){if(!a||typeof a.execute!="function")throw new Error(`Invalid plugin: ${t}`);this.plugins.set(t,a)}use(t){return this.plugins.get(t)}async run(t,a){try{let i=this.use(t);if(!i)throw new Error(`Plugin not found: ${t}`);return await i.execute(a)}catch(i){throw console.error(`[YuktAI Runtime Error in ${t}]:`,i),i}}getPlugins(){return Array.from(this.plugins.keys())}};function Zt(){if(typeof globalThis>"u")return new I;if(!globalThis.__yuktai_runtime__){let e=new I;e.register(T.name,T),e.register(K.name,K),e.register(Y.name,Y),globalThis.__yuktai_runtime__=e}return globalThis.__yuktai_runtime__}var lt=typeof window<"u"?Zt():new I,ea={wcagPlugin:T,list(){return lt.getPlugins()},use(e){return lt.use(e)},fix(e){return T.applyFixes({enabled:!0,autoFix:!0,...e})},scan(){return T.scan()}};0&&(module.exports={Runtime,YuktAI,YuktAIWrapper,aiPlugin,voicePlugin,wcag,wcagPlugin});