diff --git a/README.md b/README.md index a8b2c87..08cc83a 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,18 @@ +# Table of contents +- [Table of contents](#table-of-contents) +- [react-file-viewer](#react-file-viewer) + - [Supported file formats:](#supported-file-formats) + - [Usage](#usage) + - [Development](#development) + - [To start demo app](#to-start-demo-app) + - [Testing](#testing) + - [To run the linter](#to-run-the-linter) + - [Extending the file viewer](#extending-the-file-viewer) + - [Viewing local changes in a secondary repo](#viewing-local-changes-in-a-secondary-repo) + - [Testing locally against the mymove application](#testing-locally-against-the-mymove-application) + - [Roadmap](#roadmap) + + # react-file-viewer Extendable file viewer for web @@ -138,6 +153,22 @@ If you are working on a feature branch and need to see changes introduced in tha `"@trussworks/react-file-viewer": "git+https://github.com/trussworks react-file-viewer"` +### Testing locally against the mymove application +Testing locally against the mymove application can be done via yarn link, but for the purpose of being thorough it is recommended to manually test against the `/dist/` output. This verifies the webpack is successfully compiling/transpiling and that the mymove application is successfully serving chunks. + +TODO: ENHANCE ME (This is supposed to work, but it doesn't. Fallback is still `rm -rf node_modules && yarn install && ./scripts/copy-react-file-viewer && make client_run`) +1. [OPTIONAL] Within this repository, navigate to `webpack.config.js`. This is the production webpack. + 1. Find where ` plugins: [new BundleAnalyzerPlugin({ analyzerMode: 'disabled' })]` is located and remove/enable the analyzerMode attribute + 2. This makes it so you can preview the chunks +2. Within this repository, run `yarn build`, it should output new files to `/dist/` +3. Within the [MyMove repository](https://github.com/transcom/mymove) update `package.json` and set `"@transcom/react-file-viewer"` to point to the local location of this repository: Such as `"file:../react-file-viewer"` +4. Within MyMove, run `yarn upgrade @transcom/react-file-viewer` +5. Within MyMove, run `./scripts/copy-react-file-viewer` + +You should now successfully be testing the webpack build of react-file-viewer against MyMove. Each time you adjust react-file-viewer, repeat steps 2, 4, and 5 to reflect within MyMove. + +The benefit of working this way over yarn link is that we can properly simulate MyMove serving the chunks from its `./scripts/copy-react-file-viewer`. + ## Roadmap - [ ] Remove ignored linting rules and fix them diff --git a/dist/13.chunk.js b/dist/13.chunk.js new file mode 100644 index 0000000..b4d3434 --- /dev/null +++ b/dist/13.chunk.js @@ -0,0 +1 @@ +!function(A,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.FileViewer=e():A.FileViewer=e()}(self,(()=>(()=>{"use strict";var A={d:(e,t)=>{for(var i in t)A.o(t,i)&&!A.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},o:(A,e)=>Object.prototype.hasOwnProperty.call(A,e)},e=globalThis.pdfjsWorker={};A.d(e,{WorkerMessageHandler:()=>Dd});const t=!("object"!=typeof process||process+""!="[object process]"||process.versions.nw||process.versions.electron&&process.type&&"browser"!==process.type),i=[1,0,0,1,0,0],a=[.001,0,0,.001,0,0],s=1.35,n=.25925925925925924,g="pdfjs_internal_editor_",r={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},o="Group",I=32,c=8192,C=65536,B={E:"Mouse Enter",X:"Mouse Exit",D:"Mouse Down",U:"Mouse Up",Fo:"Focus",Bl:"Blur",PO:"PageOpen",PC:"PageClose",PV:"PageVisible",PI:"PageInvisible",K:"Keystroke",F:"Format",V:"Validate",C:"Calculate"},h={WC:"WillClose",WS:"WillSave",DS:"DidSave",WP:"WillPrint",DP:"DidPrint"},Q={O:"PageOpen",C:"PageClose"},l=10,E=11,u=12,d=37,f=44,p=58,m=59,y=70,w=71,D=83,b=85;let k=1;function F(){return k}function S(A){k>=5&&console.log(`Info: ${A}`)}function R(A){k>=1&&console.log(`Warning: ${A}`)}function G(A){throw new Error(A)}function N(A,e){A||G(e)}function x(A,e=null,t=null){if(!A)return null;try{if(t&&"string"==typeof A&&(t.addDefaultProtocol&&A.startsWith("www.")&&A.match(/\./g)?.length>=2&&(A=`http://${A}`),t.tryConvertEncoding))try{A=_(A)}catch{}const i=e?new URL(A,e):new URL(A);if(function(A){switch(A?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}(i))return i}catch{}return null}function U(A,e,t,i=!1){return Object.defineProperty(A,e,{value:t,enumerable:!i,configurable:!0,writable:!1}),t}const M=function(){function A(A,e){this.message=A,this.name=e}return A.prototype=new Error,A.constructor=A,A}();class L extends M{constructor(A,e){super(A,"PasswordException"),this.code=e}}class J extends M{constructor(A,e){super(A,"UnknownErrorException"),this.details=e}}class H extends M{constructor(A){super(A,"InvalidPDFException")}}class Y extends M{constructor(A){super(A,"MissingPDFException")}}class v extends M{constructor(A,e){super(A,"UnexpectedResponseException"),this.status=e}}class K extends M{constructor(A){super(A,"FormatError")}}class q extends M{constructor(A){super(A,"AbortException")}}function T(A){"object"==typeof A&&void 0!==A?.length||G("Invalid argument for bytesToString");const e=A.length,t=8192;if(e>24&255,A>>16&255,A>>8&255,255&A)}function Z(A){return Object.keys(A).length}class O{static get isLittleEndian(){return U(this,"isLittleEndian",function(){const A=new Uint8Array(4);return A[0]=1,1===new Uint32Array(A.buffer,0,1)[0]}())}static get isEvalSupported(){return U(this,"isEvalSupported",function(){try{return new Function(""),!0}catch{return!1}}())}static get isOffscreenCanvasSupported(){return U(this,"isOffscreenCanvasSupported","undefined"!=typeof OffscreenCanvas)}static get platform(){return"undefined"!=typeof navigator&&"string"==typeof navigator?.platform?U(this,"platform",{isMac:navigator.platform.includes("Mac"),isWindows:navigator.platform.includes("Win"),isFirefox:"string"==typeof navigator?.userAgent&&navigator.userAgent.includes("Firefox")}):U(this,"platform",{isMac:!1,isWindows:!1,isFirefox:!1})}static get isCSSRoundSupported(){return U(this,"isCSSRoundSupported",globalThis.CSS?.supports?.("width: round(1.5px, 1px)"))}}const X=Array.from(Array(256).keys(),(A=>A.toString(16).padStart(2,"0")));class V{static makeHexColor(A,e,t){return`#${X[A]}${X[e]}${X[t]}`}static scaleMinMax(A,e){let t;A[0]?(A[0]<0&&(t=e[0],e[0]=e[2],e[2]=t),e[0]*=A[0],e[2]*=A[0],A[3]<0&&(t=e[1],e[1]=e[3],e[3]=t),e[1]*=A[3],e[3]*=A[3]):(t=e[0],e[0]=e[1],e[1]=t,t=e[2],e[2]=e[3],e[3]=t,A[1]<0&&(t=e[1],e[1]=e[3],e[3]=t),e[1]*=A[1],e[3]*=A[1],A[2]<0&&(t=e[0],e[0]=e[2],e[2]=t),e[0]*=A[2],e[2]*=A[2]),e[0]+=A[4],e[1]+=A[5],e[2]+=A[4],e[3]+=A[5]}static transform(A,e){return[A[0]*e[0]+A[2]*e[1],A[1]*e[0]+A[3]*e[1],A[0]*e[2]+A[2]*e[3],A[1]*e[2]+A[3]*e[3],A[0]*e[4]+A[2]*e[5]+A[4],A[1]*e[4]+A[3]*e[5]+A[5]]}static applyTransform(A,e){return[A[0]*e[0]+A[1]*e[2]+e[4],A[0]*e[1]+A[1]*e[3]+e[5]]}static applyInverseTransform(A,e){const t=e[0]*e[3]-e[1]*e[2];return[(A[0]*e[3]-A[1]*e[2]+e[2]*e[5]-e[4]*e[3])/t,(-A[0]*e[1]+A[1]*e[0]+e[4]*e[1]-e[5]*e[0])/t]}static getAxialAlignedBoundingBox(A,e){const t=this.applyTransform(A,e),i=this.applyTransform(A.slice(2,4),e),a=this.applyTransform([A[0],A[3]],e),s=this.applyTransform([A[2],A[1]],e);return[Math.min(t[0],i[0],a[0],s[0]),Math.min(t[1],i[1],a[1],s[1]),Math.max(t[0],i[0],a[0],s[0]),Math.max(t[1],i[1],a[1],s[1])]}static inverseTransform(A){const e=A[0]*A[3]-A[1]*A[2];return[A[3]/e,-A[1]/e,-A[2]/e,A[0]/e,(A[2]*A[5]-A[4]*A[3])/e,(A[4]*A[1]-A[5]*A[0])/e]}static singularValueDecompose2dScale(A){const e=[A[0],A[2],A[1],A[3]],t=A[0]*e[0]+A[1]*e[2],i=A[0]*e[1]+A[1]*e[3],a=A[2]*e[0]+A[3]*e[2],s=A[2]*e[1]+A[3]*e[3],n=(t+s)/2,g=Math.sqrt((t+s)**2-4*(t*s-a*i))/2,r=n+g||1,o=n-g||1;return[Math.sqrt(r),Math.sqrt(o)]}static normalizeRect(A){const e=A.slice(0);return A[0]>A[2]&&(e[0]=A[2],e[2]=A[0]),A[1]>A[3]&&(e[1]=A[3],e[3]=A[1]),e}static intersect(A,e){const t=Math.max(Math.min(A[0],A[2]),Math.min(e[0],e[2])),i=Math.min(Math.max(A[0],A[2]),Math.max(e[0],e[2]));if(t>i)return null;const a=Math.max(Math.min(A[1],A[3]),Math.min(e[1],e[3])),s=Math.min(Math.max(A[1],A[3]),Math.max(e[1],e[3]));return a>s?null:[t,a,i,s]}static#A(A,e,t,i,a,s,n,g,r,o){if(r<=0||r>=1)return;const I=1-r,c=r*r,C=c*r,B=I*(I*(I*A+3*r*e)+3*c*t)+C*i,h=I*(I*(I*a+3*r*s)+3*c*n)+C*g;o[0]=Math.min(o[0],B),o[1]=Math.min(o[1],h),o[2]=Math.max(o[2],B),o[3]=Math.max(o[3],h)}static#e(A,e,t,i,a,s,n,g,r,o,I,c){if(Math.abs(r)<1e-12)return void(Math.abs(o)>=1e-12&&this.#A(A,e,t,i,a,s,n,g,-I/o,c));const C=o**2-4*I*r;if(C<0)return;const B=Math.sqrt(C),h=2*r;this.#A(A,e,t,i,a,s,n,g,(-o+B)/h,c),this.#A(A,e,t,i,a,s,n,g,(-o-B)/h,c)}static bezierBoundingBox(A,e,t,i,a,s,n,g,r){return r?(r[0]=Math.min(r[0],A,n),r[1]=Math.min(r[1],e,g),r[2]=Math.max(r[2],A,n),r[3]=Math.max(r[3],e,g)):r=[Math.min(A,n),Math.min(e,g),Math.max(A,n),Math.max(e,g)],this.#e(A,t,a,n,e,i,s,g,3*(3*(t-a)-A+n),6*(A-2*t+a),3*(t-A),r),this.#e(A,t,a,n,e,i,s,g,3*(3*(i-s)-e+g),6*(e-2*i+s),3*(i-e),r),r}}const j=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,728,711,710,729,733,731,730,732,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8226,8224,8225,8230,8212,8211,402,8260,8249,8250,8722,8240,8222,8220,8221,8216,8217,8218,8482,64257,64258,321,338,352,376,381,305,322,339,353,382,0,8364];function z(A){if(A[0]>="ï"){let e;if("þ"===A[0]&&"ÿ"===A[1]?(e="utf-16be",A.length%2==1&&(A=A.slice(0,-1))):"ÿ"===A[0]&&"þ"===A[1]?(e="utf-16le",A.length%2==1&&(A=A.slice(0,-1))):"ï"===A[0]&&"»"===A[1]&&"¿"===A[2]&&(e="utf-8"),e)try{const t=new TextDecoder(e,{fatal:!0}),i=P(A),a=t.decode(i);return a.includes("")?a.replaceAll(/\x1b[^\x1b]*(?:\x1b|$)/g,""):a}catch(A){R(`stringToPDFString: "${A}".`)}}const e=[];for(let t=0,i=A.length;t{G("Should not call `set` on the empty dictionary.")},U(this,"empty",A)}static merge({xref:A,dictArray:e,mergeSubDicts:t=!1}){const i=new CA(A),a=new Map;for(const A of e)if(A instanceof CA)for(const[e,i]of Object.entries(A._map)){let A=a.get(e);if(void 0===A)A=[],a.set(e,A);else if(!(t&&i instanceof CA))continue;A.push(i)}for(const[e,t]of a){if(1===t.length||!(t[0]instanceof CA)){i._map[e]=t[0];continue}const a=new CA(A);for(const A of t)for(const[e,t]of Object.entries(A._map))void 0===a._map[e]&&(a._map[e]=t);a.size>0&&(i._map[e]=a)}return a.clear(),i.size>0?i:CA.empty}clone(){const A=new CA(this.xref);for(const e of this.getKeys())A.set(e,this.getRaw(e));return A}delete(A){delete this._map[A]}}class BA{constructor(A,e){this.num=A,this.gen=e}toString(){return 0===this.gen?`${this.num}R`:`${this.num}R${this.gen}`}static fromString(A){const e=rA[A];if(e)return e;const t=/^(\d+)R(\d*)$/.exec(A);return t&&"0"!==t[1]?rA[A]=new BA(parseInt(t[1]),t[2]?parseInt(t[2]):0):null}static get(A,e){const t=0===e?`${A}R`:`${A}R${e}`;return rA[t]||=new BA(A,e)}}class hA{constructor(A=null){this._set=new Set(A?._set)}has(A){return this._set.has(A.toString())}put(A){this._set.add(A.toString())}remove(A){this._set.delete(A.toString())}[Symbol.iterator](){return this._set.values()}clear(){this._set.clear()}}class QA{constructor(){this._map=new Map}get size(){return this._map.size}get(A){return this._map.get(A.toString())}has(A){return this._map.has(A.toString())}put(A,e){this._map.set(A.toString(),e)}putAlias(A,e){this._map.set(A.toString(),this.get(e))}[Symbol.iterator](){return this._map.values()}clear(){this._map.clear()}*items(){for(const[A,e]of this._map)yield[BA.fromString(A),e]}}function lA(A,e){return A instanceof oA&&(void 0===e||A.name===e)}function EA(A,e){return A instanceof IA&&(void 0===e||A.cmd===e)}function uA(A,e){return A instanceof CA&&(void 0===e||lA(A.get("Type"),e))}function dA(A,e){return A.num===e.num&&A.gen===e.gen}class fA{get length(){G("Abstract getter `length` accessed")}get isEmpty(){G("Abstract getter `isEmpty` accessed")}get isDataLoaded(){return U(this,"isDataLoaded",!0)}getByte(){G("Abstract method `getByte` called")}getBytes(A){G("Abstract method `getBytes` called")}async getImageData(A,e){return this.getBytes(A,e)}async asyncGetBytes(){G("Abstract method `asyncGetBytes` called")}get isAsync(){return!1}get canAsyncDecodeImageFromBuffer(){return!1}peekByte(){const A=this.getByte();return-1!==A&&this.pos--,A}peekBytes(A){const e=this.getBytes(A);return this.pos-=e.length,e}getUint16(){const A=this.getByte(),e=this.getByte();return-1===A||-1===e?-1:(A<<8)+e}getInt32(){return(this.getByte()<<24)+(this.getByte()<<16)+(this.getByte()<<8)+this.getByte()}getByteRange(A,e){G("Abstract method `getByteRange` called")}getString(A){return T(this.getBytes(A))}skip(A){this.pos+=A||1}reset(){G("Abstract method `reset` called")}moveStart(){G("Abstract method `moveStart` called")}makeSubStream(A,e,t=null){G("Abstract method `makeSubStream` called")}getBaseStreams(){return null}}const pA=/^[1-9]\.\d$/;function mA(A){let e;return function(){return A&&(e=Object.create(null),A(e),A=null),e}}class yA extends M{constructor(A,e){super(`Missing data [${A}, ${e})`,"MissingDataException"),this.begin=A,this.end=e}}class wA extends M{constructor(A){super(A,"ParserEOFException")}}class DA extends M{constructor(A){super(A,"XRefEntryException")}}class bA extends M{constructor(A){super(A,"XRefParseException")}}function kA(A){const e=A.length;if(0===e)return new Uint8Array(0);if(1===e)return new Uint8Array(A[0]);let t=0;for(let i=0;i0,"The number should be a positive integer.");const t=[];let i;for(;A>=1e3;)A-=1e3,t.push("M");i=A/100|0,A%=100,t.push(SA[i]),i=A/10|0,A%=10,t.push(SA[10+i]),t.push(SA[20+A]);const a=t.join("");return e?a.toLowerCase():a}function GA(A){return A<=0?0:Math.ceil(Math.log2(A))}function NA(A,e){return A[e]<<24>>24}function xA(A,e){return A[e]<<8|A[e+1]}function UA(A,e){return(A[e]<<24|A[e+1]<<16|A[e+2]<<8|A[e+3])>>>0}function MA(A){return 32===A||9===A||13===A||10===A}function LA(A,e){return Array.isArray(A)?(null===e||A.length===e)&&A.every((A=>"number"==typeof A)):ArrayBuffer.isView(A)&&(0===A.length||"number"==typeof A[0])&&(null===e||A.length===e)}function JA(A,e){return LA(A,6)?A:e}function HA(A,e){return LA(A,4)?A:e}function YA(A,e){return LA(A,4)?V.normalizeRect(A):e}function vA(A){const e=/(.+)\[(\d+)\]$/;return A.split(".").map((A=>{const t=A.match(e);return t?{name:t[1],pos:parseInt(t[2],10)}:{name:A,pos:0}}))}function KA(A){const e=[];let t=0;for(let i=0,a=A.length;i126||35===a||40===a||41===a||60===a||62===a||91===a||93===a||123===a||125===a||47===a||37===a)&&(t"\n"===A?"\\n":"\r"===A?"\\r":`\\${A}`))}function TA(A,e,t,i){if(!A)return;let a=null;if(A instanceof BA){if(i.has(A))return;a=A,i.put(a),A=e.fetch(A)}if(Array.isArray(A))for(const a of A)TA(a,e,t,i);else if(A instanceof CA){if(lA(A.get("S"),"JavaScript")){const e=A.get("JS");let i;e instanceof fA?i=e.getString():"string"==typeof e&&(i=e),i&&=z(i).replaceAll("\0",""),i&&t.push(i)}TA(A.getRaw("Next"),e,t,i)}a&&i.remove(a)}function PA(A,e,t){const i=Object.create(null),a=FA({dict:e,key:"AA",stopWhenFound:!1});if(a)for(let e=a.length-1;e>=0;e--){const s=a[e];if(s instanceof CA)for(const e of s.getKeys()){const a=t[e];if(!a)continue;const n=[];TA(s.getRaw(e),A,n,new hA),n.length>0&&(i[a]=n)}}if(e.has("A")){const t=[];TA(e.get("A"),A,t,new hA),t.length>0&&(i.Action=t)}return Z(i)>0?i:null}const WA={60:"<",62:">",38:"&",34:""",39:"'"};function*ZA(A){for(let e=0,t=A.length;e55295&&(t<57344||t>65533)&&e++,yield t}}function OA(A){const e=[];let t=0;for(let i=0,a=A.length;i55295&&(a<57344||a>65533)&&i++,t=i+1}return 0===e.length?A:(t: ${A}.`),!1;return!0}function VA(A){const e=new Set(["100","200","300","400","500","600","700","800","900","1000","normal","bold","bolder","lighter"]),{fontFamily:t,fontWeight:i,italicAngle:a}=A;if(!XA(t,!0))return!1;const s=i?i.toString():"";A.fontWeight=e.has(s)?s:"400";const n=parseFloat(a);return A.italicAngle=isNaN(n)||n<-90||n>90?"14":a.toString(),!0}function jA(A){const e=new RegExp("^\\s*("+["app.launchURL","window.open","xfa.host.gotoURL"].join("|").replaceAll(".","\\.")+")\\((?:'|\")([^'\"]*)(?:'|\")(?:,\\s*(\\w+)\\)|\\))","i").exec(A);if(e?.[2]){const A=e[2];let t=!1;return"true"===e[3]&&"app.launchURL"===e[1]&&(t=!0),{url:A,newWindow:t}}return null}function zA(A){if(Number.isInteger(A))return A.toString();const e=Math.round(100*A);return e%100==0?(e/100).toString():e%10==0?A.toFixed(1):A.toFixed(2)}function _A(A){if(!A)return null;const e=new Map;for(const[t,i]of A){if(!t.startsWith(g))continue;let A=e.get(i.pageIndex);A||(A=[],e.set(i.pageIndex,A)),A.push(i)}return e.size>0?e:null}function $A(A){return function(A){return/^[\x00-\x7F]*$/.test(A)}(A)?A:ee(A,!0)}function Ae(A){const e=[];for(let t=0,i=A.length;t>8&255).toString(16).padStart(2,"0"),(255&i).toString(16).padStart(2,"0"))}return e.join("")}function ee(A,e=!1){const t=[];e&&t.push("þÿ");for(let e=0,i=A.length;e>8&255),String.fromCharCode(255&i))}return t.join("")}function te(A,e,t){switch(A){case 90:return[0,1,-1,0,e,0];case 180:return[-1,0,0,-1,e,t];case 270:return[0,-1,1,0,0,t];default:throw new Error("Invalid rotation")}}function ie(A){return Math.ceil(Math.ceil(Math.log2(1+A))/8)}class ae extends fA{constructor(A,e,t,i){super(),this.bytes=A instanceof Uint8Array?A:new Uint8Array(A),this.start=e||0,this.pos=this.start,this.end=e+t||this.bytes.length,this.dict=i}get length(){return this.end-this.start}get isEmpty(){return 0===this.length}getByte(){return this.pos>=this.end?-1:this.bytes[this.pos++]}getBytes(A){const e=this.bytes,t=this.pos,i=this.end;if(!A)return e.subarray(t,i);let a=t+A;return a>i&&(a=i),this.pos=a,e.subarray(t,a)}getByteRange(A,e){return A<0&&(A=0),e>this.end&&(e=this.end),this.bytes.subarray(A,e)}reset(){this.pos=this.start}moveStart(){this.start=this.pos}makeSubStream(A,e,t=null){return new ae(this.bytes.buffer,A,e,t)}}class se extends ae{constructor(A){super(P(A))}}class ne extends ae{constructor(){super(new Uint8Array(0))}}class ge extends ae{constructor(A,e,t){super(new Uint8Array(A),0,A,null),this.chunkSize=e,this._loadedChunks=new Set,this.numChunks=Math.ceil(A/e),this.manager=t,this.progressiveDataLength=0,this.lastSuccessfulEnsureByteChunk=-1}getMissingChunks(){const A=[];for(let e=0,t=this.numChunks;e=this.end?this.numChunks:Math.floor(e/this.chunkSize);for(let A=t;Athis.numChunks)&&e!==this.lastSuccessfulEnsureByteChunk){if(!this._loadedChunks.has(e))throw new yA(A,A+1);this.lastSuccessfulEnsureByteChunk=e}}ensureRange(A,e){if(A>=e)return;if(e<=this.progressiveDataLength)return;const t=Math.floor(A/this.chunkSize);if(t>this.numChunks)return;const i=Math.min(Math.floor((e-1)/this.chunkSize)+1,this.numChunks);for(let a=t;a=this.end?-1:(A>=this.progressiveDataLength&&this.ensureByte(A),this.bytes[this.pos++])}getBytes(A){const e=this.bytes,t=this.pos,i=this.end;if(!A)return i>this.progressiveDataLength&&this.ensureRange(t,i),e.subarray(t,i);let a=t+A;return a>i&&(a=i),a>this.progressiveDataLength&&this.ensureRange(t,a),this.pos=a,e.subarray(t,a)}getByteRange(A,e){return A<0&&(A=0),e>this.end&&(e=this.end),e>this.progressiveDataLength&&this.ensureRange(A,e),this.bytes.subarray(A,e)}makeSubStream(A,e,t=null){function i(){}e?A+e>this.progressiveDataLength&&this.ensureRange(A,A+e):A>=this.progressiveDataLength&&this.ensureByte(A),i.prototype=Object.create(this),i.prototype.getMissingChunks=function(){const A=this.chunkSize,e=Math.floor(this.start/A),t=Math.floor((this.end-1)/A)+1,i=[];for(let A=e;A{const s=({value:n,done:g})=>{try{if(g){const e=kA(i);return i=null,void A(e)}a+=n.byteLength,t.isStreamingSupported&&this.onProgress({loaded:a}),i.push(n),t.read().then(s,e)}catch(A){e(A)}};t.read().then(s,e)})).then((e=>{this.aborted||this.onReceiveData({chunk:e,begin:A})}))}requestAllChunks(A=!1){if(!A){const A=this.stream.getMissingChunks();this._requestChunks(A)}return this._loadedStreamCapability.promise}_requestChunks(A){const e=this.currRequestId++,t=new Set;this._chunksNeededByRequest.set(e,t);for(const e of A)this.stream.hasChunk(e)||t.add(e);if(0===t.size)return Promise.resolve();const i=Promise.withResolvers();this._promisesByRequest.set(e,i);const a=[];for(const A of t){let t=this._requestsByChunk.get(A);t||(t=[],this._requestsByChunk.set(A,t),a.push(A)),t.push(e)}if(a.length>0){const A=this.groupChunks(a);for(const e of A){const A=e.beginChunk*this.chunkSize,t=Math.min(e.endChunk*this.chunkSize,this.length);this.sendRequest(A,t).catch(i.reject)}}return i.promise.catch((A=>{if(!this.aborted)throw A}))}getStream(){return this.stream}requestRange(A,e){e=Math.min(e,this.length);const t=this.getBeginChunk(A),i=this.getEndChunk(e),a=[];for(let A=t;A=0&&i+1!==s&&(e.push({beginChunk:t,endChunk:i+1}),t=s),a+1===A.length&&e.push({beginChunk:t,endChunk:s+1}),i=s}return e}onProgress(A){this.msgHandler.send("DocProgress",{loaded:this.stream.numChunksLoaded*this.chunkSize+A.loaded,total:this.length})}onReceiveData(A){const e=A.chunk,t=void 0===A.begin,i=t?this.progressiveDataLength:A.begin,a=i+e.byteLength,s=Math.floor(i/this.chunkSize),n=a0||g.push(t)}}}if(!this.disableAutoFetch&&0===this._requestsByChunk.size){let A;if(1===this.stream.numChunksLoaded){const e=this.stream.numChunks-1;this.stream.hasChunk(e)||(A=e)}else A=this.stream.nextEmptyChunk(n);Number.isInteger(A)&&this._requestChunks([A])}for(const A of g){const e=this._promisesByRequest.get(A);this._promisesByRequest.delete(A),e.resolve()}this.msgHandler.send("DocProgress",{loaded:this.stream.numChunksLoaded*this.chunkSize,total:this.length})}onError(A){this._loadedStreamCapability.reject(A)}getBeginChunk(A){return Math.floor(A/this.chunkSize)}getEndChunk(A){return Math.floor((A-1)/this.chunkSize)+1}abort(A){this.aborted=!0,this.pdfNetworkStream?.cancelAllRequests(A);for(const e of this._promisesByRequest.values())e.reject(A)}}class oe{constructor(A,e){this.name=A,this.numComps=e}getRgb(A,e){const t=new Uint8ClampedArray(3);return this.getRgbItem(A,e,t,0),t}getRgbItem(A,e,t,i){G("Should not call ColorSpace.getRgbItem")}getRgbBuffer(A,e,t,i,a,s,n){G("Should not call ColorSpace.getRgbBuffer")}getOutputLength(A,e){G("Should not call ColorSpace.getOutputLength")}isPassthrough(A){return!1}isDefaultDecode(A,e){return oe.isDefaultDecode(A,this.numComps)}fillRgb(A,e,t,i,a,s,n,g,r){const o=e*t;let I=null;const c=1<c&&"DeviceGray"!==this.name&&"DeviceRGB"!==this.name){const e=n<=8?new Uint8Array(c):new Uint16Array(c);for(let A=0;A=.99554525?1:this.#Q(0,1,1.055*A**(1/2.4)-.055)}#Q(A,e,t){return Math.max(A,Math.min(e,t))}#l(A){return A<0?-this.#l(-A):A>8?((A+16)/116)**3:A*ue.#I}#E(A,e,t){if(0===A[0]&&0===A[1]&&0===A[2])return t[0]=e[0],t[1]=e[1],void(t[2]=e[2]);const i=this.#l(0),a=(1-i)/(1-this.#l(A[0])),s=1-a,n=(1-i)/(1-this.#l(A[1])),g=1-n,r=(1-i)/(1-this.#l(A[2])),o=1-r;t[0]=e[0]*a+s,t[1]=e[1]*n+g,t[2]=e[2]*r+o}#u(A,e,t){if(1===A[0]&&1===A[2])return t[0]=e[0],t[1]=e[1],void(t[2]=e[2]);const i=t;this.#c(ue.#i,e,i);const a=ue.#g;this.#C(A,i,a),this.#c(ue.#a,a,t)}#d(A,e,t){const i=t;this.#c(ue.#i,e,i);const a=ue.#g;this.#B(A,i,a),this.#c(ue.#a,a,t)}#t(A,e,t,i,a){const s=this.#Q(0,1,A[e]*a),n=this.#Q(0,1,A[e+1]*a),g=this.#Q(0,1,A[e+2]*a),r=1===s?1:s**this.GR,o=1===n?1:n**this.GG,I=1===g?1:g**this.GB,c=this.MXA*r+this.MXB*o+this.MXC*I,C=this.MYA*r+this.MYB*o+this.MYC*I,B=this.MZA*r+this.MZB*o+this.MZC*I,h=ue.#r;h[0]=c,h[1]=C,h[2]=B;const Q=ue.#o;this.#u(this.whitePoint,h,Q);const l=ue.#r;this.#E(this.blackPoint,Q,l);const E=ue.#o;this.#d(ue.#n,l,E);const u=ue.#r;this.#c(ue.#s,E,u),t[i]=255*this.#h(u[0]),t[i+1]=255*this.#h(u[1]),t[i+2]=255*this.#h(u[2])}getRgbItem(A,e,t,i){this.#t(A,e,t,i,1)}getRgbBuffer(A,e,t,i,a,s,n){const g=1/((1<this.amax||this.bmin>this.bmax)&&(S("Invalid Range, falling back to defaults"),this.amin=-100,this.amax=100,this.bmin=-100,this.bmax=100)}#f(A){return A>=6/29?A**3:108/841*(A-4/29)}#p(A,e,t,i){return t+A*(i-t)/e}#t(A,e,t,i,a){let s=A[e],n=A[e+1],g=A[e+2];!1!==t&&(s=this.#p(s,t,0,100),n=this.#p(n,t,this.amin,this.amax),g=this.#p(g,t,this.bmin,this.bmax)),n>this.amax?n=this.amax:nthis.bmax?g=this.bmax:g>>0}function pe(A,e){return 1===e?String.fromCharCode(A[0],A[1]):3===e?String.fromCharCode(A[0],A[1],A[2],A[3]):String.fromCharCode(...A.subarray(0,e+1))}function me(A,e,t){let i=0;for(let a=t;a>=0;a--)i+=A[a]+e[a],A[a]=255&i,i>>=8}function ye(A,e){let t=1;for(let i=e;i>=0&&t>0;i--)t+=A[i],A[i]=255&t,t>>=8}const we=16;class De{constructor(A){this.buffer=A,this.pos=0,this.end=A.length,this.tmpBuf=new Uint8Array(19)}readByte(){return this.pos>=this.end?-1:this.buffer[this.pos++]}readNumber(){let A,e=0;do{const t=this.readByte();if(t<0)throw new K("unexpected EOF in bcmap");A=!(128&t),e=e<<7|127&t}while(!A);return e}readSigned(){const A=this.readNumber();return 1&A?~(A>>>1):A>>>1}readHex(A,e){A.set(this.buffer.subarray(this.pos,this.pos+e+1)),this.pos+=e+1}readHexNumber(A,e){let t;const i=this.tmpBuf;let a=0;do{const A=this.readByte();if(A<0)throw new K("unexpected EOF in bcmap");t=!(128&A),i[a++]=127&A}while(!t);let s=e,n=0,g=0;for(;s>=0;){for(;g<8&&i.length>0;)n|=i[--a]<>=8,g-=8}}readHexSigned(A,e){this.readHexNumber(A,e);const t=1&A[e]?255:0;let i=0;for(let a=0;a<=e;a++)i=(1&i)<<8|A[a],A[a]=i>>1^t}readString(){const A=this.readNumber(),e=new Array(A);for(let t=0;t=0;){const A=C>>5;if(7===A){switch(31&C){case 0:i.readString();break;case 1:s=i.readString()}continue}const t=!!(16&C),a=15&C;if(a+1>we)throw new Error("BinaryCMapReader.process: Invalid dataSize.");const B=1,h=i.readNumber();switch(A){case 0:i.readHex(n,a),i.readHexNumber(g,a),me(g,n,a),e.addCodespaceRange(a+1,fe(n,a),fe(g,a));for(let A=1;Aa&&(i=a)}else{for(;!this.eof;)this.readBlock(e);i=this.bufferLength}return this.pos=i,this.buffer.subarray(t,i)}async getImageData(A,e=null){if(!this.canAsyncDecodeImageFromBuffer)return this.getBytes(A,e);const t=await this.stream.asyncGetBytes();return this.decodeImage(t,e)}reset(){this.pos=0}makeSubStream(A,e,t=null){if(void 0===e)for(;!this.eof;)this.readBlock();else{const t=A+e;for(;this.bufferLength<=t&&!this.eof;)this.readBlock()}return new ae(this.buffer,A,e,t)}getBaseStreams(){return this.str?this.str.getBaseStreams():null}}class Se extends Fe{constructor(A,e=null){let t=0;for(const e of A)t+=e instanceof Fe?e._rawMinBufferLength:e.length;super(t),this.streams=A,this._onError=e}readBlock(){const A=this.streams;if(0===A.length)return void(this.eof=!0);const e=A.shift();let t;try{t=e.getBytes()}catch(A){if(this._onError)return void this._onError(A,e.dict?.objId);throw A}const i=this.bufferLength,a=i+t.length;this.ensureBuffer(a).set(t,i),this.bufferLength=a}getBaseStreams(){const A=[];for(const e of this.streams){const t=e.getBaseStreams();t&&A.push(...t)}return A.length>0?A:null}}class Re extends Fe{constructor(A,e){e&&(e*=.8),super(e),this.str=A,this.dict=A.dict,this.input=new Uint8Array(5)}readBlock(){const A=this.str;let e=A.getByte();for(;MA(e);)e=A.getByte();if(-1===e||126===e)return void(this.eof=!0);const t=this.bufferLength;let i,a;if(122===e){for(i=this.ensureBuffer(t+4),a=0;a<4;++a)i[t+a]=0;this.bufferLength+=4}else{const s=this.input;for(s[0]=e,a=1;a<5;++a){for(e=A.getByte();MA(e);)e=A.getByte();if(s[a]=e,-1===e||126===e)break}if(i=this.ensureBuffer(t+a-1),this.bufferLength+=a-1,a<5){for(;a<5;++a)s[a]=117;this.eof=!0}let n=0;for(a=0;a<5;++a)n=85*n+(s[a]-33);for(a=3;a>=0;--a)i[t+a]=255&n,n>>=8}}}class Ge extends Fe{constructor(A,e){e&&(e*=.5),super(e),this.str=A,this.dict=A.dict,this.firstDigit=-1}readBlock(){const A=this.str.getBytes(8e3);if(!A.length)return void(this.eof=!0);const e=A.length+1>>1,t=this.ensureBuffer(this.bufferLength+e);let i=this.bufferLength,a=this.firstDigit;for(const e of A){let A;if(e>=48&&e<=57)A=15&e;else{if(!(e>=65&&e<=70||e>=97&&e<=102)){if(62===e){this.eof=!0;break}continue}A=9+(15&e)}a<0?a=A:(t[i++]=a<<4|A,a=-1)}a>=0&&this.eof&&(t[i++]=a<<4,a=-1),this.firstDigit=a,this.bufferLength=i}}const Ne=-1,xe=[[-1,-1],[-1,-1],[7,8],[7,7],[6,6],[6,6],[6,5],[6,5],[4,0],[4,0],[4,0],[4,0],[4,0],[4,0],[4,0],[4,0],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2]],Ue=[[-1,-1],[12,-2],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[11,1792],[11,1792],[12,1984],[12,2048],[12,2112],[12,2176],[12,2240],[12,2304],[11,1856],[11,1856],[11,1920],[11,1920],[12,2368],[12,2432],[12,2496],[12,2560]],Me=[[-1,-1],[-1,-1],[-1,-1],[-1,-1],[8,29],[8,29],[8,30],[8,30],[8,45],[8,45],[8,46],[8,46],[7,22],[7,22],[7,22],[7,22],[7,23],[7,23],[7,23],[7,23],[8,47],[8,47],[8,48],[8,48],[6,13],[6,13],[6,13],[6,13],[6,13],[6,13],[6,13],[6,13],[7,20],[7,20],[7,20],[7,20],[8,33],[8,33],[8,34],[8,34],[8,35],[8,35],[8,36],[8,36],[8,37],[8,37],[8,38],[8,38],[7,19],[7,19],[7,19],[7,19],[8,31],[8,31],[8,32],[8,32],[6,1],[6,1],[6,1],[6,1],[6,1],[6,1],[6,1],[6,1],[6,12],[6,12],[6,12],[6,12],[6,12],[6,12],[6,12],[6,12],[8,53],[8,53],[8,54],[8,54],[7,26],[7,26],[7,26],[7,26],[8,39],[8,39],[8,40],[8,40],[8,41],[8,41],[8,42],[8,42],[8,43],[8,43],[8,44],[8,44],[7,21],[7,21],[7,21],[7,21],[7,28],[7,28],[7,28],[7,28],[8,61],[8,61],[8,62],[8,62],[8,63],[8,63],[8,0],[8,0],[8,320],[8,320],[8,384],[8,384],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[7,27],[7,27],[7,27],[7,27],[8,59],[8,59],[8,60],[8,60],[9,1472],[9,1536],[9,1600],[9,1728],[7,18],[7,18],[7,18],[7,18],[7,24],[7,24],[7,24],[7,24],[8,49],[8,49],[8,50],[8,50],[8,51],[8,51],[8,52],[8,52],[7,25],[7,25],[7,25],[7,25],[8,55],[8,55],[8,56],[8,56],[8,57],[8,57],[8,58],[8,58],[6,192],[6,192],[6,192],[6,192],[6,192],[6,192],[6,192],[6,192],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[8,448],[8,448],[8,512],[8,512],[9,704],[9,768],[8,640],[8,640],[8,576],[8,576],[9,832],[9,896],[9,960],[9,1024],[9,1088],[9,1152],[9,1216],[9,1280],[9,1344],[9,1408],[7,256],[7,256],[7,256],[7,256],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[6,16],[6,16],[6,16],[6,16],[6,16],[6,16],[6,16],[6,16],[6,17],[6,17],[6,17],[6,17],[6,17],[6,17],[6,17],[6,17],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[6,14],[6,14],[6,14],[6,14],[6,14],[6,14],[6,14],[6,14],[6,15],[6,15],[6,15],[6,15],[6,15],[6,15],[6,15],[6,15],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7]],Le=[[-1,-1],[-1,-1],[12,-2],[12,-2],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[11,1792],[11,1792],[11,1792],[11,1792],[12,1984],[12,1984],[12,2048],[12,2048],[12,2112],[12,2112],[12,2176],[12,2176],[12,2240],[12,2240],[12,2304],[12,2304],[11,1856],[11,1856],[11,1856],[11,1856],[11,1920],[11,1920],[11,1920],[11,1920],[12,2368],[12,2368],[12,2432],[12,2432],[12,2496],[12,2496],[12,2560],[12,2560],[10,18],[10,18],[10,18],[10,18],[10,18],[10,18],[10,18],[10,18],[12,52],[12,52],[13,640],[13,704],[13,768],[13,832],[12,55],[12,55],[12,56],[12,56],[13,1280],[13,1344],[13,1408],[13,1472],[12,59],[12,59],[12,60],[12,60],[13,1536],[13,1600],[11,24],[11,24],[11,24],[11,24],[11,25],[11,25],[11,25],[11,25],[13,1664],[13,1728],[12,320],[12,320],[12,384],[12,384],[12,448],[12,448],[13,512],[13,576],[12,53],[12,53],[12,54],[12,54],[13,896],[13,960],[13,1024],[13,1088],[13,1152],[13,1216],[10,64],[10,64],[10,64],[10,64],[10,64],[10,64],[10,64],[10,64]],Je=[[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[11,23],[11,23],[12,50],[12,51],[12,44],[12,45],[12,46],[12,47],[12,57],[12,58],[12,61],[12,256],[10,16],[10,16],[10,16],[10,16],[10,17],[10,17],[10,17],[10,17],[12,48],[12,49],[12,62],[12,63],[12,30],[12,31],[12,32],[12,33],[12,40],[12,41],[11,22],[11,22],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[9,15],[9,15],[9,15],[9,15],[9,15],[9,15],[9,15],[9,15],[12,128],[12,192],[12,26],[12,27],[12,28],[12,29],[11,19],[11,19],[11,20],[11,20],[12,34],[12,35],[12,36],[12,37],[12,38],[12,39],[11,21],[11,21],[12,42],[12,43],[10,0],[10,0],[10,0],[10,0],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12]],He=[[-1,-1],[-1,-1],[-1,-1],[-1,-1],[6,9],[6,8],[5,7],[5,7],[4,6],[4,6],[4,6],[4,6],[4,5],[4,5],[4,5],[4,5],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2]];class Ye{constructor(A,e={}){if(!A||"function"!=typeof A.next)throw new Error('CCITTFaxDecoder - invalid "source" parameter.');let t;for(this.source=A,this.eof=!1,this.encoding=e.K||0,this.eoline=e.EndOfLine||!1,this.byteAlign=e.EncodedByteAlign||!1,this.columns=e.Columns||1728,this.rows=e.Rows||0,this.eoblock=e.EndOfBlock??!0,this.black=e.BlackIs1||!1,this.codingLine=new Uint32Array(this.columns+1),this.refLine=new Uint32Array(this.columns+2),this.codingLine[0]=this.columns,this.codingPos=0,this.row=0,this.nextLine2D=this.encoding<0,this.inputBits=0,this.inputBuf=0,this.outputBits=0,this.rowsDone=!1;0===(t=this._lookBits(12));)this._eatBits(1);1===t&&this._eatBits(12),this.encoding>0&&(this.nextLine2D=!this._lookBits(1),this._eatBits(1))}readNextChar(){if(this.eof)return-1;const A=this.refLine,e=this.codingLine,t=this.columns;let i,a,s,n,g;if(0===this.outputBits){if(this.rowsDone&&(this.eof=!0),this.eof)return-1;let s,g,r;if(this.err=!1,this.nextLine2D){for(n=0;e[n]=64);do{g+=r=this._getWhiteCode()}while(r>=64)}else{do{s+=r=this._getWhiteCode()}while(r>=64);do{g+=r=this._getBlackCode()}while(r>=64)}for(this._addPixels(e[this.codingPos]+s,a),e[this.codingPos]0?--i:++i;A[i]<=e[this.codingPos]&&A[i]0?--i:++i;A[i]<=e[this.codingPos]&&A[i]0?--i:++i;A[i]<=e[this.codingPos]&&A[i]=64);else do{s+=r=this._getWhiteCode()}while(r>=64);this._addPixels(e[this.codingPos]+s,a),a^=1}let o=!1;if(this.byteAlign&&(this.inputBits&=-8),this.eoblock||this.row!==this.rows-1){if(s=this._lookBits(12),this.eoline)for(;s!==Ne&&1!==s;)this._eatBits(1),s=this._lookBits(12);else for(;0===s;)this._eatBits(1),s=this._lookBits(12);1===s?(this._eatBits(12),o=!0):s===Ne&&(this.eof=!0)}else this.rowsDone=!0;if(!this.eof&&this.encoding>0&&!this.rowsDone&&(this.nextLine2D=!this._lookBits(1),this._eatBits(1)),this.eoblock&&o&&this.byteAlign){if(s=this._lookBits(12),1===s){if(this._eatBits(12),this.encoding>0&&(this._lookBits(1),this._eatBits(1)),this.encoding>=0)for(n=0;n<4;++n)s=this._lookBits(12),1!==s&&S("bad rtc code: "+s),this._eatBits(12),this.encoding>0&&(this._lookBits(1),this._eatBits(1));this.eof=!0}}else if(this.err&&this.eoline){for(;;){if(s=this._lookBits(13),s===Ne)return this.eof=!0,-1;if(s>>1==1)break;this._eatBits(1)}this._eatBits(12),this.encoding>0&&(this._eatBits(1),this.nextLine2D=!(1&s))}this.outputBits=e[0]>0?e[this.codingPos=0]:e[this.codingPos=1],this.row++}if(this.outputBits>=8)g=1&this.codingPos?0:255,this.outputBits-=8,0===this.outputBits&&e[this.codingPos]s?(g<<=s,1&this.codingPos||(g|=255>>8-s),this.outputBits-=s,s=0):(g<<=this.outputBits,1&this.codingPos||(g|=255>>8-this.outputBits),s-=this.outputBits,this.outputBits=0,e[this.codingPos]0&&(g<<=s,s=0))}while(s)}return this.black&&(g^=255),g}_addPixels(A,e){const t=this.codingLine;let i=this.codingPos;A>t[i]&&(A>this.columns&&(S("row is wrong length"),this.err=!0,A=this.columns),1&i^e&&++i,t[i]=A),this.codingPos=i}_addPixelsNeg(A,e){const t=this.codingLine;let i=this.codingPos;if(A>t[i])A>this.columns&&(S("row is wrong length"),this.err=!0,A=this.columns),1&i^e&&++i,t[i]=A;else if(A0&&A=a){const e=t[A-a];if(e[0]===i)return this._eatBits(i),[!0,e[1],!0]}}return[!1,0,!1]}_getTwoDimCode(){let A,e=0;if(this.eoblock){if(e=this._lookBits(7),A=xe[e],A?.[0]>0)return this._eatBits(A[0]),A[1]}else{const A=this._findTableCode(1,7,xe);if(A[0]&&A[2])return A[1]}return S("Bad two dim code"),Ne}_getWhiteCode(){let A,e=0;if(this.eoblock){if(e=this._lookBits(12),e===Ne)return 1;if(A=e>>5==0?Ue[e]:Me[e>>3],A[0]>0)return this._eatBits(A[0]),A[1]}else{let A=this._findTableCode(1,9,Me);if(A[0])return A[1];if(A=this._findTableCode(11,12,Ue),A[0])return A[1]}return S("bad white code"),this._eatBits(1),1}_getBlackCode(){let A,e;if(this.eoblock){if(A=this._lookBits(13),A===Ne)return 1;if(e=A>>7==0?Le[A]:A>>9==0&&A>>7!=0?Je[(A>>1)-64]:He[A>>7],e[0]>0)return this._eatBits(e[0]),e[1]}else{let A=this._findTableCode(2,6,He);if(A[0])return A[1];if(A=this._findTableCode(7,12,Je,64),A[0])return A[1];if(A=this._findTableCode(10,13,Le),A[0])return A[1]}return S("bad black code"),this._eatBits(1),1}_lookBits(A){let e;for(;this.inputBits>16-A;this.inputBuf=this.inputBuf<<8|e,this.inputBits+=8}return this.inputBuf>>this.inputBits-A&65535>>16-A}_eatBits(A){(this.inputBits-=A)<0&&(this.inputBits=0)}}class ve extends Fe{constructor(A,e,t){super(e),this.str=A,this.dict=A.dict,t instanceof CA||(t=CA.empty);const i={next:()=>A.getByte()};this.ccittFaxDecoder=new Ye(i,{K:t.get("K"),EndOfLine:t.get("EndOfLine"),EncodedByteAlign:t.get("EncodedByteAlign"),Columns:t.get("Columns"),Rows:t.get("Rows"),EndOfBlock:t.get("EndOfBlock"),BlackIs1:t.get("BlackIs1")})}readBlock(){for(;!this.eof;){const A=this.ccittFaxDecoder.readNextChar();if(-1===A)return void(this.eof=!0);this.ensureBuffer(this.bufferLength+1),this.buffer[this.bufferLength++]=A}}}const Ke=new Int32Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),qe=new Int32Array([3,4,5,6,7,8,9,10,65547,65549,65551,65553,131091,131095,131099,131103,196643,196651,196659,196667,262211,262227,262243,262259,327811,327843,327875,327907,258,258,258]),Te=new Int32Array([1,2,3,4,65541,65543,131081,131085,196625,196633,262177,262193,327745,327777,393345,393409,459009,459137,524801,525057,590849,591361,657409,658433,724993,727041,794625,798721,868353,876545]),Pe=[new Int32Array([459008,524368,524304,524568,459024,524400,524336,590016,459016,524384,524320,589984,524288,524416,524352,590048,459012,524376,524312,589968,459028,524408,524344,590032,459020,524392,524328,59e4,524296,524424,524360,590064,459010,524372,524308,524572,459026,524404,524340,590024,459018,524388,524324,589992,524292,524420,524356,590056,459014,524380,524316,589976,459030,524412,524348,590040,459022,524396,524332,590008,524300,524428,524364,590072,459009,524370,524306,524570,459025,524402,524338,590020,459017,524386,524322,589988,524290,524418,524354,590052,459013,524378,524314,589972,459029,524410,524346,590036,459021,524394,524330,590004,524298,524426,524362,590068,459011,524374,524310,524574,459027,524406,524342,590028,459019,524390,524326,589996,524294,524422,524358,590060,459015,524382,524318,589980,459031,524414,524350,590044,459023,524398,524334,590012,524302,524430,524366,590076,459008,524369,524305,524569,459024,524401,524337,590018,459016,524385,524321,589986,524289,524417,524353,590050,459012,524377,524313,589970,459028,524409,524345,590034,459020,524393,524329,590002,524297,524425,524361,590066,459010,524373,524309,524573,459026,524405,524341,590026,459018,524389,524325,589994,524293,524421,524357,590058,459014,524381,524317,589978,459030,524413,524349,590042,459022,524397,524333,590010,524301,524429,524365,590074,459009,524371,524307,524571,459025,524403,524339,590022,459017,524387,524323,589990,524291,524419,524355,590054,459013,524379,524315,589974,459029,524411,524347,590038,459021,524395,524331,590006,524299,524427,524363,590070,459011,524375,524311,524575,459027,524407,524343,590030,459019,524391,524327,589998,524295,524423,524359,590062,459015,524383,524319,589982,459031,524415,524351,590046,459023,524399,524335,590014,524303,524431,524367,590078,459008,524368,524304,524568,459024,524400,524336,590017,459016,524384,524320,589985,524288,524416,524352,590049,459012,524376,524312,589969,459028,524408,524344,590033,459020,524392,524328,590001,524296,524424,524360,590065,459010,524372,524308,524572,459026,524404,524340,590025,459018,524388,524324,589993,524292,524420,524356,590057,459014,524380,524316,589977,459030,524412,524348,590041,459022,524396,524332,590009,524300,524428,524364,590073,459009,524370,524306,524570,459025,524402,524338,590021,459017,524386,524322,589989,524290,524418,524354,590053,459013,524378,524314,589973,459029,524410,524346,590037,459021,524394,524330,590005,524298,524426,524362,590069,459011,524374,524310,524574,459027,524406,524342,590029,459019,524390,524326,589997,524294,524422,524358,590061,459015,524382,524318,589981,459031,524414,524350,590045,459023,524398,524334,590013,524302,524430,524366,590077,459008,524369,524305,524569,459024,524401,524337,590019,459016,524385,524321,589987,524289,524417,524353,590051,459012,524377,524313,589971,459028,524409,524345,590035,459020,524393,524329,590003,524297,524425,524361,590067,459010,524373,524309,524573,459026,524405,524341,590027,459018,524389,524325,589995,524293,524421,524357,590059,459014,524381,524317,589979,459030,524413,524349,590043,459022,524397,524333,590011,524301,524429,524365,590075,459009,524371,524307,524571,459025,524403,524339,590023,459017,524387,524323,589991,524291,524419,524355,590055,459013,524379,524315,589975,459029,524411,524347,590039,459021,524395,524331,590007,524299,524427,524363,590071,459011,524375,524311,524575,459027,524407,524343,590031,459019,524391,524327,589999,524295,524423,524359,590063,459015,524383,524319,589983,459031,524415,524351,590047,459023,524399,524335,590015,524303,524431,524367,590079]),9],We=[new Int32Array([327680,327696,327688,327704,327684,327700,327692,327708,327682,327698,327690,327706,327686,327702,327694,0,327681,327697,327689,327705,327685,327701,327693,327709,327683,327699,327691,327707,327687,327703,327695,0]),5];class Ze extends Fe{constructor(A,e){super(e),this.str=A,this.dict=A.dict;const t=A.getByte(),i=A.getByte();if(-1===t||-1===i)throw new K(`Invalid header in flate stream: ${t}, ${i}`);if(8!=(15&t))throw new K(`Unknown compression method in flate stream: ${t}, ${i}`);if(((t<<8)+i)%31!=0)throw new K(`Bad FCHECK in flate stream: ${t}, ${i}`);if(32&i)throw new K(`FDICT bit set in flate stream: ${t}, ${i}`);this.codeSize=0,this.codeBuf=0}async getImageData(A,e){return(await this.asyncGetBytes())?.subarray(0,A)||this.getBytes(A)}async asyncGetBytes(){this.str.reset();const A=this.str.getBytes();try{const{readable:e,writable:t}=new DecompressionStream("deflate"),i=t.getWriter();i.write(A),i.close();const a=[];let s=0;for await(const A of e)a.push(A),s+=A.byteLength;const n=new Uint8Array(s);let g=0;for(const A of a)n.set(A,g),g+=A.byteLength;return n}catch{return this.str=new ae(A,2,A.length,this.str.dict),this.reset(),null}}get isAsync(){return!0}getBits(A){const e=this.str;let t,i=this.codeSize,a=this.codeBuf;for(;i>A,this.codeSize=i-=A,t}getCode(A){const e=this.str,t=A[0],i=A[1];let a,s=this.codeSize,n=this.codeBuf;for(;s>16,o=65535&g;if(r<1||s>r,this.codeSize=s-r,o}generateHuffmanTable(A){const e=A.length;let t,i=0;for(t=0;ti&&(i=A[t]);const a=1<>=1;for(t=A;t>=1,0===e){let e;if(-1===(e=i.getByte()))return void this.#m("Bad block header in flate stream");let t=e;if(-1===(e=i.getByte()))return void this.#m("Bad block header in flate stream");if(t|=e<<8,-1===(e=i.getByte()))return void this.#m("Bad block header in flate stream");let a=e;if(-1===(e=i.getByte()))return void this.#m("Bad block header in flate stream");if(a|=e<<8,a!==(65535&~t)&&(0!==t||0!==a))throw new K("Bad uncompressed block length in flate stream");this.codeBuf=0,this.codeSize=0;const s=this.bufferLength,n=s+t;if(A=this.ensureBuffer(n),this.bufferLength=n,0===t)-1===i.peekByte()&&(this.eof=!0);else{const e=i.getBytes(t);A.set(e,s),e.length0;)I[g++]=B}a=this.generateHuffmanTable(I.subarray(0,A)),s=this.generateHuffmanTable(I.subarray(A,o))}}A=this.buffer;let n=A?A.length:0,g=this.bufferLength;for(;;){let e=this.getCode(a);if(e<256){g+1>=n&&(A=this.ensureBuffer(g+1),n=A.length),A[g++]=e;continue}if(256===e)return void(this.bufferLength=g);e-=257,e=qe[e];let i=e>>16;i>0&&(i=this.getBits(i)),t=(65535&e)+i,e=this.getCode(s),e=Te[e],i=e>>16,i>0&&(i=this.getBits(i));const r=(65535&e)+i;g+t>=n&&(A=this.ensureBuffer(g+t),n=A.length);for(let e=0;e>9&127,this.clow=this.clow<<7&65535,this.ct-=7,this.a=32768}byteIn(){const A=this.data;let e=this.bp;255===A[e]?A[e+1]>143?(this.clow+=65280,this.ct=8):(e++,this.clow+=A[e]<<9,this.ct=7,this.bp=e):(e++,this.clow+=e65535&&(this.chigh+=this.clow>>16,this.clow&=65535)}readBit(A,e){let t=A[e]>>1,i=1&A[e];const a=Oe[t],s=a.qe;let n,g=this.a-s;if(this.chigh>15&1,this.clow=this.clow<<1&65535,this.ct--}while(0==(32768&g));return this.a=g,A[e]=t<<1|i,n}}class Ve extends M{constructor(A){super(A,"Jbig2Error")}}class je{getContexts(A){return A in this?this[A]:this[A]=new Int8Array(65536)}}class ze{constructor(A,e,t){this.data=A,this.start=e,this.end=t}get decoder(){return U(this,"decoder",new Xe(this.data,this.start,this.end))}get contextCache(){return U(this,"contextCache",new je)}}function _e(A,e,t){const i=A.getContexts(e);let a=1;function s(A){let e=0;for(let s=0;s>>0}const n=s(1),g=s(1)?s(1)?s(1)?s(1)?s(1)?s(32)+4436:s(12)+340:s(8)+84:s(6)+20:s(4)+4:s(2);let r;return 0===n?r=g:g>0&&(r=-g),r>=-2147483648&&r<=2147483647?r:null}function $e(A,e,t){const i=A.getContexts("IAID");let a=1;for(let A=0;A=w&&N=D)for(H=H<<1&l,Q=0;Q=0&&U=0&&(M=S[x][U],M&&(H|=M<=A?o<<=1:o=o<<1|p[g][r];for(B=0;B=d||r<0||r>=u?o<<=1:o=o<<1|i[g][r];const h=m.readBit(y,o);e[n]=h}}return p}function gt(A,e,t,i,a,s,n,g,r,o,I,c,C,B,h,Q,l,E,u){if(A&&e)throw new Ve("refinement with Huffman is not supported");const d=[];let f,p;for(f=0;f1&&(a=A?u.readBits(E):_e(y,"IAIT",m));const s=n*w+a,D=A?B.symbolIDTable.decode(u):$e(y,m,r),b=e&&(A?u.readBit():_e(y,"IARI",m));let k=g[D],F=k[0].length,S=k.length;if(b){const A=_e(y,"IARDW",m),e=_e(y,"IARDH",m);F+=A,S+=e,k=nt(F,S,h,k,(A>>1)+_e(y,"IARDX",m),(e>>1)+_e(y,"IARDY",m),!1,Q,l)}let R=0;o?1&c?R=S-1:i+=S-1:c>1?i+=F-1:R=F-1;const G=s-(1&c?0:S-1),N=i-(2&c?F-1:0);let x,U,M;if(o)for(x=0;x>5&7;const r=[31&n];let o=e+6;if(7===n){g=536870911&UA(A,o-1),o+=3;let e=g+7>>3;for(r[0]=A[o++];--e>0;)r.push(A[o++])}else if(5===n||6===n)throw new Ve("invalid referred-to flags");t.retainBits=r;let I=4;t.number<=256?I=1:t.number<=65536&&(I=2);const c=[];let C,B;for(C=0;C>>24&255,s[3]=e.height>>16&255,s[4]=e.height>>8&255,s[5]=255&e.height,C=o,B=A.length;C>2&3,A.huffmanDWSelector=e>>4&3,A.bitmapSizeSelector=e>>6&1,A.aggregationInstancesSelector=e>>7&1,A.bitmapCodingContextUsed=!!(256&e),A.bitmapCodingContextRetained=!!(512&e),A.template=e>>10&3,A.refinementTemplate=e>>12&1,o+=2,!A.huffman){for(r=0===A.template?4:1,n=[],g=0;g>2&3,I.stripSize=1<>4&3,I.transposed=!!(64&c),I.combinationOperator=c>>7&3,I.defaultPixelValue=c>>9&1,I.dsOffset=c<<17>>27,I.refinementTemplate=c>>15&1,I.huffman){const A=xA(i,o);o+=2,I.huffmanFS=3&A,I.huffmanDS=A>>2&3,I.huffmanDT=A>>4&3,I.huffmanRefinementDW=A>>6&3,I.huffmanRefinementDH=A>>8&3,I.huffmanRefinementDX=A>>10&3,I.huffmanRefinementDY=A>>12&3,I.huffmanRefinementSizeSelector=!!(16384&A)}if(I.refinement&&!I.refinementTemplate){for(n=[],g=0;g<2;g++)n.push({x:NA(i,o),y:NA(i,o+1)}),o+=2;I.refinementAt=n}I.numberOfSymbolInstances=UA(i,o),o+=4,s=[I,t.referredTo,i,o,a];break;case 16:const C={},B=i[o++];C.mmr=!!(1&B),C.template=B>>1&3,C.patternWidth=i[o++],C.patternHeight=i[o++],C.maxPatternIndex=UA(i,o),o+=4,s=[C,t.number,i,o,a];break;case 22:case 23:const h={};h.info=It(i,o),o+=ct;const Q=i[o++];h.mmr=!!(1&Q),h.template=Q>>1&3,h.enableSkip=!!(8&Q),h.combinationOperator=Q>>4&7,h.defaultPixelValue=Q>>7&1,h.gridWidth=UA(i,o),o+=4,h.gridHeight=UA(i,o),o+=4,h.gridOffsetX=4294967295&UA(i,o),o+=4,h.gridOffsetY=4294967295&UA(i,o),o+=4,h.gridVectorX=xA(i,o),o+=2,h.gridVectorY=xA(i,o),o+=2,s=[h,t.referredTo,i,o,a];break;case 38:case 39:const l={};l.info=It(i,o),o+=ct;const E=i[o++];if(l.mmr=!!(1&E),l.template=E>>1&3,l.prediction=!!(8&E),!l.mmr){for(r=0===l.template?4:1,n=[],g=0;g>2&1,u.combinationOperator=d>>3&3,u.requiresBuffer=!!(32&d),u.combinationOperatorOverride=!!(64&d),s=[u];break;case 49:case 50:case 51:case 62:break;case 53:s=[t.number,i,o,a];break;default:throw new Ve(`segment type ${t.typeName}(${t.type}) is not implemented`)}const I="on"+t.typeName;I in e&&e[I].apply(e,s)}function Bt(A,e){for(let t=0,i=A.length;t>3,t=new Uint8ClampedArray(e*A.height);A.defaultPixelValue&&t.fill(255),this.buffer=t}drawBitmap(A,e){const t=this.currentPageInfo,i=A.width,a=A.height,s=t.width+7>>3,n=t.combinationOperatorOverride?A.combinationOperator:t.combinationOperator,g=this.buffer,r=128>>(7&A.x);let o,I,c,C,B=A.y*s+(A.x>>3);switch(n){case 0:for(o=0;o>=1,c||(c=128,C++);B+=s}break;case 2:for(o=0;o>=1,c||(c=128,C++);B+=s}break;default:throw new Ve(`operator ${n} is not supported`)}}onImmediateGenericRegion(A,e,t,i){const a=A.info,s=new ze(e,t,i),n=st(A.mmr,a.width,a.height,A.template,A.prediction,null,A.at,s);this.drawBitmap(a,n)}onImmediateLosslessGenericRegion(){this.onImmediateGenericRegion(...arguments)}onSymbolDictionary(A,e,t,i,a,s){let n,g;A.huffman&&(n=function(A,e,t){let i,a,s,n,g=0;switch(A.huffmanDHSelector){case 0:case 1:i=dt(A.huffmanDHSelector+4);break;case 3:i=pt(g,e,t),g++;break;default:throw new Ve("invalid Huffman DH selector")}switch(A.huffmanDWSelector){case 0:case 1:a=dt(A.huffmanDWSelector+2);break;case 3:a=pt(g,e,t),g++;break;default:throw new Ve("invalid Huffman DW selector")}return A.bitmapSizeSelector?(s=pt(g,e,t),g++):s=dt(1),n=A.aggregationInstancesSelector?pt(g,e,t):dt(1),{tableDeltaHeight:i,tableDeltaWidth:a,tableBitmapSize:s,tableAggregateInstances:n}}(A,t,this.customTables),g=new ft(i,a,s));let r=this.symbols;r||(this.symbols=r={});const o=[];for(const A of t){const e=r[A];e&&o.push(...e)}const I=new ze(i,a,s);r[e]=function(A,e,t,i,a,s,n,g,r,o,I,c){if(A&&e)throw new Ve("symbol refinement with Huffman is not supported");const C=[];let B=0,h=GA(t.length+i);const Q=I.decoder,l=I.contextCache;let E,u;for(A&&(E=dt(1),u=[],h=Math.max(h,1));C.length1)d=gt(A,e,i,B,0,a,1,t.concat(C),h,0,0,1,0,s,r,o,I,0,c);else{const A=$e(l,Q,h),e=_e(l,"IARDX",Q),a=_e(l,"IARDY",Q);d=nt(i,B,r,A=32){let t,i,n;switch(e){case 32:if(0===A)throw new Ve("no previous value in symbol ID table");i=a.readBits(2)+3,t=s[A-1].prefixLength;break;case 33:i=a.readBits(3)+3,t=0;break;case 34:i=a.readBits(7)+11,t=0;break;default:throw new Ve("invalid code length in symbol ID table")}for(n=0;n=0;l--)k=A?yt(b,r,o,!0):st(!1,r,o,t,!1,null,w,h),D[l]=k;for(F=0;F=0;E--)R^=D[E][F][S],G|=R<>8,U=c+F*C-S*B>>8,x>=0&&x+p<=i&&U>=0&&U+m<=a)for(l=0;l=a))for(L=Q[e],M=N[l],E=0;E=0&&A>1&7),r=1+(i>>4&7),o=[];let I,c,C=a;do{I=n.readBits(g),c=n.readBits(r),o.push(new Qt([C,I,c,0])),C+=1<>e&1;if(e<=0)this.children[t]=new lt(A);else{let i=this.children[t];i||(this.children[t]=i=new lt(null)),i.buildTree(A,e-1)}}decodeNode(A){if(this.isLeaf){if(this.isOOB)return null;const e=A.readBits(this.rangeLength);return this.rangeLow+(this.isLowerRange?-e:e)}const e=this.children[A.readBit()];if(!e)throw new Ve("invalid Huffman data");return e.decodeNode(A)}}class Et{constructor(A,e){e||this.assignPrefixCodes(A),this.rootNode=new lt(null);for(let e=0,t=A.length;e0&&this.rootNode.buildTree(t,t.prefixLength-1)}}decode(A){return this.rootNode.decodeNode(A)}assignPrefixCodes(A){const e=A.length;let t=0;for(let i=0;i=this.end)throw new Ve("end of data while reading bit");this.currentByte=this.data[this.position++],this.shift=7}const A=this.currentByte>>this.shift&1;return this.shift--,A}readBits(A){let e,t=0;for(e=A-1;e>=0;e--)t|=this.readBit()<=this.end?-1:this.data[this.position++]}}function pt(A,e,t){let i=0;for(let a=0,s=e.length;a>t&1,t--}if(i&&!g){const A=5;for(let e=0;e>3,c=7&i,C=A.length;t=new Uint32Array(t.buffer);let B=0;for(let i=0;i0&&!A[s-1];)s--;const n=[{children:[],index:0}];let g,r=n[0];for(t=0;t0;)r=n.pop();for(r.index++,n.push(r);n.length<=t;)n.push(g={children:[],index:0}),r.children[r.index]=g.children,r=g;a++}t+10)return h--,B>>h&1;if(B=A[e++],255===B){const i=A[e++];if(i){if(220===i&&o){const i=xA(A,e+=2);if(e+=2,i>0&&i!==t.scanLines)throw new Ft("Found DNL marker (0xFFDC) while parsing scan data",i)}else if(217===i){if(o){const A=m*(8===t.precision?8:0);if(A>0&&Math.round(t.scanLines/A)>=5)throw new Ft("Found EOI marker (0xFFD9) while parsing scan data, possibly caused by incorrect `scanLines` parameter",A)}throw new St("Found EOI marker (0xFFD9) while parsing scan data")}throw new kt(`unexpected marker ${(B<<8|i).toString(16)}`)}}return h=7,B>>>7}function l(A){let e=A;for(;;){switch(e=e[Q()],typeof e){case"number":return e;case"object":continue}throw new kt("invalid huffman sequence")}}function E(A){let e=0;for(;A>0;)e=e<<1|Q(),A--;return e}function u(A){if(1===A)return 1===Q()?1:-1;const e=E(A);return e>=1<0)return void f--;let t=s;const i=n;for(;t<=i;){const i=l(A.huffmanTableAC),a=15&i,s=i>>4;if(0===a){if(s<15){f=E(s)+(1<>4,0===a)o<15?(f=E(o)+(1<>4;if(0===i){if(s<15)break;a+=16;continue}a+=s;const n=Rt[a];A.blockData[e+n]=u(i),a++}};let x,U=0;const M=1===D?i[0].blocksPerLine*i[0].blocksPerColumn:I*t.mcusPerColumn;let L,J;for(;U<=M;){const t=a?Math.min(M-U,a):M;if(t>0){for(k=0;k0?"unexpected":"excessive"} MCU data, current marker is: ${x.invalid}`),e=x.offset),!(x.marker>=65488&&x.marker<=65495))break;e+=2}return e-C}function qt(A,e,t){const i=A.quantizationTable,a=A.blockData;let s,n,g,r,o,I,c,C,B,h,Q,l,E,u,d,f,p;if(!i)throw new kt("missing required Quantization Table.");for(let A=0;A<64;A+=8)B=a[e+A],h=a[e+A+1],Q=a[e+A+2],l=a[e+A+3],E=a[e+A+4],u=a[e+A+5],d=a[e+A+6],f=a[e+A+7],B*=i[A],0!=(h|Q|l|E|u|d|f)?(h*=i[A+1],Q*=i[A+2],l*=i[A+3],E*=i[A+4],u*=i[A+5],d*=i[A+6],f*=i[A+7],s=Jt*B+128>>8,n=Jt*E+128>>8,g=Q,r=d,o=Ht*(h-f)+128>>8,C=Ht*(h+f)+128>>8,I=l<<4,c=u<<4,s=s+n+1>>1,n=s-n,p=g*Lt+r*Mt+128>>8,g=g*Mt-r*Lt+128>>8,r=p,o=o+c+1>>1,c=o-c,C=C+I+1>>1,I=C-I,s=s+r+1>>1,r=s-r,n=n+g+1>>1,g=n-g,p=o*Ut+C*xt+2048>>12,o=o*xt-C*Ut+2048>>12,C=p,p=I*Nt+c*Gt+2048>>12,I=I*Gt-c*Nt+2048>>12,c=p,t[A]=s+C,t[A+7]=s-C,t[A+1]=n+c,t[A+6]=n-c,t[A+2]=g+I,t[A+5]=g-I,t[A+3]=r+o,t[A+4]=r-o):(p=Jt*B+512>>10,t[A]=p,t[A+1]=p,t[A+2]=p,t[A+3]=p,t[A+4]=p,t[A+5]=p,t[A+6]=p,t[A+7]=p);for(let A=0;A<8;++A)B=t[A],h=t[A+8],Q=t[A+16],l=t[A+24],E=t[A+32],u=t[A+40],d=t[A+48],f=t[A+56],0!=(h|Q|l|E|u|d|f)?(s=Jt*B+2048>>12,n=Jt*E+2048>>12,g=Q,r=d,o=Ht*(h-f)+2048>>12,C=Ht*(h+f)+2048>>12,I=l,c=u,s=4112+(s+n+1>>1),n=s-n,p=g*Lt+r*Mt+2048>>12,g=g*Mt-r*Lt+2048>>12,r=p,o=o+c+1>>1,c=o-c,C=C+I+1>>1,I=C-I,s=s+r+1>>1,r=s-r,n=n+g+1>>1,g=n-g,p=o*Ut+C*xt+2048>>12,o=o*xt-C*Ut+2048>>12,C=p,p=I*Nt+c*Gt+2048>>12,I=I*Gt-c*Nt+2048>>12,c=p,B=s+C,f=s-C,h=n+c,d=n-c,Q=g+I,u=g-I,l=r+o,E=r-o,B<16?B=0:B>=4080?B=255:B>>=4,h<16?h=0:h>=4080?h=255:h>>=4,Q<16?Q=0:Q>=4080?Q=255:Q>>=4,l<16?l=0:l>=4080?l=255:l>>=4,E<16?E=0:E>=4080?E=255:E>>=4,u<16?u=0:u>=4080?u=255:u>>=4,d<16?d=0:d>=4080?d=255:d>>=4,f<16?f=0:f>=4080?f=255:f>>=4,a[e+A]=B,a[e+A+8]=h,a[e+A+16]=Q,a[e+A+24]=l,a[e+A+32]=E,a[e+A+40]=u,a[e+A+48]=d,a[e+A+56]=f):(p=Jt*B+8192>>14,p=p<-2040?0:p>=2024?255:p+2056>>4,a[e+A]=p,a[e+A+8]=p,a[e+A+16]=p,a[e+A+24]=p,a[e+A+32]=p,a[e+A+40]=p,a[e+A+48]=p,a[e+A+56]=p)}function Tt(A,e){const t=e.blocksPerLine,i=e.blocksPerColumn,a=new Int16Array(64);for(let A=0;A=i)return null;const s=xA(A,e);if(s>=65472&&s<=65534)return{invalid:null,marker:s,offset:e};let n=xA(A,a);for(;!(n>=65472&&n<=65534);){if(++a>=i)return null;n=xA(A,a)}return{invalid:s.toString(16),marker:n,offset:a}}class Wt{constructor({decodeTransform:A=null,colorTransform:e=-1}={}){this._decodeTransform=A,this._colorTransform=e}parse(A,{dnlScanLines:e=null}={}){function t(){const e=xA(A,n);n+=2;let t=n+e-2;const i=Pt(A,t,n);i?.invalid&&(R("readDataBlock - incorrect length, current marker is: "+i.invalid),t=i.offset);const a=A.subarray(n,t);return n+=a.length,a}function i(A){const e=Math.ceil(A.samplesPerLine/8/A.maxH),t=Math.ceil(A.scanLines/8/A.maxV);for(const i of A.components){const a=Math.ceil(Math.ceil(A.samplesPerLine/8)*i.h/A.maxH),s=Math.ceil(Math.ceil(A.scanLines/8)*i.v/A.maxV),n=e*i.h,g=t*i.v*64*(n+1);i.blockData=new Int16Array(g),i.blocksPerLine=a,i.blocksPerColumn=s}A.mcusPerLine=e,A.mcusPerColumn=t}let a,s,n=0,g=null,r=null,o=0;const I=[],c=[],C=[];let B=xA(A,n);if(n+=2,65496!==B)throw new kt("SOI not found");B=xA(A,n),n+=2;A:for(;65497!==B;){let h,Q,l;switch(B){case 65504:case 65505:case 65506:case 65507:case 65508:case 65509:case 65510:case 65511:case 65512:case 65513:case 65514:case 65515:case 65516:case 65517:case 65518:case 65519:case 65534:const E=t();65504===B&&74===E[0]&&70===E[1]&&73===E[2]&&70===E[3]&&0===E[4]&&(g={version:{major:E[5],minor:E[6]},densityUnits:E[7],xDensity:E[8]<<8|E[9],yDensity:E[10]<<8|E[11],thumbWidth:E[12],thumbHeight:E[13],thumbData:E.subarray(14,14+3*E[12]*E[13])}),65518===B&&65===E[0]&&100===E[1]&&111===E[2]&&98===E[3]&&101===E[4]&&(r={version:E[5]<<8|E[6],flags0:E[7]<<8|E[8],flags1:E[9]<<8|E[10],transformCode:E[11]});break;case 65499:const u=xA(A,n);n+=2;const d=u+n-2;let f;for(;n>4==0)for(Q=0;Q<64;Q++)f=Rt[Q],t[f]=A[n++];else{if(e>>4!=1)throw new kt("DQT - invalid table spec");for(Q=0;Q<64;Q++)f=Rt[Q],t[f]=xA(A,n),n+=2}I[15&e]=t}break;case 65472:case 65473:case 65474:if(a)throw new kt("Only single frame JPEGs supported");n+=2,a={},a.extended=65473===B,a.progressive=65474===B,a.precision=A[n++];const p=xA(A,n);n+=2,a.scanLines=e||p,a.samplesPerLine=xA(A,n),n+=2,a.components=[],a.componentIds={};const m=A[n++];let y=0,w=0;for(h=0;h>4,i=15&A[n+1];y>4==0?C:c)[15&e]=Yt(t,a)}break;case 65501:n+=2,s=xA(A,n),n+=2;break;case 65498:const b=1==++o&&!e;n+=2;const k=A[n++],F=[];for(h=0;h>4],i.huffmanTableAC=c[15&s],F.push(i)}const S=A[n++],G=A[n++],N=A[n++];try{const e=Kt(A,n,a,F,s,S,G,N>>4,15&N,b);n+=e}catch(e){if(e instanceof Ft)return R(`${e.message} -- attempting to re-parse the JPEG image.`),this.parse(A,{dnlScanLines:e.scanLines});if(e instanceof St){R(`${e.message} -- ignoring the rest of the image data.`);break A}throw e}break;case 65500:n+=4;break;case 65535:255!==A[n]&&n--;break;default:const x=Pt(A,n-2,n-3);if(x?.invalid){R("JpegImage.parse - unexpected data, current marker is: "+x.invalid),n=x.offset;break}if(!x||n>=A.length-1){R("JpegImage.parse - reached the end of the image data without finding an EOI marker (0xFFD9).");break A}throw new kt("JpegImage.parse - unknown marker: "+B.toString(16))}B=xA(A,n),n+=2}if(!a)throw new kt("JpegImage.parse - no frame data found.");this.width=a.samplesPerLine,this.height=a.scanLines,this.jfif=g,this.adobe=r,this.components=[];for(const A of a.components){const e=I[A.quantizationId];e&&(A.quantizationTable=e),this.components.push({index:A.index,output:Tt(0,A),scaleX:A.h/a.maxH,scaleY:A.v/a.maxV,blocksPerLine:A.blocksPerLine,blocksPerColumn:A.blocksPerColumn})}this.numComponents=this.components.length}_getLinearizedBlockData(A,e,t=!1){const i=this.width/A,a=this.height/e;let s,n,g,r,o,I,c,C,B,h,Q,l=0;const E=this.components.length,u=A*e*E,d=new Uint8ClampedArray(u),f=new Uint32Array(A),p=4294967288;let m;for(c=0;c>8)+y[B+1];return d}get _isColorConversionNeeded(){return this.adobe?!!this.adobe.transformCode:3===this.numComponents?0!==this._colorTransform&&(82!==this.components[0].index||71!==this.components[1].index||66!==this.components[2].index):1===this._colorTransform}_convertYccToRgb(A){let e,t,i;for(let a=0,s=A.length;a4)throw new kt("Unsupported color mode");const s=this._getLinearizedBlockData(A,e,a);if(1===this.numComponents&&(t||i)){const A=s.length*(t?4:3),e=new Uint8ClampedArray(A);let i=0;if(t)!function(A,e){if(O.isLittleEndian)for(let t=0,i=A.length;t0&&(A=A.subarray(e));break}const e={decodeTransform:void 0,colorTransform:void 0},t=this.dict.getArray("D","Decode");if((this.forceRGBA||this.forceRGB)&&Array.isArray(t)){const A=this.dict.get("BPC","BitsPerComponent")||8,i=t.length,a=new Int32Array(i);let s=!1;const n=(1<{e=A,t=i})),i.decode=function(A,{numComponents:e=4,isIndexedColormap:t=!1,smaskInData:a=!1}){const s=A.length,n=i._malloc(s);i.HEAPU8.set(A,n);const g=i._jp2_decode(n,s,e>0?e:0,!!t,!!a);if(i._free(n),g){const{errorMessages:A}=i;return A?(delete i.errorMessages,A):"Unknown error"}const{imageData:r}=i;return i.imageData=null,r};var a=Object.assign({},i),s="./this.program",n="";"undefined"!=typeof document&&document.currentScript&&(n=document.currentScript.src),Ot&&(n=Ot),n=n.startsWith("blob:")?"":n.substr(0,n.replace(/[?#].*/,"").lastIndexOf("/")+1);var g,r,o,I,c,C=i.print||console.log.bind(console),B=i.printErr||console.error.bind(console);function h(){var A=r.buffer;i.HEAP8=o=new Int8Array(A),i.HEAP16=new Int16Array(A),i.HEAPU8=I=new Uint8Array(A),i.HEAPU16=new Uint16Array(A),i.HEAP32=new Int32Array(A),i.HEAPU32=c=new Uint32Array(A),i.HEAPF32=new Float32Array(A),i.HEAPF64=new Float64Array(A)}Object.assign(i,a),a=null,i.arguments&&i.arguments,i.thisProgram&&(s=i.thisProgram),i.quit&&i.quit,i.wasmBinary&&(g=i.wasmBinary);var Q,l=[],E=[],u=[],d=0,f=null,p=null,m="data:application/octet-stream;base64,",y=A=>A.startsWith(m);function w(A,e){var t,i=function(A){if(A==Q&&g)return new Uint8Array(g);var e=function(A){if(y(A))return function(A){for(var e=atob(A),t=new Uint8Array(e.length),i=0;i{for(;A.length>0;)A.shift()(i)};i.noExitRuntime;var b,k=A=>{var e=(A-r.buffer.byteLength+65535)/65536;try{return r.grow(e),h(),1}catch(A){}},F={},S=()=>{if(!S.strings){var A={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:s||"./this.program"};for(var e in F)void 0===F[e]?delete A[e]:A[e]=F[e];var t=[];for(var e in A)t.push(`${e}=${A[e]}`);S.strings=t}return S.strings},R=[null,[],[]],G="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0,N=(A,e,t)=>{for(var i=e+t,a=e;A[a]&&!(a>=i);)++a;if(a-e>16&&A.buffer&&G)return G.decode(A.subarray(e,a));for(var s="";e>10,56320|1023&o)}}else s+=String.fromCharCode((31&n)<<6|g)}else s+=String.fromCharCode(n)}return s},x=(A,e)=>A?N(I,A,e):"",U={c:(A,e,t)=>I.copyWithin(A,e,e+t),g:function(A,e){A>>=2;const t=i.imageData=new Uint8ClampedArray(e),a=i.HEAP32.subarray(A,A+e);t.set(a)},f:function(A,e,t,a){A>>=2,e>>=2,t>>=2;const s=i.imageData=new Uint8ClampedArray(3*a),n=i.HEAP32.subarray(A,A+a),g=i.HEAP32.subarray(e,e+a),r=i.HEAP32.subarray(t,t+a);for(let A=0;A>=2,e>>=2,t>>=2,a>>=2;const n=i.imageData=new Uint8ClampedArray(4*s),g=i.HEAP32.subarray(A,A+s),r=i.HEAP32.subarray(e,e+s),o=i.HEAP32.subarray(t,t+s),I=i.HEAP32.subarray(a,a+s);for(let A=0;A{var e=I.length,t=2147483648;if((A>>>=0)>t)return!1;for(var i,a=1;a<=4;a*=2){var s=e*(1+.2/a);s=Math.min(s,A+100663296);var n=Math.min(t,(i=Math.max(A,s))+(65536-i%65536)%65536);if(k(n))return!0}return!1},l:(A,e)=>{var t=0;return S().forEach(((i,a)=>{var s=e+t;c[A+4*a>>2]=s,((A,e)=>{for(var t=0;t{var t=S();c[A>>2]=t.length;var i=0;return t.forEach((A=>i+=A.length+1)),c[e>>2]=i,0},n:A=>52,j:function(A,e,t,i,a){return 70},b:(A,e,t,i)=>{for(var a,s,n,g=0,r=0;r>2],h=c[e+4>>2];e+=8;for(var Q=0;Q>2]=g,0},o:function(A,e){A>>=2;const t=i.imageData=new Uint8ClampedArray(4*e),a=i.HEAP32.subarray(A,A+e);for(let A=0;A>=2,e>>=2;const a=i.imageData=new Uint8ClampedArray(4*t),s=i.HEAP32.subarray(A,A+t),n=i.HEAP32.subarray(e,e+t);for(let A=0;A>=2,e>>=2,t>>=2;const s=i.imageData=new Uint8ClampedArray(4*a),n=i.HEAP32.subarray(A,A+a),g=i.HEAP32.subarray(e,e+a),r=i.HEAP32.subarray(t,t+a);for(let A=0;A0||(function(){if(i.preRun)for("function"==typeof i.preRun&&(i.preRun=[i.preRun]);i.preRun.length;)A=i.preRun.shift(),l.unshift(A);var A;D(l)}(),d>0||(i.setStatus?(i.setStatus("Running..."),setTimeout((function(){setTimeout((function(){i.setStatus("")}),1),A()}),1)):A()))}if(M.q,i._malloc=M.r,i._free=M.s,i._jp2_decode=M.u,p=function A(){b||L(),b||(p=A)},i.preInit)for("function"==typeof i.preInit&&(i.preInit=[i.preInit]);i.preInit.length>0;)i.preInit.pop()();return L(),i});const Vt=Xt;class jt extends M{constructor(A){super(A,"JpxError")}}class zt{static#y=null;static decode(A,e){e||={},this.#y||=Vt({warn:R});const t=this.#y.decode(A,e);if("string"==typeof t)throw new jt(t);return t}static cleanup(){this.#y=null}static parseImageProperties(A){let e=A.getByte();for(;e>=0;){const t=e;if(e=A.getByte(),65361==(t<<8|e)){A.skip(4);const e=A.getInt32()>>>0,t=A.getInt32()>>>0,i=A.getInt32()>>>0,a=A.getInt32()>>>0;return A.skip(16),{width:e-i,height:t-a,bitsPerComponent:8,componentsCount:A.getUint16()}}}throw new jt("No size marker found in JPX stream")}}class _t extends Fe{constructor(A,e,t){super(e),this.stream=A,this.dict=A.dict,this.maybeLength=e,this.params=t}get bytes(){return U(this,"bytes",this.stream.getBytes(this.maybeLength))}ensureBuffer(A){}readBlock(A){this.decodeImage(null,A)}decodeImage(A,e){return this.eof||(A||=this.bytes,this.buffer=zt.decode(A,e),this.bufferLength=this.buffer.length,this.eof=!0),this.buffer}get canAsyncDecodeImageFromBuffer(){return this.stream.isAsync}}class $t extends Fe{constructor(A,e,t){super(e),this.str=A,this.dict=A.dict,this.cachedData=0,this.bitsCached=0;const i=4096,a={earlyChange:t,codeLength:9,nextCode:258,dictionaryValues:new Uint8Array(i),dictionaryLengths:new Uint16Array(i),dictionaryPrevCodes:new Uint16Array(i),currentSequence:new Uint8Array(i),currentSequenceLength:0};for(let A=0;A<256;++A)a.dictionaryValues[A]=A,a.dictionaryLengths[A]=1;this.lzwState=a}readBits(A){let e=this.bitsCached,t=this.cachedData;for(;e>>e&(1<0;if(A<256)C[0]=A,B=1;else{if(!(A>=258)){if(256===A){I=9,n=258,B=0;continue}this.eof=!0,delete this.lzwState;break}if(A=0;e--)C[e]=g[t],t=o[t];else C[B++]=C[0]}if(a&&(o[n]=c,r[n]=r[c]+1,g[n]=C[0],n++,I=n+s&n+s-1?I:0|Math.min(Math.log(n+s)/.6931471805599453+1,12)),c=A,h+=B,i15))throw new K(`Unsupported predictor: ${i}`);this.readBlock=2===i?this.readBlockTiff:this.readBlockPng,this.str=A,this.dict=A.dict;const a=this.colors=t.get("Colors")||1,s=this.bits=t.get("BPC","BitsPerComponent")||8,n=this.columns=t.get("Columns")||1;return this.pixBytes=a*s+7>>3,this.rowBytes=n*a*s+7>>3,this}readBlockTiff(){const A=this.rowBytes,e=this.bufferLength,t=this.ensureBuffer(e+A),i=this.bits,a=this.colors,s=this.str.getBytes(A);if(this.eof=!s.length,this.eof)return;let n,g=0,r=0,o=0,I=0,c=e;if(1===i&&1===a)for(n=0;n>1,A^=A>>2,A^=A>>4,g=(1&A)<<7,t[c++]=A}else if(8===i){for(n=0;n>8&255,t[c++]=255&A}}else{const A=new Uint8Array(a+1),c=(1<>o-i)&c,o-=i,r=r<=8&&(t[B++]=r>>I-8&255,I-=8);I>0&&(t[B++]=(r<<8-I)+(g&(1<<8-I)-1))}this.bufferLength+=A}readBlockPng(){const A=this.rowBytes,e=this.pixBytes,t=this.str.getByte(),i=this.str.getBytes(A);if(this.eof=!i.length,this.eof)return;const a=this.bufferLength,s=this.ensureBuffer(a+A);let n=s.subarray(a-A,a);0===n.length&&(n=new Uint8Array(A));let g,r,o,I=a;switch(t){case 0:for(g=0;g>1)+i[g];for(;g>1)+i[g]&255,I++;break;case 4:for(g=0;g0){const A=this.str.getBytes(i);e.set(A,t),t+=i}}else{i=257-i;const a=A[1];e=this.ensureBuffer(t+i+1);for(let A=0;A>")&&this.buf1!==sA;){if(!(this.buf1 instanceof oA)){S("Malformed dictionary: key must be a name object"),this.shift();continue}const e=this.buf1.name;if(this.shift(),this.buf1===sA)break;i.set(e,this.getObj(A))}if(this.buf1===sA){if(this.recoveryMode)return i;throw new wA("End of file inside dictionary.")}return EA(this.buf2,"stream")?this.allowStreams?this.makeStream(i,A):i:(this.shift(),i);default:return e}if(Number.isInteger(e)){if(Number.isInteger(this.buf1)&&EA(this.buf2,"R")){const A=BA.get(e,this.buf1);return this.shift(),this.shift(),A}return e}return"string"==typeof e&&A?A.decryptString(e):e}findDefaultInlineStreamEnd(A){const{knownCommands:e}=this.lexer,t=A.pos;let i,a,s=0;for(;-1!==(i=A.getByte());)if(0===s)s=69===i?1:0;else if(1===s)s=73===i?2:0;else if(32===i||10===i||13===i){a=A.pos;const t=A.peekBytes(15),n=t.length;if(0===n)break;for(let A=0;A127)){s=0;break}if(2!==s)continue;if(!e){R("findDefaultInlineStreamEnd - `lexer.knownCommands` is undefined.");continue}const g=new si(new ae(t.slice()),e);g._hexStringWarn=()=>{};let r=0;for(;;){const A=g.getObj();if(A===sA){s=0;break}if(A instanceof IA){const t=e[A.cmd];if(!t){s=0;break}if(t.variableArgs?r<=t.numArgs:r===t.numArgs)break;r=0}else r++}if(2===s)break}else s=0;-1===i&&(R("findDefaultInlineStreamEnd: Reached the end of the stream without finding a valid EI marker"),a&&(R('... trying to recover by using the last "EI" occurrence.'),A.skip(-(A.pos-a))));let n=4;return A.skip(-n),i=A.peekByte(),A.skip(n),MA(i)||n--,A.pos-n-t}findDCTDecodeInlineStreamEnd(A){const e=A.pos;let t,i,a=!1;for(;-1!==(t=A.getByte());)if(255===t){switch(A.getByte()){case 0:break;case 255:A.skip(-1);break;case 217:a=!0;break;case 192:case 193:case 194:case 195:case 197:case 198:case 199:case 201:case 202:case 203:case 205:case 206:case 207:case 196:case 204:case 218:case 219:case 220:case 221:case 222:case 223:case 224:case 225:case 226:case 227:case 228:case 229:case 230:case 231:case 232:case 233:case 234:case 235:case 236:case 237:case 238:case 239:case 254:i=A.getUint16(),i>2?A.skip(i-2):A.skip(-2)}if(a)break}const s=A.pos-e;return-1===t?(R("Inline DCTDecode image stream: EOI marker not found, searching for /EI/ instead."),A.skip(-s),this.findDefaultInlineStreamEnd(A)):(this.inlineStreamSkipEI(A),s)}findASCII85DecodeInlineStreamEnd(A){const e=A.pos;let t;for(;-1!==(t=A.getByte());)if(126===t){const e=A.pos;for(t=A.peekByte();MA(t);)A.skip(),t=A.peekByte();if(62===t){A.skip();break}if(A.pos>e){const e=A.peekBytes(2);if(69===e[0]&&73===e[1])break}}const i=A.pos-e;return-1===t?(R("Inline ASCII85Decode image stream: EOD marker not found, searching for /EI/ instead."),A.skip(-i),this.findDefaultInlineStreamEnd(A)):(this.inlineStreamSkipEI(A),i)}findASCIIHexDecodeInlineStreamEnd(A){const e=A.pos;let t;for(;-1!==(t=A.getByte())&&62!==t;);const i=A.pos-e;return-1===t?(R("Inline ASCIIHexDecode image stream: EOD marker not found, searching for /EI/ instead."),A.skip(-i),this.findDefaultInlineStreamEnd(A)):(this.inlineStreamSkipEI(A),i)}inlineStreamSkipEI(A){let e,t=0;for(;-1!==(e=A.getByte());)if(0===t)t=69===e?1:0;else if(1===t)t=73===e?2:0;else if(2===t)break}makeInlineImage(A){const e=this.lexer,t=e.stream,i=Object.create(null);let a;for(;!EA(this.buf1,"ID")&&this.buf1!==sA;){if(!(this.buf1 instanceof oA))throw new K("Dictionary key must be a name object");const e=this.buf1.name;if(this.shift(),this.buf1===sA)break;i[e]=this.getObj(A)}-1!==e.beginInlineImagePos&&(a=t.pos-e.beginInlineImagePos);const s=this.xref.fetchIfRef(i.F||i.Filter);let n;if(s instanceof oA)n=s.name;else if(Array.isArray(s)){const A=this.xref.fetchIfRef(s[0]);A instanceof oA&&(n=A.name)}const g=t.pos;let r,o;switch(n){case"DCT":case"DCTDecode":r=this.findDCTDecodeInlineStreamEnd(t);break;case"A85":case"ASCII85Decode":r=this.findASCII85DecodeInlineStreamEnd(t);break;case"AHx":case"ASCIIHexDecode":r=this.findASCIIHexDecodeInlineStreamEnd(t);break;default:r=this.findDefaultInlineStreamEnd(t)}if(r<1e3&&a>0){const A=t.pos;t.pos=e.beginInlineImagePos,o=function(A){const e=[],t=A.length;let i=0;for(;i=a){let a=!1;for(const A of s){const e=A.length;let s=0;for(;s=n){a=!0;break}if(s>=e){MA(g[o+t+s])&&(S(`Found "${T([...i,...A])}" when searching for endstream command.`),a=!0);break}}if(a)return e.pos+=o,e.pos-A}o++}e.pos+=r}return-1}makeStream(A,e){const t=this.lexer;let i=t.stream;t.skipToNextLine();const a=i.pos-1;let s=A.get("Length");if(Number.isInteger(s)||(S(`Bad length "${s&&s.toString()}" in stream.`),s=0),i.pos=a+s,t.nextChar(),this.tryShift()&&EA(this.buf2,"endstream"))this.shift();else{if(s=this.#w(a),s<0)throw new K("Missing endstream command.");t.nextChar(),this.shift(),this.shift()}return this.shift(),i=i.makeSubStream(a,s,A),e&&(i=e.createStream(i,s)),i=this.filter(i,A,s),i.dict=A,i}filter(A,e,t){let i=e.get("F","Filter"),a=e.get("DP","DecodeParms");if(i instanceof oA)return Array.isArray(a)&&R("/DecodeParms should not be an Array, when /Filter is a Name."),this.makeFilter(A,i.name,t,a);let s=t;if(Array.isArray(i)){const e=i,t=a;for(let n=0,g=e.length;n=48&&A<=57?15&A:A>=65&&A<=70||A>=97&&A<=102?9+(15&A):-1}class si{constructor(A,e=null){this.stream=A,this.nextChar(),this.strBuf=[],this.knownCommands=e,this._hexStringNumWarn=0,this.beginInlineImagePos=-1}nextChar(){return this.currentChar=this.stream.getByte()}peekChar(){return this.stream.peekByte()}getNumber(){let A=this.currentChar,e=!1,t=0,i=1;if(45===A?(i=-1,A=this.nextChar(),45===A&&(A=this.nextChar())):43===A&&(A=this.nextChar()),10===A||13===A)do{A=this.nextChar()}while(10===A||13===A);if(46===A&&(t=10,A=this.nextChar()),A<48||A>57){const e=`Invalid number: ${String.fromCharCode(A)} (charCode ${A})`;if(MA(A)||-1===A)return S(`Lexer.getNumber - "${e}".`),0;throw new K(e)}let a=A-48,s=0,n=1;for(;(A=this.nextChar())>=0;)if(A>=48&&A<=57){const i=A-48;e?s=10*s+i:(0!==t&&(t*=10),a=10*a+i)}else if(46===A){if(0!==t)break;t=1}else if(45===A)R("Badly formatted number: minus sign in the middle");else{if(69!==A&&101!==A)break;if(A=this.peekChar(),43===A||45===A)n=45===A?-1:1,this.nextChar();else if(A<48||A>57)break;e=!0}return 0!==t&&(a/=t),e&&(a*=10**(n*s)),i*a}getString(){let A=1,e=!1;const t=this.strBuf;t.length=0;let i=this.nextChar();for(;;){let a=!1;switch(0|i){case-1:R("Unterminated string"),e=!0;break;case 40:++A,t.push("(");break;case 41:0==--A?(this.nextChar(),e=!0):t.push(")");break;case 92:switch(i=this.nextChar(),i){case-1:R("Unterminated string"),e=!0;break;case 110:t.push("\n");break;case 114:t.push("\r");break;case 116:t.push("\t");break;case 98:t.push("\b");break;case 102:t.push("\f");break;case 92:case 40:case 41:t.push(String.fromCharCode(i));break;case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:let A=15&i;i=this.nextChar(),a=!0,i>=48&&i<=55&&(A=(A<<3)+(15&i),i=this.nextChar(),i>=48&&i<=55&&(a=!1,A=(A<<3)+(15&i))),t.push(String.fromCharCode(A));break;case 13:10===this.peekChar()&&this.nextChar();break;case 10:break;default:t.push(String.fromCharCode(i))}break;default:t.push(String.fromCharCode(i))}if(e)break;a||(i=this.nextChar())}return t.join("")}getName(){let A,e;const t=this.strBuf;for(t.length=0;(A=this.nextChar())>=0&&!ii[A];)if(35===A){if(A=this.nextChar(),ii[A]){R("Lexer_getName: NUMBER SIGN (#) should be followed by a hexadecimal number."),t.push("#");break}const i=ai(A);if(-1!==i){e=A,A=this.nextChar();const a=ai(A);if(-1===a){if(R(`Lexer_getName: Illegal digit (${String.fromCharCode(A)}) in hexadecimal number.`),t.push("#",String.fromCharCode(e)),ii[A])break;t.push(String.fromCharCode(A));continue}t.push(String.fromCharCode(i<<4|a))}else t.push("#",String.fromCharCode(A))}else t.push(String.fromCharCode(A));return t.length>127&&R(`Name token is longer than allowed by the spec: ${t.length}`),oA.get(t.join(""))}_hexStringWarn(A){5!=this._hexStringNumWarn++?this._hexStringNumWarn>5||R(`getHexString - ignoring invalid character: ${A}`):R("getHexString - ignoring additional invalid characters.")}getHexString(){const A=this.strBuf;A.length=0;let e=this.currentChar,t=-1,i=-1;for(this._hexStringNumWarn=0;;){if(e<0){R("Unterminated hex string");break}if(62===e){this.nextChar();break}1!==ii[e]?(i=ai(e),-1===i?this._hexStringWarn(e):-1===t?t=i:(A.push(String.fromCharCode(t<<4|i)),t=-1),e=this.nextChar()):e=this.nextChar()}return-1!==t&&A.push(String.fromCharCode(t<<4)),A.join("")}getObj(){let A=!1,e=this.currentChar;for(;;){if(e<0)return sA;if(A)10!==e&&13!==e||(A=!1);else if(37===e)A=!0;else if(1!==ii[e])break;e=this.nextChar()}switch(0|e){case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:case 43:case 45:case 46:return this.getNumber();case 40:return this.getString();case 47:return this.getName();case 91:return this.nextChar(),IA.get("[");case 93:return this.nextChar(),IA.get("]");case 60:return e=this.nextChar(),60===e?(this.nextChar(),IA.get("<<")):this.getHexString();case 62:return e=this.nextChar(),62===e?(this.nextChar(),IA.get(">>")):IA.get(">");case 123:return this.nextChar(),IA.get("{");case 125:return this.nextChar(),IA.get("}");case 41:throw this.nextChar(),new K(`Illegal character: ${e}`)}let t=String.fromCharCode(e);if(e<32||e>127){const A=this.peekChar();if(A>=32&&A<=127)return this.nextChar(),IA.get(t)}const i=this.knownCommands;let a=void 0!==i?.[t];for(;(e=this.nextChar())>=0&&!ii[e];){const A=t+String.fromCharCode(e);if(a&&void 0===i[A])break;if(128===t.length)throw new K(`Command token too long: ${t.length}`);t=A,a=void 0!==i?.[t]}return"true"===t||"false"!==t&&("null"===t?null:("BI"===t&&(this.beginInlineImagePos=this.stream.pos),IA.get(t)))}skipToNextLine(){let A=this.currentChar;for(;A>=0;){if(13===A){A=this.nextChar(),10===A&&this.nextChar();break}if(10===A){this.nextChar();break}A=this.nextChar()}}}class ni{static create(A){function e(A,e,t=!1){const i=A.get(e);if(Number.isInteger(i)&&(t?i>=0:i>0))return i;throw new Error(`The "${e}" parameter in the linearization dictionary is invalid.`)}const t=new ti({lexer:new si(A),xref:null}),i=t.getObj(),a=t.getObj(),s=t.getObj(),n=t.getObj();let g,r;if(!(Number.isInteger(i)&&Number.isInteger(a)&&EA(s,"obj")&&n instanceof CA&&"number"==typeof(g=n.get("Linearized"))&&g>0))return null;if((r=e(n,"L"))!==A.length)throw new Error('The "L" parameter in the linearization dictionary does not equal the stream length.');return{length:r,hints:function(A){const e=A.get("H");let t;if(Array.isArray(e)&&(2===(t=e.length)||4===t)){for(let A=0;A0))throw new Error(`Hint (${A}) in the linearization dictionary is invalid.`)}return e}throw new Error("Hint array in the linearization dictionary is invalid.")}(n),objectNumberFirst:e(n,"O"),endFirst:e(n,"E"),numPages:e(n,"N"),mainXRefEntriesOffset:e(n,"T"),pageFirst:n.has("P")?e(n,"P",!0):0}}}const gi=["Adobe-GB1-UCS2","Adobe-CNS1-UCS2","Adobe-Japan1-UCS2","Adobe-Korea1-UCS2","78-EUC-H","78-EUC-V","78-H","78-RKSJ-H","78-RKSJ-V","78-V","78ms-RKSJ-H","78ms-RKSJ-V","83pv-RKSJ-H","90ms-RKSJ-H","90ms-RKSJ-V","90msp-RKSJ-H","90msp-RKSJ-V","90pv-RKSJ-H","90pv-RKSJ-V","Add-H","Add-RKSJ-H","Add-RKSJ-V","Add-V","Adobe-CNS1-0","Adobe-CNS1-1","Adobe-CNS1-2","Adobe-CNS1-3","Adobe-CNS1-4","Adobe-CNS1-5","Adobe-CNS1-6","Adobe-GB1-0","Adobe-GB1-1","Adobe-GB1-2","Adobe-GB1-3","Adobe-GB1-4","Adobe-GB1-5","Adobe-Japan1-0","Adobe-Japan1-1","Adobe-Japan1-2","Adobe-Japan1-3","Adobe-Japan1-4","Adobe-Japan1-5","Adobe-Japan1-6","Adobe-Korea1-0","Adobe-Korea1-1","Adobe-Korea1-2","B5-H","B5-V","B5pc-H","B5pc-V","CNS-EUC-H","CNS-EUC-V","CNS1-H","CNS1-V","CNS2-H","CNS2-V","ETHK-B5-H","ETHK-B5-V","ETen-B5-H","ETen-B5-V","ETenms-B5-H","ETenms-B5-V","EUC-H","EUC-V","Ext-H","Ext-RKSJ-H","Ext-RKSJ-V","Ext-V","GB-EUC-H","GB-EUC-V","GB-H","GB-V","GBK-EUC-H","GBK-EUC-V","GBK2K-H","GBK2K-V","GBKp-EUC-H","GBKp-EUC-V","GBT-EUC-H","GBT-EUC-V","GBT-H","GBT-V","GBTpc-EUC-H","GBTpc-EUC-V","GBpc-EUC-H","GBpc-EUC-V","H","HKdla-B5-H","HKdla-B5-V","HKdlb-B5-H","HKdlb-B5-V","HKgccs-B5-H","HKgccs-B5-V","HKm314-B5-H","HKm314-B5-V","HKm471-B5-H","HKm471-B5-V","HKscs-B5-H","HKscs-B5-V","Hankaku","Hiragana","KSC-EUC-H","KSC-EUC-V","KSC-H","KSC-Johab-H","KSC-Johab-V","KSC-V","KSCms-UHC-H","KSCms-UHC-HW-H","KSCms-UHC-HW-V","KSCms-UHC-V","KSCpc-EUC-H","KSCpc-EUC-V","Katakana","NWP-H","NWP-V","RKSJ-H","RKSJ-V","Roman","UniCNS-UCS2-H","UniCNS-UCS2-V","UniCNS-UTF16-H","UniCNS-UTF16-V","UniCNS-UTF32-H","UniCNS-UTF32-V","UniCNS-UTF8-H","UniCNS-UTF8-V","UniGB-UCS2-H","UniGB-UCS2-V","UniGB-UTF16-H","UniGB-UTF16-V","UniGB-UTF32-H","UniGB-UTF32-V","UniGB-UTF8-H","UniGB-UTF8-V","UniJIS-UCS2-H","UniJIS-UCS2-HW-H","UniJIS-UCS2-HW-V","UniJIS-UCS2-V","UniJIS-UTF16-H","UniJIS-UTF16-V","UniJIS-UTF32-H","UniJIS-UTF32-V","UniJIS-UTF8-H","UniJIS-UTF8-V","UniJIS2004-UTF16-H","UniJIS2004-UTF16-V","UniJIS2004-UTF32-H","UniJIS2004-UTF32-V","UniJIS2004-UTF8-H","UniJIS2004-UTF8-V","UniJISPro-UCS2-HW-V","UniJISPro-UCS2-V","UniJISPro-UTF8-V","UniJISX0213-UTF32-H","UniJISX0213-UTF32-V","UniJISX02132004-UTF32-H","UniJISX02132004-UTF32-V","UniKS-UCS2-H","UniKS-UCS2-V","UniKS-UTF16-H","UniKS-UTF16-V","UniKS-UTF32-H","UniKS-UTF32-V","UniKS-UTF8-H","UniKS-UTF8-V","V","WP-Symbol"],ri=2**24-1;class oi{constructor(A=!1){this.codespaceRanges=[[],[],[],[]],this.numCodespaceRanges=0,this._map=[],this.name="",this.vertical=!1,this.useCMap=null,this.builtInCMap=A}addCodespaceRange(A,e,t){this.codespaceRanges[A-1].push(e,t),this.numCodespaceRanges++}mapCidRange(A,e,t){if(e-A>ri)throw new Error("mapCidRange - ignoring data above MAX_MAP_RANGE.");for(;A<=e;)this._map[A++]=t++}mapBfRange(A,e,t){if(e-A>ri)throw new Error("mapBfRange - ignoring data above MAX_MAP_RANGE.");const i=t.length-1;for(;A<=e;){this._map[A++]=t;const e=t.charCodeAt(i)+1;t=e>255?t.substring(0,i-1)+String.fromCharCode(t.charCodeAt(i-1)+1)+"\0":t.substring(0,i)+String.fromCharCode(e)}}mapBfRangeToArray(A,e,t){if(e-A>ri)throw new Error("mapBfRangeToArray - ignoring data above MAX_MAP_RANGE.");const i=t.length;let a=0;for(;A<=e&&a>>0;const n=a[s];for(let A=0,e=n.length;A=e&&i<=a)return t.charcode=i,void(t.length=s+1)}}t.charcode=0,t.length=1}getCharCodeLength(A){const e=this.codespaceRanges;for(let t=0,i=e.length;t=a&&A<=s)return t+1}}return 1}get length(){return this._map.length}get isIdentityCMap(){if("Identity-H"!==this.name&&"Identity-V"!==this.name)return!1;if(65536!==this._map.length)return!1;for(let A=0;A<65536;A++)if(this._map[A]!==A)return!1;return!0}}class Ii extends oi{constructor(A,e){super(),this.vertical=A,this.addCodespaceRange(e,0,65535)}mapCidRange(A,e,t){G("should not call mapCidRange")}mapBfRange(A,e,t){G("should not call mapBfRange")}mapBfRangeToArray(A,e,t){G("should not call mapBfRangeToArray")}mapOne(A,e){G("should not call mapCidOne")}lookup(A){return Number.isInteger(A)&&A<=65535?A:void 0}contains(A){return Number.isInteger(A)&&A<=65535}forEach(A){for(let e=0;e<=65535;e++)A(e,e)}charCodeOf(A){return Number.isInteger(A)&&A<=65535?A:-1}getMap(){const A=new Array(65536);for(let e=0;e<=65535;e++)A[e]=e;return A}get length(){return 65536}get isIdentityCMap(){G("should not access .isIdentityCMap")}}function ci(A){let e=0;for(let t=0;t>>0}function Ci(A){if("string"!=typeof A)throw new K("Malformed CMap: expected string.")}function Bi(A){if(!Number.isInteger(A))throw new K("Malformed CMap: expected int.")}function hi(A,e){for(;;){let t=e.getObj();if(t===sA)break;if(EA(t,"endbfchar"))return;Ci(t);const i=ci(t);t=e.getObj(),Ci(t);const a=t;A.mapOne(i,a)}}function Qi(A,e){for(;;){let t=e.getObj();if(t===sA)break;if(EA(t,"endbfrange"))return;Ci(t);const i=ci(t);t=e.getObj(),Ci(t);const a=ci(t);if(t=e.getObj(),Number.isInteger(t)||"string"==typeof t){const e=Number.isInteger(t)?String.fromCharCode(t):t;A.mapBfRange(i,a,e)}else{if(!EA(t,"["))break;{t=e.getObj();const s=[];for(;!EA(t,"]")&&t!==sA;)s.push(t),t=e.getObj();A.mapBfRangeToArray(i,a,s)}}}throw new K("Invalid bf range.")}function li(A,e){for(;;){let t=e.getObj();if(t===sA)break;if(EA(t,"endcidchar"))return;Ci(t);const i=ci(t);t=e.getObj(),Bi(t);const a=t;A.mapOne(i,a)}}function Ei(A,e){for(;;){let t=e.getObj();if(t===sA)break;if(EA(t,"endcidrange"))return;Ci(t);const i=ci(t);t=e.getObj(),Ci(t);const a=ci(t);t=e.getObj(),Bi(t);const s=t;A.mapCidRange(i,a,s)}}function ui(A,e){for(;;){let t=e.getObj();if(t===sA)break;if(EA(t,"endcodespacerange"))return;if("string"!=typeof t)break;const i=ci(t);if(t=e.getObj(),"string"!=typeof t)break;const a=ci(t);A.addCodespaceRange(t.length,i,a)}throw new K("Invalid codespace range.")}function di(A,e){const t=e.getObj();Number.isInteger(t)&&(A.vertical=!!t)}function fi(A,e){const t=e.getObj();t instanceof oA&&(A.name=t.name)}async function pi(A,e,t,i){let a,s;A:for(;;)try{const t=e.getObj();if(t===sA)break;if(t instanceof oA)"WMode"===t.name?di(A,e):"CMapName"===t.name&&fi(A,e),a=t;else if(t instanceof IA)switch(t.cmd){case"endcmap":break A;case"usecmap":a instanceof oA&&(s=a.name);break;case"begincodespacerange":ui(A,e);break;case"beginbfchar":hi(A,e);break;case"begincidchar":li(A,e);break;case"beginbfrange":Qi(A,e);break;case"begincidrange":Ei(A,e)}}catch(A){if(A instanceof yA)throw A;R("Invalid cMap data: "+A);continue}return!i&&s&&(i=s),i?mi(A,t,i):A}async function mi(A,e,t){if(A.useCMap=await yi(t,e),0===A.numCodespaceRanges){const e=A.useCMap.codespaceRanges;for(let t=0;tmi(a,e,A)));if(0===i){const A=new si(new ae(t));return pi(a,A,e,null)}throw new Error(`Invalid CMap "compressionType" value: ${i}`)}class wi{static async create({encoding:A,fetchBuiltInCMap:e,useCMap:t}){if(A instanceof oA)return yi(A.name,e);if(A instanceof fA){const i=await pi(new oi,new si(A),e,t);return i.isIdentityCMap?yi(i.name,e):i}throw new Error("Encoding required.")}}const Di=[".notdef","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quoteright","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","quoteleft","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","exclamdown","cent","sterling","fraction","yen","florin","section","currency","quotesingle","quotedblleft","guillemotleft","guilsinglleft","guilsinglright","fi","fl","endash","dagger","daggerdbl","periodcentered","paragraph","bullet","quotesinglbase","quotedblbase","quotedblright","guillemotright","ellipsis","perthousand","questiondown","grave","acute","circumflex","tilde","macron","breve","dotaccent","dieresis","ring","cedilla","hungarumlaut","ogonek","caron","emdash","AE","ordfeminine","Lslash","Oslash","OE","ordmasculine","ae","dotlessi","lslash","oslash","oe","germandbls","onesuperior","logicalnot","mu","trademark","Eth","onehalf","plusminus","Thorn","onequarter","divide","brokenbar","degree","thorn","threequarters","twosuperior","registered","minus","eth","multiply","threesuperior","copyright","Aacute","Acircumflex","Adieresis","Agrave","Aring","Atilde","Ccedilla","Eacute","Ecircumflex","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Ntilde","Oacute","Ocircumflex","Odieresis","Ograve","Otilde","Scaron","Uacute","Ucircumflex","Udieresis","Ugrave","Yacute","Ydieresis","Zcaron","aacute","acircumflex","adieresis","agrave","aring","atilde","ccedilla","eacute","ecircumflex","edieresis","egrave","iacute","icircumflex","idieresis","igrave","ntilde","oacute","ocircumflex","odieresis","ograve","otilde","scaron","uacute","ucircumflex","udieresis","ugrave","yacute","ydieresis","zcaron"],bi=[".notdef","space","exclamsmall","Hungarumlautsmall","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","commasuperior","threequartersemdash","periodsuperior","questionsmall","asuperior","bsuperior","centsuperior","dsuperior","esuperior","isuperior","lsuperior","msuperior","nsuperior","osuperior","rsuperior","ssuperior","tsuperior","ff","fi","fl","ffi","ffl","parenleftinferior","parenrightinferior","Circumflexsmall","hyphensuperior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","exclamdownsmall","centoldstyle","Lslashsmall","Scaronsmall","Zcaronsmall","Dieresissmall","Brevesmall","Caronsmall","Dotaccentsmall","Macronsmall","figuredash","hypheninferior","Ogoneksmall","Ringsmall","Cedillasmall","onequarter","onehalf","threequarters","questiondownsmall","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","zerosuperior","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior","Agravesmall","Aacutesmall","Acircumflexsmall","Atildesmall","Adieresissmall","Aringsmall","AEsmall","Ccedillasmall","Egravesmall","Eacutesmall","Ecircumflexsmall","Edieresissmall","Igravesmall","Iacutesmall","Icircumflexsmall","Idieresissmall","Ethsmall","Ntildesmall","Ogravesmall","Oacutesmall","Ocircumflexsmall","Otildesmall","Odieresissmall","OEsmall","Oslashsmall","Ugravesmall","Uacutesmall","Ucircumflexsmall","Udieresissmall","Yacutesmall","Thornsmall","Ydieresissmall"],ki=[".notdef","space","dollaroldstyle","dollarsuperior","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","commasuperior","threequartersemdash","periodsuperior","asuperior","bsuperior","centsuperior","dsuperior","esuperior","isuperior","lsuperior","msuperior","nsuperior","osuperior","rsuperior","ssuperior","tsuperior","ff","fi","fl","ffi","ffl","parenleftinferior","parenrightinferior","hyphensuperior","colonmonetary","onefitted","rupiah","centoldstyle","figuredash","hypheninferior","onequarter","onehalf","threequarters","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","zerosuperior","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior"],Fi=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclamsmall","Hungarumlautsmall","","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","commasuperior","threequartersemdash","periodsuperior","questionsmall","","asuperior","bsuperior","centsuperior","dsuperior","esuperior","","","","isuperior","","","lsuperior","msuperior","nsuperior","osuperior","","","rsuperior","ssuperior","tsuperior","","ff","fi","fl","ffi","ffl","parenleftinferior","","parenrightinferior","Circumflexsmall","hyphensuperior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","exclamdownsmall","centoldstyle","Lslashsmall","","","Scaronsmall","Zcaronsmall","Dieresissmall","Brevesmall","Caronsmall","","Dotaccentsmall","","","Macronsmall","","","figuredash","hypheninferior","","","Ogoneksmall","Ringsmall","Cedillasmall","","","","onequarter","onehalf","threequarters","questiondownsmall","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","","","zerosuperior","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior","Agravesmall","Aacutesmall","Acircumflexsmall","Atildesmall","Adieresissmall","Aringsmall","AEsmall","Ccedillasmall","Egravesmall","Eacutesmall","Ecircumflexsmall","Edieresissmall","Igravesmall","Iacutesmall","Icircumflexsmall","Idieresissmall","Ethsmall","Ntildesmall","Ogravesmall","Oacutesmall","Ocircumflexsmall","Otildesmall","Odieresissmall","OEsmall","Oslashsmall","Ugravesmall","Uacutesmall","Ucircumflexsmall","Udieresissmall","Yacutesmall","Thornsmall","Ydieresissmall"],Si=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclamsmall","Hungarumlautsmall","centoldstyle","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","","threequartersemdash","","questionsmall","","","","","Ethsmall","","","onequarter","onehalf","threequarters","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","","","","","","","ff","fi","fl","ffi","ffl","parenleftinferior","","parenrightinferior","Circumflexsmall","hypheninferior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","","","asuperior","centsuperior","","","","","Aacutesmall","Agravesmall","Acircumflexsmall","Adieresissmall","Atildesmall","Aringsmall","Ccedillasmall","Eacutesmall","Egravesmall","Ecircumflexsmall","Edieresissmall","Iacutesmall","Igravesmall","Icircumflexsmall","Idieresissmall","Ntildesmall","Oacutesmall","Ogravesmall","Ocircumflexsmall","Odieresissmall","Otildesmall","Uacutesmall","Ugravesmall","Ucircumflexsmall","Udieresissmall","","eightsuperior","fourinferior","threeinferior","sixinferior","eightinferior","seveninferior","Scaronsmall","","centinferior","twoinferior","","Dieresissmall","","Caronsmall","osuperior","fiveinferior","","commainferior","periodinferior","Yacutesmall","","dollarinferior","","","Thornsmall","","nineinferior","zeroinferior","Zcaronsmall","AEsmall","Oslashsmall","questiondownsmall","oneinferior","Lslashsmall","","","","","","","Cedillasmall","","","","","","OEsmall","figuredash","hyphensuperior","","","","","exclamdownsmall","","Ydieresissmall","","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","ninesuperior","zerosuperior","","esuperior","rsuperior","tsuperior","","","isuperior","ssuperior","dsuperior","","","","","","lsuperior","Ogoneksmall","Brevesmall","Macronsmall","bsuperior","nsuperior","msuperior","commasuperior","periodsuperior","Dotaccentsmall","Ringsmall","","","",""],Ri=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quotesingle","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","grave","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","","Adieresis","Aring","Ccedilla","Eacute","Ntilde","Odieresis","Udieresis","aacute","agrave","acircumflex","adieresis","atilde","aring","ccedilla","eacute","egrave","ecircumflex","edieresis","iacute","igrave","icircumflex","idieresis","ntilde","oacute","ograve","ocircumflex","odieresis","otilde","uacute","ugrave","ucircumflex","udieresis","dagger","degree","cent","sterling","section","bullet","paragraph","germandbls","registered","copyright","trademark","acute","dieresis","notequal","AE","Oslash","infinity","plusminus","lessequal","greaterequal","yen","mu","partialdiff","summation","product","pi","integral","ordfeminine","ordmasculine","Omega","ae","oslash","questiondown","exclamdown","logicalnot","radical","florin","approxequal","Delta","guillemotleft","guillemotright","ellipsis","space","Agrave","Atilde","Otilde","OE","oe","endash","emdash","quotedblleft","quotedblright","quoteleft","quoteright","divide","lozenge","ydieresis","Ydieresis","fraction","currency","guilsinglleft","guilsinglright","fi","fl","daggerdbl","periodcentered","quotesinglbase","quotedblbase","perthousand","Acircumflex","Ecircumflex","Aacute","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Oacute","Ocircumflex","apple","Ograve","Uacute","Ucircumflex","Ugrave","dotlessi","circumflex","tilde","macron","breve","dotaccent","ring","cedilla","hungarumlaut","ogonek","caron"],Gi=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quoteright","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","quoteleft","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","exclamdown","cent","sterling","fraction","yen","florin","section","currency","quotesingle","quotedblleft","guillemotleft","guilsinglleft","guilsinglright","fi","fl","","endash","dagger","daggerdbl","periodcentered","","paragraph","bullet","quotesinglbase","quotedblbase","quotedblright","guillemotright","ellipsis","perthousand","","questiondown","","grave","acute","circumflex","tilde","macron","breve","dotaccent","dieresis","","ring","cedilla","","hungarumlaut","ogonek","caron","emdash","","","","","","","","","","","","","","","","","AE","","ordfeminine","","","","","Lslash","Oslash","OE","ordmasculine","","","","","","ae","","","","dotlessi","","","lslash","oslash","oe","germandbls","","","",""],Ni=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quotesingle","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","grave","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","bullet","Euro","bullet","quotesinglbase","florin","quotedblbase","ellipsis","dagger","daggerdbl","circumflex","perthousand","Scaron","guilsinglleft","OE","bullet","Zcaron","bullet","bullet","quoteleft","quoteright","quotedblleft","quotedblright","bullet","endash","emdash","tilde","trademark","scaron","guilsinglright","oe","bullet","zcaron","Ydieresis","space","exclamdown","cent","sterling","currency","yen","brokenbar","section","dieresis","copyright","ordfeminine","guillemotleft","logicalnot","hyphen","registered","macron","degree","plusminus","twosuperior","threesuperior","acute","mu","paragraph","periodcentered","cedilla","onesuperior","ordmasculine","guillemotright","onequarter","onehalf","threequarters","questiondown","Agrave","Aacute","Acircumflex","Atilde","Adieresis","Aring","AE","Ccedilla","Egrave","Eacute","Ecircumflex","Edieresis","Igrave","Iacute","Icircumflex","Idieresis","Eth","Ntilde","Ograve","Oacute","Ocircumflex","Otilde","Odieresis","multiply","Oslash","Ugrave","Uacute","Ucircumflex","Udieresis","Yacute","Thorn","germandbls","agrave","aacute","acircumflex","atilde","adieresis","aring","ae","ccedilla","egrave","eacute","ecircumflex","edieresis","igrave","iacute","icircumflex","idieresis","eth","ntilde","ograve","oacute","ocircumflex","otilde","odieresis","divide","oslash","ugrave","uacute","ucircumflex","udieresis","yacute","thorn","ydieresis"],xi=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","universal","numbersign","existential","percent","ampersand","suchthat","parenleft","parenright","asteriskmath","plus","comma","minus","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","congruent","Alpha","Beta","Chi","Delta","Epsilon","Phi","Gamma","Eta","Iota","theta1","Kappa","Lambda","Mu","Nu","Omicron","Pi","Theta","Rho","Sigma","Tau","Upsilon","sigma1","Omega","Xi","Psi","Zeta","bracketleft","therefore","bracketright","perpendicular","underscore","radicalex","alpha","beta","chi","delta","epsilon","phi","gamma","eta","iota","phi1","kappa","lambda","mu","nu","omicron","pi","theta","rho","sigma","tau","upsilon","omega1","omega","xi","psi","zeta","braceleft","bar","braceright","similar","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","Euro","Upsilon1","minute","lessequal","fraction","infinity","florin","club","diamond","heart","spade","arrowboth","arrowleft","arrowup","arrowright","arrowdown","degree","plusminus","second","greaterequal","multiply","proportional","partialdiff","bullet","divide","notequal","equivalence","approxequal","ellipsis","arrowvertex","arrowhorizex","carriagereturn","aleph","Ifraktur","Rfraktur","weierstrass","circlemultiply","circleplus","emptyset","intersection","union","propersuperset","reflexsuperset","notsubset","propersubset","reflexsubset","element","notelement","angle","gradient","registerserif","copyrightserif","trademarkserif","product","radical","dotmath","logicalnot","logicaland","logicalor","arrowdblboth","arrowdblleft","arrowdblup","arrowdblright","arrowdbldown","lozenge","angleleft","registersans","copyrightsans","trademarksans","summation","parenlefttp","parenleftex","parenleftbt","bracketlefttp","bracketleftex","bracketleftbt","bracelefttp","braceleftmid","braceleftbt","braceex","","angleright","integral","integraltp","integralex","integralbt","parenrighttp","parenrightex","parenrightbt","bracketrighttp","bracketrightex","bracketrightbt","bracerighttp","bracerightmid","bracerightbt",""],Ui=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","a1","a2","a202","a3","a4","a5","a119","a118","a117","a11","a12","a13","a14","a15","a16","a105","a17","a18","a19","a20","a21","a22","a23","a24","a25","a26","a27","a28","a6","a7","a8","a9","a10","a29","a30","a31","a32","a33","a34","a35","a36","a37","a38","a39","a40","a41","a42","a43","a44","a45","a46","a47","a48","a49","a50","a51","a52","a53","a54","a55","a56","a57","a58","a59","a60","a61","a62","a63","a64","a65","a66","a67","a68","a69","a70","a71","a72","a73","a74","a203","a75","a204","a76","a77","a78","a79","a81","a82","a83","a84","a97","a98","a99","a100","","a89","a90","a93","a94","a91","a92","a205","a85","a206","a86","a87","a88","a95","a96","","","","","","","","","","","","","","","","","","","","a101","a102","a103","a104","a106","a107","a108","a112","a111","a110","a109","a120","a121","a122","a123","a124","a125","a126","a127","a128","a129","a130","a131","a132","a133","a134","a135","a136","a137","a138","a139","a140","a141","a142","a143","a144","a145","a146","a147","a148","a149","a150","a151","a152","a153","a154","a155","a156","a157","a158","a159","a160","a161","a163","a164","a196","a165","a192","a166","a167","a168","a169","a170","a171","a172","a173","a162","a174","a175","a176","a177","a178","a179","a193","a180","a199","a181","a200","a182","","a201","a183","a184","a197","a185","a194","a198","a186","a195","a187","a188","a189","a190","a191",""];function Mi(A){switch(A){case"WinAnsiEncoding":return Ni;case"StandardEncoding":return Gi;case"MacRomanEncoding":return Ri;case"SymbolSetEncoding":return xi;case"ZapfDingbatsEncoding":return Ui;case"ExpertEncoding":return Fi;case"MacExpertEncoding":return Si;default:return null}}const Li=[".notdef","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quoteright","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","quoteleft","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","exclamdown","cent","sterling","fraction","yen","florin","section","currency","quotesingle","quotedblleft","guillemotleft","guilsinglleft","guilsinglright","fi","fl","endash","dagger","daggerdbl","periodcentered","paragraph","bullet","quotesinglbase","quotedblbase","quotedblright","guillemotright","ellipsis","perthousand","questiondown","grave","acute","circumflex","tilde","macron","breve","dotaccent","dieresis","ring","cedilla","hungarumlaut","ogonek","caron","emdash","AE","ordfeminine","Lslash","Oslash","OE","ordmasculine","ae","dotlessi","lslash","oslash","oe","germandbls","onesuperior","logicalnot","mu","trademark","Eth","onehalf","plusminus","Thorn","onequarter","divide","brokenbar","degree","thorn","threequarters","twosuperior","registered","minus","eth","multiply","threesuperior","copyright","Aacute","Acircumflex","Adieresis","Agrave","Aring","Atilde","Ccedilla","Eacute","Ecircumflex","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Ntilde","Oacute","Ocircumflex","Odieresis","Ograve","Otilde","Scaron","Uacute","Ucircumflex","Udieresis","Ugrave","Yacute","Ydieresis","Zcaron","aacute","acircumflex","adieresis","agrave","aring","atilde","ccedilla","eacute","ecircumflex","edieresis","egrave","iacute","icircumflex","idieresis","igrave","ntilde","oacute","ocircumflex","odieresis","ograve","otilde","scaron","uacute","ucircumflex","udieresis","ugrave","yacute","ydieresis","zcaron","exclamsmall","Hungarumlautsmall","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","commasuperior","threequartersemdash","periodsuperior","questionsmall","asuperior","bsuperior","centsuperior","dsuperior","esuperior","isuperior","lsuperior","msuperior","nsuperior","osuperior","rsuperior","ssuperior","tsuperior","ff","ffi","ffl","parenleftinferior","parenrightinferior","Circumflexsmall","hyphensuperior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","exclamdownsmall","centoldstyle","Lslashsmall","Scaronsmall","Zcaronsmall","Dieresissmall","Brevesmall","Caronsmall","Dotaccentsmall","Macronsmall","figuredash","hypheninferior","Ogoneksmall","Ringsmall","Cedillasmall","questiondownsmall","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","zerosuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior","Agravesmall","Aacutesmall","Acircumflexsmall","Atildesmall","Adieresissmall","Aringsmall","AEsmall","Ccedillasmall","Egravesmall","Eacutesmall","Ecircumflexsmall","Edieresissmall","Igravesmall","Iacutesmall","Icircumflexsmall","Idieresissmall","Ethsmall","Ntildesmall","Ogravesmall","Oacutesmall","Ocircumflexsmall","Otildesmall","Odieresissmall","OEsmall","Oslashsmall","Ugravesmall","Uacutesmall","Ucircumflexsmall","Udieresissmall","Yacutesmall","Thornsmall","Ydieresissmall","001.000","001.001","001.002","001.003","Black","Bold","Book","Light","Medium","Regular","Roman","Semibold"],Ji=[null,{id:"hstem",min:2,stackClearing:!0,stem:!0},null,{id:"vstem",min:2,stackClearing:!0,stem:!0},{id:"vmoveto",min:1,stackClearing:!0},{id:"rlineto",min:2,resetStack:!0},{id:"hlineto",min:1,resetStack:!0},{id:"vlineto",min:1,resetStack:!0},{id:"rrcurveto",min:6,resetStack:!0},null,{id:"callsubr",min:1,undefStack:!0},{id:"return",min:0,undefStack:!0},null,null,{id:"endchar",min:0,stackClearing:!0},null,null,null,{id:"hstemhm",min:2,stackClearing:!0,stem:!0},{id:"hintmask",min:0,stackClearing:!0},{id:"cntrmask",min:0,stackClearing:!0},{id:"rmoveto",min:2,stackClearing:!0},{id:"hmoveto",min:1,stackClearing:!0},{id:"vstemhm",min:2,stackClearing:!0,stem:!0},{id:"rcurveline",min:8,resetStack:!0},{id:"rlinecurve",min:8,resetStack:!0},{id:"vvcurveto",min:4,resetStack:!0},{id:"hhcurveto",min:4,resetStack:!0},null,{id:"callgsubr",min:1,undefStack:!0},{id:"vhcurveto",min:4,resetStack:!0},{id:"hvcurveto",min:4,resetStack:!0}],Hi=[null,null,null,{id:"and",min:2,stackDelta:-1},{id:"or",min:2,stackDelta:-1},{id:"not",min:1,stackDelta:0},null,null,null,{id:"abs",min:1,stackDelta:0},{id:"add",min:2,stackDelta:-1,stackFn(A,e){A[e-2]=A[e-2]+A[e-1]}},{id:"sub",min:2,stackDelta:-1,stackFn(A,e){A[e-2]=A[e-2]-A[e-1]}},{id:"div",min:2,stackDelta:-1,stackFn(A,e){A[e-2]=A[e-2]/A[e-1]}},null,{id:"neg",min:1,stackDelta:0,stackFn(A,e){A[e-1]=-A[e-1]}},{id:"eq",min:2,stackDelta:-1},null,null,{id:"drop",min:1,stackDelta:-1},null,{id:"put",min:2,stackDelta:-2},{id:"get",min:1,stackDelta:0},{id:"ifelse",min:4,stackDelta:-3},{id:"random",min:0,stackDelta:1},{id:"mul",min:2,stackDelta:-1,stackFn(A,e){A[e-2]=A[e-2]*A[e-1]}},null,{id:"sqrt",min:1,stackDelta:0},{id:"dup",min:1,stackDelta:1},{id:"exch",min:2,stackDelta:0},{id:"index",min:2,stackDelta:0},{id:"roll",min:3,stackDelta:-2},null,null,null,{id:"hflex",min:7,resetStack:!0},{id:"flex",min:13,resetStack:!0},{id:"hflex1",min:9,resetStack:!0},{id:"flex1",min:11,resetStack:!0}];class Yi{constructor(A,e,t){this.bytes=A.getBytes(),this.properties=e,this.seacAnalysisEnabled=!!t}parse(){const A=this.properties,e=new vi;this.cff=e;const t=this.parseHeader(),i=this.parseIndex(t.endPos),a=this.parseIndex(i.endPos),s=this.parseIndex(a.endPos),n=this.parseIndex(s.endPos),g=this.parseDict(a.obj.get(0)),r=this.createDict(Zi,g,e.strings);e.header=t.obj,e.names=this.parseNameIndex(i.obj),e.strings=this.parseStringIndex(s.obj),e.topDict=r,e.globalSubrIndex=n.obj,this.parsePrivateDict(e.topDict),e.isCIDFont=r.hasName("ROS");const o=r.getByName("CharStrings"),I=this.parseIndex(o).obj,c=r.getByName("FontMatrix");c&&(A.fontMatrix=c);const C=r.getByName("FontBBox");let B,h;if(C&&(A.ascent=Math.max(C[3],C[1]),A.descent=Math.min(C[1],C[3]),A.ascentScaled=!0),e.isCIDFont){const A=this.parseIndex(r.getByName("FDArray")).obj;for(let t=0,i=A.count;t=e)throw new K("Invalid CFF header");0!==t&&(S("cff data is shifted"),A=A.subarray(t),this.bytes=A);const i=A[0],a=A[1],s=A[2],n=A[3];return{obj:new Ki(i,a,s,n),endPos:s}}parseDict(A){let e=0;function t(){let t=A[e++];return 30===t?function(){let t="";const i=["0","1","2","3","4","5","6","7","8","9",".","E","E-",null,"-"],a=A.length;for(;e>4,n=15&a;if(15===s)break;if(t+=i[s],15===n)break;t+=i[n]}return parseFloat(t)}():28===t?(t=A[e++],t=(t<<24|A[e++]<<16)>>16,t):29===t?(t=A[e++],t=t<<8|A[e++],t=t<<8|A[e++],t=t<<8|A[e++],t):t>=32&&t<=246?t-139:t>=247&&t<=250?256*(t-247)+A[e++]+108:t>=251&&t<=254?-256*(t-251)-A[e++]-108:(R('CFFParser_parseDict: "'+t+'" is a reserved command.'),NaN)}let i=[];const a=[];e=0;const s=A.length;for(;e10)return!1;let a=A.stackSize;const s=A.stack;let n=e.length;for(let g=0;g>16,g+=2,a++;else if(14===r){if(a>=4&&(a-=4,this.seacAnalysisEnabled))return A.seac=s.slice(a,a+4),!1;o=Ji[r]}else if(r>=32&&r<=246)s[a]=r-139,a++;else if(r>=247&&r<=254)s[a]=r<251?(r-247<<8)+e[g]+108:-(r-251<<8)-e[g]-108,g++,a++;else if(255===r)s[a]=(e[g]<<24|e[g+1]<<16|e[g+2]<<8|e[g+3])/65536,g+=4,a++;else if(19===r||20===r){if(A.hints+=a>>1,0===A.hints){e.copyWithin(g-1,g,-1),g-=1,n-=1;continue}g+=A.hints+7>>3,a%=2,o=Ji[r]}else{if(10===r||29===r){const e=10===r?t:i;if(!e)return o=Ji[r],R("Missing subrsIndex for "+o.id),!1;let n=32768;e.count<1240?n=107:e.count<33900&&(n=1131);const g=s[--a]+n;if(g<0||g>=e.count||isNaN(g))return o=Ji[r],R("Out of bounds subrIndex for "+o.id),!1;if(A.stackSize=a,A.callDepth++,!this.parseCharString(A,e.get(g),t,i))return!1;A.callDepth--,a=A.stackSize;continue}if(11===r)return A.stackSize=a,!0;if(0===r&&g===e.length)e[g-1]=14,o=Ji[14];else{if(9===r){e.copyWithin(g-1,g,-1),g-=1,n-=1;continue}o=Ji[r]}}if(o){if(o.stem&&(A.hints+=a>>1,3===r||23===r?A.hasVStems=!0:!A.hasVStems||1!==r&&18!==r||(R("CFF stem hints are in wrong order"),e[g-1]=1===r?3:23)),"min"in o&&!A.undefStack&&a=2&&o.stem?a%=2:a>1&&R("Found too many parameters for stack-clearing command"),a>0&&(A.width=s[a-1])),"stackDelta"in o?("stackFn"in o&&o.stackFn(s,a),a+=o.stackDelta):o.stackClearing?a=0:o.resetStack?(a=0,A.undefStack=!1):o.undefStack&&(a=0,A.undefStack=!0,A.firstStackClearing=!1)}}return n=a.length&&(R("Invalid fd index for glyph index."),c=!1),c&&(B=a[A].privateDict,C=B.subrsIndex)}else e&&(C=e);if(c&&(c=this.parseCharString(I,r,C,t)),null!==I.width){const A=B.getByName("nominalWidthX");g[o]=A+I.width}else{const A=B.getByName("defaultWidthX");g[o]=A}null!==I.seac&&(n[o]=I.seac),c||A.set(o,new Uint8Array([14]))}return{charStrings:A,seacs:n,widths:g}}emptyPrivateDictionary(A){const e=this.createDict(Xi,[],A.strings);A.setByKey(18,[0,0]),A.privateDict=e}parsePrivateDict(A){if(!A.hasName("Private"))return void this.emptyPrivateDictionary(A);const e=A.getByName("Private");if(!Array.isArray(e)||2!==e.length)return void A.removeByName("Private");const t=e[0],i=e[1];if(0===t||i>=this.bytes.length)return void this.emptyPrivateDictionary(A);const a=i+t,s=this.bytes.subarray(i,a),n=this.parseDict(s),g=this.createDict(Xi,n,A.strings);if(A.privateDict=g,0===g.getByName("ExpansionFactor")&&g.setByName("ExpansionFactor",.06),!g.getByName("Subrs"))return;const r=g.getByName("Subrs"),o=i+r;if(0===r||o>=this.bytes.length)return void this.emptyPrivateDictionary(A);const I=this.parseIndex(o);g.subrsIndex=I.obj}parseCharsets(A,e,t,i){if(0===A)return new ji(!0,Vi.ISO_ADOBE,Di);if(1===A)return new ji(!0,Vi.EXPERT,bi);if(2===A)return new ji(!0,Vi.EXPERT_SUBSET,ki);const a=this.bytes,s=A,n=a[A++],g=[i?0:".notdef"];let r,o,I;switch(e-=1,n){case 0:for(I=0;I=65535)return void R("Not enough space in charstrings to duplicate first glyph.");const A=this.charStrings.get(0);this.charStrings.add(A),this.isCIDFont&&this.fdSelect.fdSelect.push(this.fdSelect.fdSelect[0])}hasGlyphId(A){return!(A<0||A>=this.charStrings.count)&&this.charStrings.get(A).length>0}}class Ki{constructor(A,e,t,i){this.major=A,this.minor=e,this.hdrSize=t,this.offSize=i}}class qi{constructor(){this.strings=[]}get(A){return A>=0&&A<=390?Li[A]:A-391<=this.strings.length?this.strings[A-391]:Li[0]}getSID(A){let e=Li.indexOf(A);return-1!==e?e:(e=this.strings.indexOf(A),-1!==e?e+391:-1)}add(A){this.strings.push(A)}get count(){return this.strings.length}}class Ti{constructor(){this.objects=[],this.length=0}add(A){this.length+=A.length,this.objects.push(A)}set(A,e){this.length+=e.length-this.objects[A].length,this.objects[A]=e}get(A){return this.objects[A]}get count(){return this.objects.length}}class Pi{constructor(A,e){this.keyToNameMap=A.keyToNameMap,this.nameToKeyMap=A.nameToKeyMap,this.defaults=A.defaults,this.types=A.types,this.opcodes=A.opcodes,this.order=A.order,this.strings=e,this.values=Object.create(null)}setByKey(A,e){if(!(A in this.keyToNameMap))return!1;if(0===e.length)return!0;for(const t of e)if(isNaN(t))return R(`Invalid CFFDict value: "${e}" for key "${A}".`),!0;const t=this.types[A];return"num"!==t&&"sid"!==t&&"offset"!==t||(e=e[0]),this.values[A]=e,!0}setByName(A,e){if(!(A in this.nameToKeyMap))throw new K(`Invalid dictionary name "${A}"`);this.values[this.nameToKeyMap[A]]=e}hasName(A){return this.nameToKeyMap[A]in this.values}getByName(A){if(!(A in this.nameToKeyMap))throw new K(`Invalid dictionary name ${A}"`);const e=this.nameToKeyMap[A];return e in this.values?this.values[e]:this.defaults[e]}removeByName(A){delete this.values[this.nameToKeyMap[A]]}static createTables(A){const e={keyToNameMap:{},nameToKeyMap:{},defaults:{},types:{},opcodes:{},order:[]};for(const t of A){const A=Array.isArray(t[0])?(t[0][0]<<8)+t[0][1]:t[0];e.keyToNameMap[A]=t[1],e.nameToKeyMap[t[1]]=A,e.types[A]=t[2],e.defaults[A]=t[3],e.opcodes[A]=Array.isArray(t[0])?t[0]:[t[0]],e.order.push(A)}return e}}const Wi=[[[12,30],"ROS",["sid","sid","num"],null],[[12,20],"SyntheticBase","num",null],[0,"version","sid",null],[1,"Notice","sid",null],[[12,0],"Copyright","sid",null],[2,"FullName","sid",null],[3,"FamilyName","sid",null],[4,"Weight","sid",null],[[12,1],"isFixedPitch","num",0],[[12,2],"ItalicAngle","num",0],[[12,3],"UnderlinePosition","num",-100],[[12,4],"UnderlineThickness","num",50],[[12,5],"PaintType","num",0],[[12,6],"CharstringType","num",2],[[12,7],"FontMatrix",["num","num","num","num","num","num"],[.001,0,0,.001,0,0]],[13,"UniqueID","num",null],[5,"FontBBox",["num","num","num","num"],[0,0,0,0]],[[12,8],"StrokeWidth","num",0],[14,"XUID","array",null],[15,"charset","offset",0],[16,"Encoding","offset",0],[17,"CharStrings","offset",0],[18,"Private",["offset","offset"],null],[[12,21],"PostScript","sid",null],[[12,22],"BaseFontName","sid",null],[[12,23],"BaseFontBlend","delta",null],[[12,31],"CIDFontVersion","num",0],[[12,32],"CIDFontRevision","num",0],[[12,33],"CIDFontType","num",0],[[12,34],"CIDCount","num",8720],[[12,35],"UIDBase","num",null],[[12,37],"FDSelect","offset",null],[[12,36],"FDArray","offset",null],[[12,38],"FontName","sid",null]];class Zi extends Pi{static get tables(){return U(this,"tables",this.createTables(Wi))}constructor(A){super(Zi.tables,A),this.privateDict=null}}const Oi=[[6,"BlueValues","delta",null],[7,"OtherBlues","delta",null],[8,"FamilyBlues","delta",null],[9,"FamilyOtherBlues","delta",null],[[12,9],"BlueScale","num",.039625],[[12,10],"BlueShift","num",7],[[12,11],"BlueFuzz","num",1],[10,"StdHW","num",null],[11,"StdVW","num",null],[[12,12],"StemSnapH","delta",null],[[12,13],"StemSnapV","delta",null],[[12,14],"ForceBold","num",0],[[12,17],"LanguageGroup","num",0],[[12,18],"ExpansionFactor","num",.06],[[12,19],"initialRandomSeed","num",0],[20,"defaultWidthX","num",0],[21,"nominalWidthX","num",0],[19,"Subrs","offset",null]];class Xi extends Pi{static get tables(){return U(this,"tables",this.createTables(Oi))}constructor(A){super(Xi.tables,A),this.subrsIndex=null}}const Vi={ISO_ADOBE:0,EXPERT:1,EXPERT_SUBSET:2};class ji{constructor(A,e,t,i){this.predefined=A,this.format=e,this.charset=t,this.raw=i}}class zi{constructor(A,e,t,i){this.predefined=A,this.format=e,this.encoding=t,this.raw=i}}class _i{constructor(A,e){this.format=A,this.fdSelect=e}getFDIndex(A){return A<0||A>=this.fdSelect.length?-1:this.fdSelect[A]}}class $i{constructor(){this.offsets=Object.create(null)}isTracking(A){return A in this.offsets}track(A,e){if(A in this.offsets)throw new K(`Already tracking location of ${A}`);this.offsets[A]=e}offset(A){for(const e in this.offsets)this.offsets[e]+=A}setEntryLocation(A,e,t){if(!(A in this.offsets))throw new K(`Not tracking location of ${A}`);const i=t.data,a=this.offsets[A];for(let A=0,t=e.length;A>24&255,i[n]=o>>16&255,i[g]=o>>8&255,i[r]=255&o}}}class Aa{constructor(A){this.cff=A}compile(){const A=this.cff,e={data:[],length:0,add(A){try{this.data.push(...A)}catch{this.data=this.data.concat(A)}this.length=this.data.length}},t=this.compileHeader(A.header);e.add(t);const i=this.compileNameIndex(A.names);if(e.add(i),A.isCIDFont&&A.topDict.hasName("FontMatrix")){const e=A.topDict.getByName("FontMatrix");A.topDict.removeByName("FontMatrix");for(const t of A.fdArray){let A=e.slice(0);t.hasName("FontMatrix")&&(A=V.transform(A,t.getByName("FontMatrix"))),t.setByName("FontMatrix",A)}}A.topDict.getByName("XUID")?.length>16&&A.topDict.removeByName("XUID"),A.topDict.setByName("charset",0);let a=this.compileTopDicts([A.topDict],e.length,A.isCIDFont);e.add(a.output);const s=a.trackers[0],n=this.compileStringIndex(A.strings.strings);e.add(n);const g=this.compileIndex(A.globalSubrIndex);if(e.add(g),A.encoding&&A.topDict.hasName("Encoding"))if(A.encoding.predefined)s.setEntryLocation("Encoding",[A.encoding.format],e);else{const t=this.compileEncoding(A.encoding);s.setEntryLocation("Encoding",[e.length],e),e.add(t)}const r=this.compileCharset(A.charset,A.charStrings.count,A.strings,A.isCIDFont);s.setEntryLocation("charset",[e.length],e),e.add(r);const o=this.compileCharStrings(A.charStrings);if(s.setEntryLocation("CharStrings",[e.length],e),e.add(o),A.isCIDFont){s.setEntryLocation("FDSelect",[e.length],e);const t=this.compileFDSelect(A.fdSelect);e.add(t),a=this.compileTopDicts(A.fdArray,e.length,!0),s.setEntryLocation("FDArray",[e.length],e),e.add(a.output);const i=a.trackers;this.compilePrivateDicts(A.fdArray,i,e)}return this.compilePrivateDicts([A.topDict],[s],e),e.add([0]),e.data}encodeNumber(A){return Number.isInteger(A)?this.encodeInteger(A):this.encodeFloat(A)}static get EncodeFloatRegExp(){return U(this,"EncodeFloatRegExp",/\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/)}encodeFloat(A){let e=A.toString();const t=Aa.EncodeFloatRegExp.exec(e);if(t){const i=parseFloat("1e"+((t[2]?+t[2]:0)+t[1].length));e=(Math.round(A*i)/i).toString()}let i,a,s="";for(i=0,a=e.length;i=-107&&A<=107?[A+139]:A>=108&&A<=1131?[247+((A-=108)>>8),255&A]:A>=-1131&&A<=-108?[251+((A=-A-108)>>8),255&A]:A>=-32768&&A<=32767?[28,A>>8&255,255&A]:[29,A>>24&255,A>>16&255,A>>8&255,255&A],e}compileHeader(A){return[A.major,A.minor,4,A.offSize]}compileNameIndex(A){const e=new Ti;for(const t of A){const A=Math.min(t.length,127);let i=new Array(A);for(let e=0;e"~"||"["===A||"]"===A||"("===A||")"===A||"{"===A||"}"===A||"<"===A||">"===A||"/"===A||"%"===A)&&(A="_"),i[e]=A}i=i.join(""),""===i&&(i="Bad_Font_Name"),e.add(P(i))}return this.compileIndex(e)}compileTopDicts(A,e,t){const i=[];let a=new Ti;for(const s of A){t&&(s.removeByName("CIDFontVersion"),s.removeByName("CIDFontRevision"),s.removeByName("CIDFontType"),s.removeByName("CIDCount"),s.removeByName("UIDBase"));const A=new $i,n=this.compileDict(s,A);i.push(A),a.add(n),A.offset(e)}return a=this.compileIndex(a,i),{trackers:i,output:a}}compilePrivateDicts(A,e,t){for(let i=0,a=A.length;i>8&255,255&s]);else{a=new Uint8Array(1+2*s),a[0]=0;let e=0;const i=A.charset.length;let n=!1;for(let s=1;s>8&255,a[s+1]=255&g}}return this.compileTypedArray(a)}compileEncoding(A){return this.compileTypedArray(A.raw)}compileFDSelect(A){const e=A.format;let t,i;switch(e){case 0:for(t=new Uint8Array(1+A.fdSelect.length),t[0]=e,i=0;i>8&255,255&a,s];for(i=1;i>8&255,255&i,e),s=e)}const g=(n.length-3)/3;n[1]=g>>8&255,n[2]=255&g,n.push(i>>8&255,255&i),t=new Uint8Array(n)}return this.compileTypedArray(t)}compileTypedArray(A){return Array.from(A)}compileIndex(A,e=[]){const t=A.objects,i=t.length;if(0===i)return[0,0];const a=[i>>8&255,255&i];let s,n,g=1;for(s=0;s>8&255,255&r):3===n?a.push(r>>16&255,r>>8&255,255&r):a.push(r>>>24&255,r>>16&255,r>>8&255,255&r),t[s]&&(r+=t[s].length);for(s=0;s=5&&e<=7))return-1;i=A.substring(1)}if(i===i.toUpperCase()&&(t=parseInt(i,16),t>=0))return t}return-1}const sa=[[0,127],[128,255],[256,383],[384,591],[592,687,7424,7551,7552,7615],[688,767,42752,42783],[768,879,7616,7679],[880,1023],[11392,11519],[1024,1279,1280,1327,11744,11775,42560,42655],[1328,1423],[1424,1535],[42240,42559],[1536,1791,1872,1919],[1984,2047],[2304,2431],[2432,2559],[2560,2687],[2688,2815],[2816,2943],[2944,3071],[3072,3199],[3200,3327],[3328,3455],[3584,3711],[3712,3839],[4256,4351,11520,11567],[6912,7039],[4352,4607],[7680,7935,11360,11391,42784,43007],[7936,8191],[8192,8303,11776,11903],[8304,8351],[8352,8399],[8400,8447],[8448,8527],[8528,8591],[8592,8703,10224,10239,10496,10623,11008,11263],[8704,8959,10752,11007,10176,10223,10624,10751],[8960,9215],[9216,9279],[9280,9311],[9312,9471],[9472,9599],[9600,9631],[9632,9727],[9728,9983],[9984,10175],[12288,12351],[12352,12447],[12448,12543,12784,12799],[12544,12591,12704,12735],[12592,12687],[43072,43135],[12800,13055],[13056,13311],[44032,55215],[55296,57343],[67840,67871],[19968,40959,11904,12031,12032,12255,12272,12287,13312,19903,131072,173791,12688,12703],[57344,63743],[12736,12783,63744,64255,194560,195103],[64256,64335],[64336,65023],[65056,65071],[65040,65055],[65104,65135],[65136,65279],[65280,65519],[65520,65535],[3840,4095],[1792,1871],[1920,1983],[3456,3583],[4096,4255],[4608,4991,4992,5023,11648,11743],[5024,5119],[5120,5759],[5760,5791],[5792,5887],[6016,6143],[6144,6319],[10240,10495],[40960,42127],[5888,5919,5920,5951,5952,5983,5984,6015],[66304,66351],[66352,66383],[66560,66639],[118784,119039,119040,119295,119296,119375],[119808,120831],[1044480,1048573],[65024,65039,917760,917999],[917504,917631],[6400,6479],[6480,6527],[6528,6623],[6656,6687],[11264,11359],[11568,11647],[19904,19967],[43008,43055],[65536,65663,65664,65791,65792,65855],[65856,65935],[66432,66463],[66464,66527],[66640,66687],[66688,66735],[67584,67647],[68096,68191],[119552,119647],[73728,74751,74752,74879],[119648,119679],[7040,7103],[7168,7247],[7248,7295],[43136,43231],[43264,43311],[43312,43359],[43520,43615],[65936,65999],[66e3,66047],[66208,66271,66176,66207,67872,67903],[127024,127135,126976,127023]];function na(A,e=-1){if(-1!==e){const t=sa[e];for(let i=0,a=t.length;i=t[i]&&A<=t[i+1])return e}for(let e=0,t=sa.length;e=t[i]&&A<=t[i+1])return e}return-1}const ga=new RegExp("^(\\s)|(\\p{Mn})|(\\p{Cf})$","u"),ra=new Map,oa=!0,Ia=[".notdef",".null","nonmarkingreturn","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quotesingle","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","grave","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","Adieresis","Aring","Ccedilla","Eacute","Ntilde","Odieresis","Udieresis","aacute","agrave","acircumflex","adieresis","atilde","aring","ccedilla","eacute","egrave","ecircumflex","edieresis","iacute","igrave","icircumflex","idieresis","ntilde","oacute","ograve","ocircumflex","odieresis","otilde","uacute","ugrave","ucircumflex","udieresis","dagger","degree","cent","sterling","section","bullet","paragraph","germandbls","registered","copyright","trademark","acute","dieresis","notequal","AE","Oslash","infinity","plusminus","lessequal","greaterequal","yen","mu","partialdiff","summation","product","pi","integral","ordfeminine","ordmasculine","Omega","ae","oslash","questiondown","exclamdown","logicalnot","radical","florin","approxequal","Delta","guillemotleft","guillemotright","ellipsis","nonbreakingspace","Agrave","Atilde","Otilde","OE","oe","endash","emdash","quotedblleft","quotedblright","quoteleft","quoteright","divide","lozenge","ydieresis","Ydieresis","fraction","currency","guilsinglleft","guilsinglright","fi","fl","daggerdbl","periodcentered","quotesinglbase","quotedblbase","perthousand","Acircumflex","Ecircumflex","Aacute","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Oacute","Ocircumflex","apple","Ograve","Uacute","Ucircumflex","Ugrave","dotlessi","circumflex","tilde","macron","breve","dotaccent","ring","cedilla","hungarumlaut","ogonek","caron","Lslash","lslash","Scaron","scaron","Zcaron","zcaron","brokenbar","Eth","eth","Yacute","yacute","Thorn","thorn","minus","multiply","onesuperior","twosuperior","threesuperior","onehalf","onequarter","threequarters","franc","Gbreve","gbreve","Idotaccent","Scedilla","scedilla","Cacute","cacute","Ccaron","ccaron","dcroat"];function ca(A,e){if(void 0!==e[A])return A;const t=aa(A,e);if(-1!==t)for(const A in e)if(e[A]===t)return A;return S("Unable to recover a standard glyph name for: "+A),A}function Ca(A,e,t){const i=Object.create(null);let a,s,n;const g=!!(4&A.flags);if(A.isInternalFont)for(n=e,s=0;s=0?a:0;else if(A.baseEncodingName)for(n=Mi(A.baseEncodingName),s=0;s=0?a:0;else if(g)for(s in e)i[s]=e[s];else for(n=Gi,s=0;s=0?a:0;const r=A.differences;let o;if(r)for(s in r){const A=r[s];if(a=t.indexOf(A),-1===a){o||(o=ea());const e=ca(A,o);e!==A&&(a=t.indexOf(e))}i[s]=a>=0?a:0}return i}function Ba(A){return A.replaceAll(/[,_]/g,"-").replaceAll(/\s/g,"")}const ha=mA((A=>{A[8211]=65074,A[8212]=65073,A[8229]=65072,A[8230]=65049,A[12289]=65041,A[12290]=65042,A[12296]=65087,A[12297]=65088,A[12298]=65085,A[12299]=65086,A[12300]=65089,A[12301]=65090,A[12302]=65091,A[12303]=65092,A[12304]=65083,A[12305]=65084,A[12308]=65081,A[12309]=65082,A[12310]=65047,A[12311]=65048,A[65103]=65076,A[65281]=65045,A[65288]=65077,A[65289]=65078,A[65292]=65040,A[65306]=65043,A[65307]=65044,A[65311]=65046,A[65339]=65095,A[65341]=65096,A[65343]=65075,A[65371]=65079,A[65373]=65080})),Qa=mA((function(A){A["Times-Roman"]="Times-Roman",A.Helvetica="Helvetica",A.Courier="Courier",A.Symbol="Symbol",A["Times-Bold"]="Times-Bold",A["Helvetica-Bold"]="Helvetica-Bold",A["Courier-Bold"]="Courier-Bold",A.ZapfDingbats="ZapfDingbats",A["Times-Italic"]="Times-Italic",A["Helvetica-Oblique"]="Helvetica-Oblique",A["Courier-Oblique"]="Courier-Oblique",A["Times-BoldItalic"]="Times-BoldItalic",A["Helvetica-BoldOblique"]="Helvetica-BoldOblique",A["Courier-BoldOblique"]="Courier-BoldOblique",A.ArialNarrow="Helvetica",A["ArialNarrow-Bold"]="Helvetica-Bold",A["ArialNarrow-BoldItalic"]="Helvetica-BoldOblique",A["ArialNarrow-Italic"]="Helvetica-Oblique",A.ArialBlack="Helvetica",A["ArialBlack-Bold"]="Helvetica-Bold",A["ArialBlack-BoldItalic"]="Helvetica-BoldOblique",A["ArialBlack-Italic"]="Helvetica-Oblique",A["Arial-Black"]="Helvetica",A["Arial-Black-Bold"]="Helvetica-Bold",A["Arial-Black-BoldItalic"]="Helvetica-BoldOblique",A["Arial-Black-Italic"]="Helvetica-Oblique",A.Arial="Helvetica",A["Arial-Bold"]="Helvetica-Bold",A["Arial-BoldItalic"]="Helvetica-BoldOblique",A["Arial-Italic"]="Helvetica-Oblique",A.ArialMT="Helvetica",A["Arial-BoldItalicMT"]="Helvetica-BoldOblique",A["Arial-BoldMT"]="Helvetica-Bold",A["Arial-ItalicMT"]="Helvetica-Oblique",A["Arial-BoldItalicMT-BoldItalic"]="Helvetica-BoldOblique",A["Arial-BoldMT-Bold"]="Helvetica-Bold",A["Arial-ItalicMT-Italic"]="Helvetica-Oblique",A.ArialUnicodeMS="Helvetica",A["ArialUnicodeMS-Bold"]="Helvetica-Bold",A["ArialUnicodeMS-BoldItalic"]="Helvetica-BoldOblique",A["ArialUnicodeMS-Italic"]="Helvetica-Oblique",A["Courier-BoldItalic"]="Courier-BoldOblique",A["Courier-Italic"]="Courier-Oblique",A.CourierNew="Courier",A["CourierNew-Bold"]="Courier-Bold",A["CourierNew-BoldItalic"]="Courier-BoldOblique",A["CourierNew-Italic"]="Courier-Oblique",A["CourierNewPS-BoldItalicMT"]="Courier-BoldOblique",A["CourierNewPS-BoldMT"]="Courier-Bold",A["CourierNewPS-ItalicMT"]="Courier-Oblique",A.CourierNewPSMT="Courier",A["Helvetica-BoldItalic"]="Helvetica-BoldOblique",A["Helvetica-Italic"]="Helvetica-Oblique",A["Symbol-Bold"]="Symbol",A["Symbol-BoldItalic"]="Symbol",A["Symbol-Italic"]="Symbol",A.TimesNewRoman="Times-Roman",A["TimesNewRoman-Bold"]="Times-Bold",A["TimesNewRoman-BoldItalic"]="Times-BoldItalic",A["TimesNewRoman-Italic"]="Times-Italic",A.TimesNewRomanPS="Times-Roman",A["TimesNewRomanPS-Bold"]="Times-Bold",A["TimesNewRomanPS-BoldItalic"]="Times-BoldItalic",A["TimesNewRomanPS-BoldItalicMT"]="Times-BoldItalic",A["TimesNewRomanPS-BoldMT"]="Times-Bold",A["TimesNewRomanPS-Italic"]="Times-Italic",A["TimesNewRomanPS-ItalicMT"]="Times-Italic",A.TimesNewRomanPSMT="Times-Roman",A["TimesNewRomanPSMT-Bold"]="Times-Bold",A["TimesNewRomanPSMT-BoldItalic"]="Times-BoldItalic",A["TimesNewRomanPSMT-Italic"]="Times-Italic"})),la=mA((function(A){A.Courier="FoxitFixed.pfb",A["Courier-Bold"]="FoxitFixedBold.pfb",A["Courier-BoldOblique"]="FoxitFixedBoldItalic.pfb",A["Courier-Oblique"]="FoxitFixedItalic.pfb",A.Helvetica="LiberationSans-Regular.ttf",A["Helvetica-Bold"]="LiberationSans-Bold.ttf",A["Helvetica-BoldOblique"]="LiberationSans-BoldItalic.ttf",A["Helvetica-Oblique"]="LiberationSans-Italic.ttf",A["Times-Roman"]="FoxitSerif.pfb",A["Times-Bold"]="FoxitSerifBold.pfb",A["Times-BoldItalic"]="FoxitSerifBoldItalic.pfb",A["Times-Italic"]="FoxitSerifItalic.pfb",A.Symbol="FoxitSymbol.pfb",A.ZapfDingbats="FoxitDingbats.pfb",A["LiberationSans-Regular"]="LiberationSans-Regular.ttf",A["LiberationSans-Bold"]="LiberationSans-Bold.ttf",A["LiberationSans-Italic"]="LiberationSans-Italic.ttf",A["LiberationSans-BoldItalic"]="LiberationSans-BoldItalic.ttf"})),Ea=mA((function(A){A.Calibri="Helvetica",A["Calibri-Bold"]="Helvetica-Bold",A["Calibri-BoldItalic"]="Helvetica-BoldOblique",A["Calibri-Italic"]="Helvetica-Oblique",A.CenturyGothic="Helvetica",A["CenturyGothic-Bold"]="Helvetica-Bold",A["CenturyGothic-BoldItalic"]="Helvetica-BoldOblique",A["CenturyGothic-Italic"]="Helvetica-Oblique",A.ComicSansMS="Comic Sans MS",A["ComicSansMS-Bold"]="Comic Sans MS-Bold",A["ComicSansMS-BoldItalic"]="Comic Sans MS-BoldItalic",A["ComicSansMS-Italic"]="Comic Sans MS-Italic",A.GillSansMT="Helvetica",A["GillSansMT-Bold"]="Helvetica-Bold",A["GillSansMT-BoldItalic"]="Helvetica-BoldOblique",A["GillSansMT-Italic"]="Helvetica-Oblique",A.Impact="Helvetica",A["ItcSymbol-Bold"]="Helvetica-Bold",A["ItcSymbol-BoldItalic"]="Helvetica-BoldOblique",A["ItcSymbol-Book"]="Helvetica",A["ItcSymbol-BookItalic"]="Helvetica-Oblique",A["ItcSymbol-Medium"]="Helvetica",A["ItcSymbol-MediumItalic"]="Helvetica-Oblique",A.LucidaConsole="Courier",A["LucidaConsole-Bold"]="Courier-Bold",A["LucidaConsole-BoldItalic"]="Courier-BoldOblique",A["LucidaConsole-Italic"]="Courier-Oblique",A["LucidaSans-Demi"]="Helvetica-Bold",A["MS-Gothic"]="MS Gothic",A["MS-Gothic-Bold"]="MS Gothic-Bold",A["MS-Gothic-BoldItalic"]="MS Gothic-BoldItalic",A["MS-Gothic-Italic"]="MS Gothic-Italic",A["MS-Mincho"]="MS Mincho",A["MS-Mincho-Bold"]="MS Mincho-Bold",A["MS-Mincho-BoldItalic"]="MS Mincho-BoldItalic",A["MS-Mincho-Italic"]="MS Mincho-Italic",A["MS-PGothic"]="MS PGothic",A["MS-PGothic-Bold"]="MS PGothic-Bold",A["MS-PGothic-BoldItalic"]="MS PGothic-BoldItalic",A["MS-PGothic-Italic"]="MS PGothic-Italic",A["MS-PMincho"]="MS PMincho",A["MS-PMincho-Bold"]="MS PMincho-Bold",A["MS-PMincho-BoldItalic"]="MS PMincho-BoldItalic",A["MS-PMincho-Italic"]="MS PMincho-Italic",A.NuptialScript="Times-Italic",A.SegoeUISymbol="Helvetica"})),ua=mA((function(A){A["Adobe Jenson"]=!0,A["Adobe Text"]=!0,A.Albertus=!0,A.Aldus=!0,A.Alexandria=!0,A.Algerian=!0,A["American Typewriter"]=!0,A.Antiqua=!0,A.Apex=!0,A.Arno=!0,A.Aster=!0,A.Aurora=!0,A.Baskerville=!0,A.Bell=!0,A.Bembo=!0,A["Bembo Schoolbook"]=!0,A.Benguiat=!0,A["Berkeley Old Style"]=!0,A["Bernhard Modern"]=!0,A["Berthold City"]=!0,A.Bodoni=!0,A["Bauer Bodoni"]=!0,A["Book Antiqua"]=!0,A.Bookman=!0,A["Bordeaux Roman"]=!0,A["Californian FB"]=!0,A.Calisto=!0,A.Calvert=!0,A.Capitals=!0,A.Cambria=!0,A.Cartier=!0,A.Caslon=!0,A.Catull=!0,A.Centaur=!0,A["Century Old Style"]=!0,A["Century Schoolbook"]=!0,A.Chaparral=!0,A["Charis SIL"]=!0,A.Cheltenham=!0,A["Cholla Slab"]=!0,A.Clarendon=!0,A.Clearface=!0,A.Cochin=!0,A.Colonna=!0,A["Computer Modern"]=!0,A["Concrete Roman"]=!0,A.Constantia=!0,A["Cooper Black"]=!0,A.Corona=!0,A.Ecotype=!0,A.Egyptienne=!0,A.Elephant=!0,A.Excelsior=!0,A.Fairfield=!0,A["FF Scala"]=!0,A.Folkard=!0,A.Footlight=!0,A.FreeSerif=!0,A["Friz Quadrata"]=!0,A.Garamond=!0,A.Gentium=!0,A.Georgia=!0,A.Gloucester=!0,A["Goudy Old Style"]=!0,A["Goudy Schoolbook"]=!0,A["Goudy Pro Font"]=!0,A.Granjon=!0,A["Guardian Egyptian"]=!0,A.Heather=!0,A.Hercules=!0,A["High Tower Text"]=!0,A.Hiroshige=!0,A["Hoefler Text"]=!0,A["Humana Serif"]=!0,A.Imprint=!0,A["Ionic No. 5"]=!0,A.Janson=!0,A.Joanna=!0,A.Korinna=!0,A.Lexicon=!0,A.LiberationSerif=!0,A["Liberation Serif"]=!0,A["Linux Libertine"]=!0,A.Literaturnaya=!0,A.Lucida=!0,A["Lucida Bright"]=!0,A.Melior=!0,A.Memphis=!0,A.Miller=!0,A.Minion=!0,A.Modern=!0,A["Mona Lisa"]=!0,A["Mrs Eaves"]=!0,A["MS Serif"]=!0,A["Museo Slab"]=!0,A["New York"]=!0,A["Nimbus Roman"]=!0,A["NPS Rawlinson Roadway"]=!0,A.NuptialScript=!0,A.Palatino=!0,A.Perpetua=!0,A.Plantin=!0,A["Plantin Schoolbook"]=!0,A.Playbill=!0,A["Poor Richard"]=!0,A["Rawlinson Roadway"]=!0,A.Renault=!0,A.Requiem=!0,A.Rockwell=!0,A.Roman=!0,A["Rotis Serif"]=!0,A.Sabon=!0,A.Scala=!0,A.Seagull=!0,A.Sistina=!0,A.Souvenir=!0,A.STIX=!0,A["Stone Informal"]=!0,A["Stone Serif"]=!0,A.Sylfaen=!0,A.Times=!0,A.Trajan=!0,A["Trinité"]=!0,A["Trump Mediaeval"]=!0,A.Utopia=!0,A["Vale Type"]=!0,A["Bitstream Vera"]=!0,A["Vera Serif"]=!0,A.Versailles=!0,A.Wanted=!0,A.Weiss=!0,A["Wide Latin"]=!0,A.Windsor=!0,A.XITS=!0})),da=mA((function(A){A.Dingbats=!0,A.Symbol=!0,A.ZapfDingbats=!0,A.Wingdings=!0,A["Wingdings-Bold"]=!0,A["Wingdings-Regular"]=!0})),fa=mA((function(A){A[2]=10,A[3]=32,A[4]=33,A[5]=34,A[6]=35,A[7]=36,A[8]=37,A[9]=38,A[10]=39,A[11]=40,A[12]=41,A[13]=42,A[14]=43,A[15]=44,A[16]=45,A[17]=46,A[18]=47,A[19]=48,A[20]=49,A[21]=50,A[22]=51,A[23]=52,A[24]=53,A[25]=54,A[26]=55,A[27]=56,A[28]=57,A[29]=58,A[30]=894,A[31]=60,A[32]=61,A[33]=62,A[34]=63,A[35]=64,A[36]=65,A[37]=66,A[38]=67,A[39]=68,A[40]=69,A[41]=70,A[42]=71,A[43]=72,A[44]=73,A[45]=74,A[46]=75,A[47]=76,A[48]=77,A[49]=78,A[50]=79,A[51]=80,A[52]=81,A[53]=82,A[54]=83,A[55]=84,A[56]=85,A[57]=86,A[58]=87,A[59]=88,A[60]=89,A[61]=90,A[62]=91,A[63]=92,A[64]=93,A[65]=94,A[66]=95,A[67]=96,A[68]=97,A[69]=98,A[70]=99,A[71]=100,A[72]=101,A[73]=102,A[74]=103,A[75]=104,A[76]=105,A[77]=106,A[78]=107,A[79]=108,A[80]=109,A[81]=110,A[82]=111,A[83]=112,A[84]=113,A[85]=114,A[86]=115,A[87]=116,A[88]=117,A[89]=118,A[90]=119,A[91]=120,A[92]=121,A[93]=122,A[94]=123,A[95]=124,A[96]=125,A[97]=126,A[98]=196,A[99]=197,A[100]=199,A[101]=201,A[102]=209,A[103]=214,A[104]=220,A[105]=225,A[106]=224,A[107]=226,A[108]=228,A[109]=227,A[110]=229,A[111]=231,A[112]=233,A[113]=232,A[114]=234,A[115]=235,A[116]=237,A[117]=236,A[118]=238,A[119]=239,A[120]=241,A[121]=243,A[122]=242,A[123]=244,A[124]=246,A[125]=245,A[126]=250,A[127]=249,A[128]=251,A[129]=252,A[130]=8224,A[131]=176,A[132]=162,A[133]=163,A[134]=167,A[135]=8226,A[136]=182,A[137]=223,A[138]=174,A[139]=169,A[140]=8482,A[141]=180,A[142]=168,A[143]=8800,A[144]=198,A[145]=216,A[146]=8734,A[147]=177,A[148]=8804,A[149]=8805,A[150]=165,A[151]=181,A[152]=8706,A[153]=8721,A[154]=8719,A[156]=8747,A[157]=170,A[158]=186,A[159]=8486,A[160]=230,A[161]=248,A[162]=191,A[163]=161,A[164]=172,A[165]=8730,A[166]=402,A[167]=8776,A[168]=8710,A[169]=171,A[170]=187,A[171]=8230,A[179]=8220,A[180]=8221,A[181]=8216,A[182]=8217,A[200]=193,A[203]=205,A[207]=211,A[210]=218,A[223]=711,A[224]=321,A[225]=322,A[226]=352,A[227]=353,A[228]=381,A[229]=382,A[233]=221,A[234]=253,A[252]=263,A[253]=268,A[254]=269,A[258]=258,A[260]=260,A[261]=261,A[265]=280,A[266]=281,A[267]=282,A[268]=283,A[269]=313,A[275]=323,A[276]=324,A[278]=328,A[283]=344,A[284]=345,A[285]=346,A[286]=347,A[292]=367,A[295]=377,A[296]=378,A[298]=380,A[305]=963,A[306]=964,A[307]=966,A[308]=8215,A[309]=8252,A[310]=8319,A[311]=8359,A[312]=8592,A[313]=8593,A[337]=9552,A[493]=1039,A[494]=1040,A[672]=1488,A[673]=1489,A[674]=1490,A[675]=1491,A[676]=1492,A[677]=1493,A[678]=1494,A[679]=1495,A[680]=1496,A[681]=1497,A[682]=1498,A[683]=1499,A[684]=1500,A[685]=1501,A[686]=1502,A[687]=1503,A[688]=1504,A[689]=1505,A[690]=1506,A[691]=1507,A[692]=1508,A[693]=1509,A[694]=1510,A[695]=1511,A[696]=1512,A[697]=1513,A[698]=1514,A[705]=1524,A[706]=8362,A[710]=64288,A[711]=64298,A[759]=1617,A[761]=1776,A[763]=1778,A[775]=1652,A[777]=1764,A[778]=1780,A[779]=1781,A[780]=1782,A[782]=771,A[783]=64726,A[786]=8363,A[788]=8532,A[790]=768,A[791]=769,A[792]=768,A[795]=803,A[797]=64336,A[798]=64337,A[799]=64342,A[800]=64343,A[801]=64344,A[802]=64345,A[803]=64362,A[804]=64363,A[805]=64364,A[2424]=7821,A[2425]=7822,A[2426]=7823,A[2427]=7824,A[2428]=7825,A[2429]=7826,A[2430]=7827,A[2433]=7682,A[2678]=8045,A[2679]=8046,A[2830]=1552,A[2838]=686,A[2840]=751,A[2842]=753,A[2843]=754,A[2844]=755,A[2846]=757,A[2856]=767,A[2857]=848,A[2858]=849,A[2862]=853,A[2863]=854,A[2864]=855,A[2865]=861,A[2866]=862,A[2906]=7460,A[2908]=7462,A[2909]=7463,A[2910]=7464,A[2912]=7466,A[2913]=7467,A[2914]=7468,A[2916]=7470,A[2917]=7471,A[2918]=7472,A[2920]=7474,A[2921]=7475,A[2922]=7476,A[2924]=7478,A[2925]=7479,A[2926]=7480,A[2928]=7482,A[2929]=7483,A[2930]=7484,A[2932]=7486,A[2933]=7487,A[2934]=7488,A[2936]=7490,A[2937]=7491,A[2938]=7492,A[2940]=7494,A[2941]=7495,A[2942]=7496,A[2944]=7498,A[2946]=7500,A[2948]=7502,A[2950]=7504,A[2951]=7505,A[2952]=7506,A[2954]=7508,A[2955]=7509,A[2956]=7510,A[2958]=7512,A[2959]=7513,A[2960]=7514,A[2962]=7516,A[2963]=7517,A[2964]=7518,A[2966]=7520,A[2967]=7521,A[2968]=7522,A[2970]=7524,A[2971]=7525,A[2972]=7526,A[2974]=7528,A[2975]=7529,A[2976]=7530,A[2978]=1537,A[2979]=1538,A[2980]=1539,A[2982]=1549,A[2983]=1551,A[2984]=1552,A[2986]=1554,A[2987]=1555,A[2988]=1556,A[2990]=1623,A[2991]=1624,A[2995]=1775,A[2999]=1791,A[3002]=64290,A[3003]=64291,A[3004]=64292,A[3006]=64294,A[3007]=64295,A[3008]=64296,A[3011]=1900,A[3014]=8223,A[3015]=8244,A[3017]=7532,A[3018]=7533,A[3019]=7534,A[3075]=7590,A[3076]=7591,A[3079]=7594,A[3080]=7595,A[3083]=7598,A[3084]=7599,A[3087]=7602,A[3088]=7603,A[3091]=7606,A[3092]=7607,A[3095]=7610,A[3096]=7611,A[3099]=7614,A[3100]=7615,A[3103]=7618,A[3104]=7619,A[3107]=8337,A[3108]=8338,A[3116]=1884,A[3119]=1885,A[3120]=1885,A[3123]=1886,A[3124]=1886,A[3127]=1887,A[3128]=1887,A[3131]=1888,A[3132]=1888,A[3135]=1889,A[3136]=1889,A[3139]=1890,A[3140]=1890,A[3143]=1891,A[3144]=1891,A[3147]=1892,A[3148]=1892,A[3153]=580,A[3154]=581,A[3157]=584,A[3158]=585,A[3161]=588,A[3162]=589,A[3165]=891,A[3166]=892,A[3169]=1274,A[3170]=1275,A[3173]=1278,A[3174]=1279,A[3181]=7622,A[3182]=7623,A[3282]=11799,A[3316]=578,A[3379]=42785,A[3393]=1159,A[3416]=8377})),pa=mA((function(A){A[227]=322,A[264]=261,A[291]=346})),ma=mA((function(A){A[1]=32,A[4]=65,A[5]=192,A[6]=193,A[9]=196,A[17]=66,A[18]=67,A[21]=268,A[24]=68,A[28]=69,A[29]=200,A[30]=201,A[32]=282,A[38]=70,A[39]=71,A[44]=72,A[47]=73,A[48]=204,A[49]=205,A[58]=74,A[60]=75,A[62]=76,A[68]=77,A[69]=78,A[75]=79,A[76]=210,A[80]=214,A[87]=80,A[89]=81,A[90]=82,A[92]=344,A[94]=83,A[97]=352,A[100]=84,A[104]=85,A[109]=220,A[115]=86,A[116]=87,A[121]=88,A[122]=89,A[124]=221,A[127]=90,A[129]=381,A[258]=97,A[259]=224,A[260]=225,A[263]=228,A[268]=261,A[271]=98,A[272]=99,A[273]=263,A[275]=269,A[282]=100,A[286]=101,A[287]=232,A[288]=233,A[290]=283,A[295]=281,A[296]=102,A[336]=103,A[346]=104,A[349]=105,A[350]=236,A[351]=237,A[361]=106,A[364]=107,A[367]=108,A[371]=322,A[373]=109,A[374]=110,A[381]=111,A[382]=242,A[383]=243,A[386]=246,A[393]=112,A[395]=113,A[396]=114,A[398]=345,A[400]=115,A[401]=347,A[403]=353,A[410]=116,A[437]=117,A[442]=252,A[448]=118,A[449]=119,A[454]=120,A[455]=121,A[457]=253,A[460]=122,A[462]=382,A[463]=380,A[853]=44,A[855]=58,A[856]=46,A[876]=47,A[878]=45,A[882]=45,A[894]=40,A[895]=41,A[896]=91,A[897]=93,A[923]=64,A[1004]=48,A[1005]=49,A[1006]=50,A[1007]=51,A[1008]=52,A[1009]=53,A[1010]=54,A[1011]=55,A[1012]=56,A[1013]=57,A[1081]=37,A[1085]=43,A[1086]=45}));function ya(A){const e=Ba(A);return Qa()[e]}function wa(A){const e=Ba(A);return!!(Qa()[e]||Ea()[e]||ua()[e]||da()[e])}class Da{constructor(A=[]){this._map=A}get length(){return this._map.length}forEach(A){for(const e in this._map)A(e,this._map[e].charCodeAt(0))}has(A){return void 0!==this._map[A]}get(A){return this._map[A]}charCodeOf(A){const e=this._map;if(e.length<=65536)return e.indexOf(A);for(const t in e)if(e[t]===A)return 0|t;return-1}amend(A){for(const e in A)this._map[e]=A[e]}}class ba{constructor(A,e){this.firstChar=A,this.lastChar=e}get length(){return this.lastChar+1-this.firstChar}forEach(A){for(let e=this.firstChar,t=this.lastChar;e<=t;e++)A(e,e)}has(A){return this.firstChar<=A&&A<=this.lastChar}get(A){if(this.firstChar<=A&&A<=this.lastChar)return String.fromCharCode(A)}charCodeOf(A){return Number.isInteger(A)&&A>=this.firstChar&&A<=this.lastChar?A:-1}amend(A){G("Should not call amend()")}}class ka{constructor(A,e){this.properties=e;const t=new Yi(A,e,oa);this.cff=t.parse(),this.cff.duplicateFirstGlyph();const i=new Aa(this.cff);this.seacs=this.cff.seacs;try{this.data=i.compile()}catch{R("Failed to compile font "+e.loadedName),this.data=A}this._createBuiltInEncoding()}get numGlyphs(){return this.cff.charStrings.count}getCharset(){return this.cff.charset.charset}getGlyphMapping(){const A=this.cff,e=this.properties,{cidToGidMap:t,cMap:i}=e,a=A.charset.charset;let s,n;if(e.composite){let e,g;if(t?.length>0){e=Object.create(null);for(let A=0,i=t.length;A=0){const i=t[e];i&&(a[A]=i)}}a.length>0&&(this.properties.builtInEncoding=a)}}function Fa(A,e){return(A[e]<<24|A[e+1]<<16|A[e+2]<<8|A[e+3])>>>0}function Sa(A,e){return A[e]<<8|A[e+1]}function Ra(A,e){return(A[e]<<24|A[e+1]<<16)>>16}function Ga(A,e){return A[e]<<24>>24}function Na(A,e){return Ra(A,e)/16384}function xa(A){const e=A.length;let t=32768;return e<1240?t=107:e<33900&&(t=1131),t}function Ua(A,e,t){const i=1===Sa(A,e+2)?Fa(A,e+8):Fa(A,e+16),a=Sa(A,e+i);let s,n,g;if(4===a){Sa(A,e+i+2);const t=Sa(A,e+i+6)>>1;for(n=e+i+14,s=[],g=0;g>1;t0;)B.push({flags:r})}for(t=0;t>1,m=!0;break;case 4:o+=g.pop(),a(r,o),m=!0;break;case 5:for(;g.length>0;)r+=g.shift(),o+=g.shift(),s(r,o);break;case 6:for(;g.length>0&&(r+=g.shift(),s(r,o),0!==g.length);)o+=g.shift(),s(r,o);break;case 7:for(;g.length>0&&(o+=g.shift(),s(r,o),0!==g.length);)r+=g.shift(),s(r,o);break;case 8:for(;g.length>0;)B=r+g.shift(),Q=o+g.shift(),h=B+g.shift(),l=Q+g.shift(),r=h+g.shift(),o=l+g.shift(),n(B,Q,h,l,r,o);break;case 10:if(f=g.pop(),p=null,t.isCFFCIDFont){const A=t.fdSelect.getFDIndex(i);if(A>=0&&AMath.abs(o-e)?r+=g.shift():o+=g.shift(),n(B,Q,h,l,r,o);break;default:throw new K(`unknown operator: 12 ${y}`)}break;case 14:if(g.length>=4){const A=g.pop(),i=g.pop();o=g.pop(),r=g.pop(),e.add(5),e.add(8,[r,o]);let a=La(t.cmap,String.fromCharCode(t.glyphNameMap[Gi[A]]));Ha(t.glyphs[a.glyphId],e,t,a.glyphId),e.add(4),a=La(t.cmap,String.fromCharCode(t.glyphNameMap[Gi[i]])),Ha(t.glyphs[a.glyphId],e,t,a.glyphId)}return;case 19:case 20:I+=g.length>>1,C+=I+7>>3,m=!0;break;case 21:o+=g.pop(),r+=g.pop(),a(r,o),m=!0;break;case 22:r+=g.pop(),a(r,o),m=!0;break;case 24:for(;g.length>2;)B=r+g.shift(),Q=o+g.shift(),h=B+g.shift(),l=Q+g.shift(),r=h+g.shift(),o=l+g.shift(),n(B,Q,h,l,r,o);r+=g.shift(),o+=g.shift(),s(r,o);break;case 25:for(;g.length>6;)r+=g.shift(),o+=g.shift(),s(r,o);B=r+g.shift(),Q=o+g.shift(),h=B+g.shift(),l=Q+g.shift(),r=h+g.shift(),o=l+g.shift(),n(B,Q,h,l,r,o);break;case 26:for(g.length%2&&(r+=g.shift());g.length>0;)B=r,Q=o+g.shift(),h=B+g.shift(),l=Q+g.shift(),r=h,o=l+g.shift(),n(B,Q,h,l,r,o);break;case 27:for(g.length%2&&(o+=g.shift());g.length>0;)B=r+g.shift(),Q=o,h=B+g.shift(),l=Q+g.shift(),r=h+g.shift(),o=l,n(B,Q,h,l,r,o);break;case 28:g.push((c[C]<<24|c[C+1]<<16)>>16),C+=2;break;case 29:f=g.pop()+t.gsubrsBias,p=t.gsubrs[f],p&&A(p);break;case 30:for(;g.length>0&&(B=r,Q=o+g.shift(),h=B+g.shift(),l=Q+g.shift(),r=h+g.shift(),o=l+(1===g.length?g.shift():0),n(B,Q,h,l,r,o),0!==g.length);)B=r+g.shift(),Q=o,h=B+g.shift(),l=Q+g.shift(),o=l+g.shift(),r=h+(1===g.length?g.shift():0),n(B,Q,h,l,r,o);break;case 31:for(;g.length>0&&(B=r+g.shift(),Q=o,h=B+g.shift(),l=Q+g.shift(),o=l+g.shift(),r=h+(1===g.length?g.shift():0),n(B,Q,h,l,r,o),0!==g.length);)B=r,Q=o+g.shift(),h=B+g.shift(),l=Q+g.shift(),r=h+g.shift(),o=l+(1===g.length?g.shift():0),n(B,Q,h,l,r,o);break;default:if(y<32)throw new K(`unknown operator: ${y}`);y<247?g.push(y-139):y<251?g.push(256*(y-247)+c[C++]+108):y<255?g.push(256*-(y-251)-c[C++]-108):(g.push((c[C]<<24|c[C+1]<<16|c[C+2]<<8|c[C+3])/65536),C+=4)}m&&(g.length=0)}}(A)}const Ya=[];class va{cmds=[];add(A,e){if(e)if(LA(e,null))this.cmds.push(A,...e);else{R(`Commands.add - "${A}" has at least one non-number arg: "${e}".`);const t=e.map((A=>"number"==typeof A?A:0));this.cmds.push(A,...t)}else this.cmds.push(A)}}class Ka{constructor(A){this.fontMatrix=A,this.compiledGlyphs=Object.create(null),this.compiledCharCodeToGlyphId=Object.create(null)}getPathJs(A){const{charCode:e,glyphId:t}=La(this.cmap,A);let i,a=this.compiledGlyphs[t];if(!a){try{a=this.compileGlyph(this.glyphs[t],t)}catch(A){a=Ya,i=A}this.compiledGlyphs[t]=a}if(this.compiledCharCodeToGlyphId[e]??=t,i)throw i;return a}compileGlyph(A,e){if(!A||0===A.length||14===A[0])return Ya;let t=this.fontMatrix;if(this.isCFFCIDFont){const A=this.fdSelect.getFDIndex(e);A>=0&&A2*Sa(A,e));const s=[];let n=a(e,0);for(let t=i;tA+(e.getSize()+3&-4)),0)}write(){const A=this.getSize(),e=new DataView(new ArrayBuffer(A)),t=A>131070,i=t?4:2,a=new DataView(new ArrayBuffer((this.glyphs.length+1)*i));t?a.setUint32(0,0):a.setUint16(0,0);let s=0,n=0;for(const A of this.glyphs)s+=A.write(s,e),s=s+3&-4,n+=i,t?a.setUint32(n,s):a.setUint16(n,s>>1);return{isLocationLong:t,loca:new Uint8Array(a.buffer),glyf:new Uint8Array(e.buffer)}}scale(A){for(let e=0,t=this.glyphs.length;eA+e.getSize()),0);return this.header.getSize()+A}write(A,e){if(!this.header)return 0;const t=A;if(A+=this.header.write(A,e),this.simple)A+=this.simple.write(A,e);else for(const t of this.composites)A+=t.write(A,e);return A-t}scale(A){if(!this.header)return;const e=(this.header.xMin+this.header.xMax)/2;if(this.header.scale(e,A),this.simple)this.simple.scale(e,A);else for(const t of this.composites)t.scale(e,A)}}class Va{constructor({numberOfContours:A,xMin:e,yMin:t,xMax:i,yMax:a}){this.numberOfContours=A,this.xMin=e,this.yMin=t,this.xMax=i,this.yMax=a}static parse(A,e){return[10,new Va({numberOfContours:e.getInt16(A),xMin:e.getInt16(A+2),yMin:e.getInt16(A+4),xMax:e.getInt16(A+6),yMax:e.getInt16(A+8)})]}getSize(){return 10}write(A,e){return e.setInt16(A,this.numberOfContours),e.setInt16(A+2,this.xMin),e.setInt16(A+4,this.yMin),e.setInt16(A+6,this.xMax),e.setInt16(A+8,this.yMax),10}scale(A,e){this.xMin=Math.round(A+(this.xMin-A)*e),this.xMax=Math.round(A+(this.xMax-A)*e)}}class ja{constructor({flags:A,xCoordinates:e,yCoordinates:t}){this.xCoordinates=e,this.yCoordinates=t,this.flags=A}}class za{constructor({contours:A,instructions:e}){this.contours=A,this.instructions=e}static parse(A,e,t){const i=[];for(let a=0;a255?A+=2:g>0&&(A+=1),e=s,g=Math.abs(n-t),g>255?A+=2:g>0&&(A+=1),t=n}}return A}write(A,e){const t=A,i=[],a=[],s=[];let n=0,g=0;for(const t of this.contours){for(let A=0,e=t.xCoordinates.length;A=0?18:2,i.push(A)):i.push(o)}n=r;const I=t.yCoordinates[A];if(o=I-g,0===o)e|=32,a.push(0);else{const A=Math.abs(o);A<=255?(e|=o>=0?36:4,a.push(A)):a.push(o)}g=I,s.push(e)}e.setUint16(A,i.length-1),A+=2}e.setUint16(A,this.instructions.length),A+=2,this.instructions.length&&(new Uint8Array(e.buffer,0,e.buffer.byteLength).set(this.instructions,A),A+=this.instructions.length);for(const t of s)e.setUint8(A++,t);for(let t=0,a=i.length;t=-128&&this.argument1<=127&&this.argument2>=-128&&this.argument2<=127||(A+=2):this.argument1>=0&&this.argument1<=255&&this.argument2>=0&&this.argument2<=255||(A+=2),A}write(A,e){const t=A;return 2&this.flags?this.argument1>=-128&&this.argument1<=127&&this.argument2>=-128&&this.argument2<=127||(this.flags|=1):this.argument1>=0&&this.argument1<=255&&this.argument2>=0&&this.argument2<=255||(this.flags|=1),e.setUint16(A,this.flags),e.setUint16(A+2,this.glyphIndex),A+=4,1&this.flags?(2&this.flags?(e.setInt16(A,this.argument1),e.setInt16(A+2,this.argument2)):(e.setUint16(A,this.argument1),e.setUint16(A+2,this.argument2)),A+=4):(e.setUint8(A,this.argument1),e.setUint8(A+1,this.argument2),A+=2),256&this.flags&&(e.setUint16(A,this.instructions.length),A+=2,this.instructions.length&&(new Uint8Array(e.buffer,0,e.buffer.byteLength).set(this.instructions,A),A+=this.instructions.length)),A-t}scale(A,e){}}function $a(A,e,t){A[e]=t>>8&255,A[e+1]=255&t}function As(A,e,t){A[e]=t>>24&255,A[e+1]=t>>16&255,A[e+2]=t>>8&255,A[e+3]=255&t}function es(A,e,t){if(t instanceof Uint8Array)A.set(t,e);else if("string"==typeof t)for(let i=0,a=t.length;it;)t<<=1,i++;const a=t*e;return{range:a,entry:i,rangeShift:e*A-a}}toArray(){let A=this.sfnt;const e=this.tables,t=Object.keys(e);t.sort();const i=t.length;let a,s,n,g,r,o=12+16*i;const I=[o];for(a=0;a>>0,I.push(o);const c=new Uint8Array(o);for(a=0;a>>0;As(c,o+4,A),As(c,o+8,I[a]),As(c,o+12,e[r].length),o+=16}return c}addTable(A,e){if(A in this.tables)throw new Error("Table "+A+" already exists");this.tables[A]=e}}const is=[4],as=[5],ss=[6],ns=[7],gs=[8],rs=[12,35],os=[14],Is=[21],cs=[22],Cs=[30],Bs=[31];class hs{constructor(){this.width=0,this.lsb=0,this.flexing=!1,this.output=[],this.stack=[]}convert(A,e,t){const i=A.length;let a,s,n,g=!1;for(let r=0;ri)return!0;const a=i-A;for(let A=a;A>8&255,255&e):(e=65536*e|0,this.output.push(255,e>>24&255,e>>16&255,e>>8&255,255&e))}return this.output.push(...e),t?this.stack.splice(a,A):this.stack.length=0,!1}}function Qs(A){return A>=48&&A<=57||A>=65&&A<=70||A>=97&&A<=102}function ls(A,e,t){if(t>=A.length)return new Uint8Array(0);let i,a,s=0|e;for(i=0;i>8,s=52845*(e+s)+22719&65535}return g}function Es(A){return 47===A||91===A||93===A||123===A||125===A||40===A||41===A}class us{constructor(A,e,t){if(e){const e=A.getBytes(),t=!((Qs(e[0])||MA(e[0]))&&Qs(e[1])&&Qs(e[2])&&Qs(e[3])&&Qs(e[4])&&Qs(e[5])&&Qs(e[6])&&Qs(e[7]));A=new ae(t?ls(e,55665,4):function(A,e,t){let i=55665;const a=A.length,s=new Uint8Array(a>>>1);let n,g;for(n=0,g=0;n>8,i=52845*(A+i)+22719&65535}}return s.slice(4,g)}(e))}this.seacAnalysisEnabled=!!t,this.stream=A,this.nextChar()}readNumberArray(){this.getToken();const A=[];for(;;){const e=this.getToken();if(null===e||"]"===e||"}"===e)break;A.push(parseFloat(e||0))}return A}readNumber(){const A=this.getToken();return parseFloat(A||0)}readInt(){const A=this.getToken();return 0|parseInt(A||0,10)}readBoolean(){return"true"===this.getToken()?1:0}nextChar(){return this.currentChar=this.stream.getByte()}prevChar(){return this.stream.skip(-2),this.currentChar=this.stream.getByte()}getToken(){let A=!1,e=this.currentChar;for(;;){if(-1===e)return null;if(A)10!==e&&13!==e||(A=!1);else if(37===e)A=!0;else if(!MA(e))break;e=this.nextChar()}if(Es(e))return this.nextChar(),String.fromCharCode(e);let t="";do{t+=String.fromCharCode(e),e=this.nextChar()}while(e>=0&&!MA(e)&&!Es(e));return t}readCharStrings(A,e){return-1===e?A:ls(A,4330,e)}extractFontProgram(A){const e=this.stream,t=[],i=[],a=Object.create(null);a.lenIV=4;const s={subrs:[],charstrings:[],properties:{privateData:a}};let n,g,r,o;for(;null!==(n=this.getToken());)if("/"===n)switch(n=this.getToken(),n){case"CharStrings":for(this.getToken(),this.getToken(),this.getToken(),this.getToken();n=this.getToken(),null!==n&&"end"!==n;){if("/"!==n)continue;const A=this.getToken();g=this.readInt(),this.getToken(),r=g>0?e.getBytes(g):new Uint8Array(0),o=s.properties.privateData.lenIV;const t=this.readCharStrings(r,o);this.nextChar(),n=this.getToken(),"noaccess"===n?this.getToken():"/"===n&&this.prevChar(),i.push({glyph:A,encoded:t})}break;case"Subrs":for(this.readInt(),this.getToken();"dup"===this.getToken();){const A=this.readInt();g=this.readInt(),this.getToken(),r=g>0?e.getBytes(g):new Uint8Array(0),o=s.properties.privateData.lenIV;const i=this.readCharStrings(r,o);this.nextChar(),n=this.getToken(),"noaccess"===n&&this.getToken(),t[A]=i}break;case"BlueValues":case"OtherBlues":case"FamilyBlues":case"FamilyOtherBlues":const A=this.readNumberArray();A.length>0&&A.length;break;case"StemSnapH":case"StemSnapV":s.properties.privateData[n]=this.readNumberArray();break;case"StdHW":case"StdVW":s.properties.privateData[n]=this.readNumberArray()[0];break;case"BlueShift":case"lenIV":case"BlueFuzz":case"BlueScale":case"LanguageGroup":s.properties.privateData[n]=this.readNumber();break;case"ExpansionFactor":s.properties.privateData[n]=this.readNumber()||.06;break;case"ForceBold":s.properties.privateData[n]=this.readBoolean()}for(const{encoded:e,glyph:a}of i){const i=new hs,n=i.convert(e,t,this.seacAnalysisEnabled);let g=i.output;n&&(g=[14]);const r={glyphName:a,charstring:g,width:i.width,lsb:i.lsb,seac:i.seac};if(".notdef"===a?s.charstrings.unshift(r):s.charstrings.push(r),A.builtInEncoding){const e=A.builtInEncoding.indexOf(a);e>-1&&void 0===A.widths[e]&&e>=A.firstChar&&e<=A.lastChar&&(A.widths[e]=i.width)}}return s}extractFontHeader(A){let e;for(;null!==(e=this.getToken());)if("/"===e)switch(e=this.getToken(),e){case"FontMatrix":const t=this.readNumberArray();A.fontMatrix=t;break;case"Encoding":const i=this.getToken();let a;if(/^\d+$/.test(i)){a=[];const A=0|parseInt(i,10);this.getToken();for(let t=0;t=a){for(n+=t;n=0&&(i[A]=a)}return Ca(A,i,t)}hasGlyphId(A){return!(A<0||A>=this.numGlyphs)&&(0===A||this.charstrings[A-1].charstring.length>0)}getSeacs(A){const e=[];for(let t=0,i=A.length;t0;A--)e[A]-=e[A-1];B.setByName(A,e)}s.topDict.privateDict=B;const Q=new Ti;for(I=0,c=i.length;I0&&A.toUnicode.amend(e)}class ks{constructor(A,e,t,i,a,s,n,g,r){this.originalCharCode=A,this.fontChar=e,this.unicode=t,this.accent=i,this.width=a,this.vmetric=s,this.operatorListId=n,this.isSpace=g,this.isInFont=r}get category(){return U(this,"category",function(A){const e=ra.get(A);if(e)return e;const t=A.match(ga),i={isWhitespace:!!t?.[1],isZeroWidthDiacritic:!!t?.[2],isInvisibleFormatMark:!!t?.[3]};return ra.set(A,i),i}(this.unicode),!0)}}function Fs(A,e){return(A<<8)+e}function Ss(A,e,t){A[e+1]=t,A[e]=t>>>8}function Rs(A,e){const t=(A<<8)+e;return 32768&t?t-65536:t}function Gs(A){return String.fromCharCode(A>>8&255,255&A)}function Ns(A){return A>32767?A=32767:A<-32768&&(A=-32768),String.fromCharCode(A>>8&255,255&A)}function xs(A){return"ttcf"===T(A.peekBytes(4))}function Us(A,e){for(const t in e)A[+t]=e[t]}function Ms(A,e,t){const i=[];let a;for(let t=0,s=A.length;tI){if(r++,r>=ps.length){R("Ran out of space in font private use area.");break}o=ps[r][0],I=ps[r][1]}const h=o++;0===B&&(B=t);let Q=i.get(C);"string"==typeof Q&&(Q=Q.codePointAt(0)),!Q||(c=Q,ps[0][0]<=c&&c<=ps[0][1]||ps[1][0]<=c&&c<=ps[1][1])||g.has(B)||(s.set(Q,B),g.add(B)),a[h]=B,n[C]=h}var c;return{toFontChar:n,charCodeToGlyphId:a,toUnicodeExtraMap:s,nextAvailableFontCharCode:o}}function vs(A,e,t){const i=function(A,e,t){const i=[];for(const e in A)A[e]>=t||i.push({fontCharCode:0|e,glyphId:A[e]});if(e)for(const[A,a]of e)a>=t||i.push({fontCharCode:A,glyphId:a});0===i.length&&i.push({fontCharCode:0,glyphId:0}),i.sort((function(A,e){return A.fontCharCode-e.fontCharCode}));const a=[],s=i.length;for(let A=0;A65535?2:1;let s,n,g,r,o="\0\0"+Gs(a)+"\0\0"+W(4+8*a);for(s=i.length-1;s>=0&&!(i[s][0]<=65535);--s);const I=s+1;i[s][0]<65535&&65535===i[s][1]&&(i[s][1]=65534);const c=i[s][1]<65535?1:0,C=I+c,B=ts.getSearchParams(C,2);let h,Q,l,E,u="",d="",f="",p="",m="",y=0;for(s=0,n=I;s0&&(d+="ÿÿ",u+="ÿÿ",f+="\0",p+="\0\0");const w="\0\0"+Gs(2*C)+Gs(B.range)+Gs(B.entry)+Gs(B.rangeShift)+d+"\0\0"+u+f+p+m;let D="",b="";if(a>1){for(o+="\0\0\n"+W(4+8*a+4+w.length),D="",s=0,n=i.length;sA||!g)&&(g=A),r 123 are reserved for internal usage");n|=1<65535&&(r=65535)}else g=0,r=255;const I=A.bbox||[0,0,0,0],c=t.unitsPerEm||(A.fontMatrix?1/Math.max(...A.fontMatrix.slice(0,4).map(Math.abs)):1e3),C=A.ascentScaled?1:c/ms,B=t.ascent||Math.round(C*(A.ascent||I[3]));let h=t.descent||Math.round(C*(A.descent||I[1]));h>0&&A.descent>0&&I[1]<0&&(h=-h);const Q=t.yMax||B,l=-t.yMin||-h;return"\0$ô\0\0\0Š»\0\0\0ŒŠ»\0\0ß\x001\0\0\0\0"+String.fromCharCode(A.fixedPitch?9:0)+"\0\0\0\0\0\0"+W(i)+W(a)+W(s)+W(n)+"*21*"+Gs(A.italicAngle?1:0)+Gs(g||A.firstChar)+Gs(r||A.lastChar)+Gs(B)+Gs(h)+"\0d"+Gs(Q)+Gs(l)+"\0\0\0\0\0\0\0\0"+Gs(A.xHeight)+Gs(A.capHeight)+Gs(0)+Gs(g||A.firstChar)+"\0"}function qs(A){return"\0\0\0"+W(Math.floor(65536*A.italicAngle))+"\0\0\0\0"+W(A.fixedPitch?1:0)+"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"}function Ts(A){return A.replaceAll(/[^\x21-\x7E]|[[\](){}<>/%]/g,"").slice(0,63)}function Ps(A,e){e||(e=[[],[]]);const t=[e[0][0]||"Original licence",e[0][1]||A,e[0][2]||"Unknown",e[0][3]||"uniqueID",e[0][4]||A,e[0][5]||"Version 0.11",e[0][6]||Ts(A),e[0][7]||"Unknown",e[0][8]||"Unknown",e[0][9]||"Unknown"],i=[];let a,s,n,g,r;for(a=0,s=t.length;a=1&&e[3]>=1&&e[3]<=4}(A)?i?(a="CIDFontType0",s="CIDFontType0C"):(a="MMType1"===e?"MMType1":"Type1",s="Type1C"):(R("getFontFileType: Unable to detect correct font file Type/Subtype."),a=e,s=t),[a,s]}(e,t),a===this.type&&s===this.subtype||S(`Inconsistent font file Type/SubType, expected: ${this.type}/${this.subtype} but found: ${a}/${s}.`);try{switch(a){case"MMType1":S("MMType1 font ("+A+"), falling back to Type1.");case"Type1":case"CIDFontType0":this.mimetype="font/opentype";const i="Type1C"===s||"CIDFontType0C"===s?new ka(e,t):new fs(A,e,t);Ds(t),g=this.convert(A,i,t);break;case"OpenType":case"TrueType":case"CIDFontType2":this.mimetype="font/opentype",g=this.checkAndRepair(A,e,t),this.isOpenType&&(Ds(t),a="OpenType");break;default:throw new K(`Font ${a} is not supported`)}}catch(A){return R(A),void this.fallbackToSystemFont(t)}bs(t),this.data=g,this.type=a,this.subtype=s,this.fontMatrix=t.fontMatrix,this.widths=t.widths,this.defaultWidth=t.defaultWidth,this.toUnicode=t.toUnicode,this.seacMap=t.seacMap}get renderer(){return U(this,"renderer",Pa.create(this,oa))}exportData(A=!1){const e=A?[...ys,...ws]:ys,t=Object.create(null);let i,a;for(i of e)a=this[i],void 0!==a&&(t[i]=a);return t}fallbackToSystemFont(A){this.missingFile=!0;const{name:e,type:t}=this;let i=Ba(e);const a=Qa(),s=Ea(),n=!!a[i],g=!(!s[i]||!a[s[i]]);i=a[i]||s[i]||i;const r=Za()[i];r&&(isNaN(this.ascent)&&(this.ascent=r.ascent/ms),isNaN(this.descent)&&(this.descent=r.descent/ms),isNaN(this.capHeight)&&(this.capHeight=r.capHeight/ms)),this.bold=/bold/gi.test(i),this.italic=/oblique|italic/gi.test(i),this.black=/Black/g.test(e);const o=/Narrow/g.test(e);if(this.remeasure=(!n||o)&&Object.keys(this.widths).length>0,(n||g)&&"CIDFontType2"===t&&this.cidEncoding.startsWith("Identity-")){const t=A.cidToGidMap,i=[];if(Us(i,fa()),/Arial-?Black/i.test(e)?Us(i,pa()):/Calibri/i.test(e)&&Us(i,ma()),t){for(const A in i){const e=i[A];void 0!==t[e]&&(i[+A]=t[e])}t.length!==this.toUnicode.length&&A.hasIncludedToUnicodeMap&&this.toUnicode instanceof ba&&this.toUnicode.forEach((function(A,e){const a=i[A];void 0===t[a]&&(i[+A]=e)}))}this.toUnicode instanceof ba||this.toUnicode.forEach((function(A,e){i[+A]=e})),this.toFontChar=i,this.toUnicode=new Da(i)}else if(/Symbol/i.test(i))this.toFontChar=Ms(xi,ea(),this.differences);else if(/Dingbats/i.test(i))this.toFontChar=Ms(Ui,ta(),this.differences);else if(n||g){const A=Ms(this.defaultEncoding,ea(),this.differences);"CIDFontType2"!==t||this.cidEncoding.startsWith("Identity-")||this.toUnicode instanceof ba||this.toUnicode.forEach((function(e,t){A[+e]=t})),this.toFontChar=A}else{const A=ea(),t=[];this.toUnicode.forEach(((e,i)=>{if(!this.composite){const t=aa(this.differences[e]||this.defaultEncoding[e],A);-1!==t&&(i=t)}t[+e]=i})),this.composite&&this.toUnicode instanceof ba&&/Tahoma|Verdana/i.test(e)&&Us(t,fa()),this.toFontChar=t}bs(A),this.loadedName=i.split("-",1)[0]}checkAndRepair(A,e,t){const i=["OS/2","cmap","head","hhea","hmtx","maxp","name","post","loca","glyf","fpgm","prep","cvt ","CFF "];function a(A,e){const t=Object.create(null);t["OS/2"]=null,t.cmap=null,t.head=null,t.hhea=null,t.hmtx=null,t.maxp=null,t.name=null,t.post=null;for(let a=0;a>>0,i=A.getInt32()>>>0,a=A.getInt32()>>>0,s=A.pos;A.pos=A.start||0,A.skip(i);const n=A.getBytes(a);return A.pos=s,"head"===e&&(n[8]=n[9]=n[10]=n[11]=0,n[17]|=32),{tag:e,checksum:t,length:a,offset:i,data:n}}function n(A){return{version:A.getString(4),numTables:A.getUint16(),searchRange:A.getUint16(),entrySelector:A.getUint16(),rangeShift:A.getUint16()}}function g(A,e,t,i,a,s){const n={length:0,sizeOfInstructions:0};if(e<0||e>=A.length||t>A.length||t-e<=12)return n;const g=A.subarray(e,t),r=Rs(g[2],g[3]),o=Rs(g[4],g[5]),I=Rs(g[6],g[7]),c=Rs(g[8],g[9]);r>I&&(Ss(g,2,I),Ss(g,6,r)),o>c&&(Ss(g,4,c),Ss(g,8,o));const C=Rs(g[0],g[1]);if(C<0)return C<-1||(i.set(g,a),n.length=g.length),n;let B,h=10,Q=0;for(B=0;Bg.length?n:!s&&E>0?(i.set(g.subarray(0,l),a),i.set([0,0],a+l),i.set(g.subarray(u,f),a+l+2),f-=E,g.length-f>3&&(f=f+3&-4),n.length=f,n):g.length-f>3?(f=f+3&-4,i.set(g.subarray(0,f),a),n.length=f,n):(i.set(g,a),n.length=g.length,n)}function r(A){const t=(e.start||0)+A.offset;e.pos=t;const i=[[],[]],a=[],s=A.length,n=t+s;if(0!==e.getUint16()||s<6)return[i,a];const g=e.getUint16(),r=e.getUint16();let o,I;for(o=0;on)continue;e.pos=s;const g=A.name;if(A.encoding){let t="";for(let i=0,a=A.length;i0&&(r+=A-1)}}else(l||u)&&(R("TT: nested FDEFs not allowed"),Q=!0),l=!0,c=r,s=C.pop(),e.functionsDefined[s]={data:g,i:r};else if(!l&&!u)if(s=C.at(-1),isNaN(s))S("TT: CALL empty stack (or invalid entry).");else if(e.functionsUsed[s]=!0,s in e.functionsStackDeltas){const A=C.length+e.functionsStackDeltas[s];if(A<0)return R("TT: CALL invalid functions stack delta."),void(e.hintsValid=!1);C.length=A}else if(s in e.functionsDefined&&!h.includes(s)){if(B.push({data:g,i:r,stackTop:C.length-1}),h.push(s),n=e.functionsDefined[s],!n)return R("TT: CALL non-existent function"),void(e.hintsValid=!1);g=n.data,r=n.i}if(!l&&!u){let e=0;for(A<=142?e=o[A]:A>=192&&A<=223?e=-1:A>=224&&(e=-2),A>=113&&A<=117&&(i=C.pop(),isNaN(i)||(e=2*-i));e<0&&C.length>0;)C.pop(),e++;for(;e>0;)C.push(NaN),e--}}e.tooComplexToFollowFunctions=Q;const d=[g];r>g.length&&d.push(new Uint8Array(r-g.length)),c>I&&(R("TT: complementing a missing function tail"),d.push(new Uint8Array([34,45]))),function(A,e){if(e.length>1){let t,i,a=0;for(t=0,i=e.length;t>>0,s=[];for(let e=0;e>>0);const n={ttcTag:e,majorVersion:t,minorVersion:i,numFonts:a,offsetTable:s};switch(t){case 1:return n;case 2:return n.dsigTag=A.getInt32()>>>0,n.dsigLength=A.getInt32()>>>0,n.dsigOffset=A.getInt32()>>>0,n}throw new K(`Invalid TrueType Collection majorVersion: ${t}.`)}(A),s=e.split("+");let g;for(let o=0;o0||!(t.cMap instanceof Ii));if("OTTO"===c.version&&!e||!C.head||!C.hhea||!C.maxp||!C.post)return h=new ae(C["CFF "].data),B=new ka(h,t),Ds(t),this.convert(A,B,t);delete C.glyf,delete C.loca,delete C.fpgm,delete C.prep,delete C["cvt "],this.isOpenType=!0}if(!C.maxp)throw new K('Required "maxp" table is not found');e.pos=(e.start||0)+C.maxp.offset;let l=e.getInt32();const E=e.getUint16();if(65536!==l&&20480!==l){if(6===C.maxp.length)l=20480;else{if(!(C.maxp.length>=32))throw new K('"maxp" table has a wrong version number');l=65536}d=l,(u=C.maxp.data)[3+0]=255&d,u[2]=d>>>8,u[1]=d>>>16,u[0]=d>>>24}var u,d;if(t.scaleFactors?.length===E&&Q){const{scaleFactors:A}=t,e=Fs(C.head.data[50],C.head.data[51]),i=new Oa({glyfTable:C.glyf.data,isGlyphLocationsLong:e,locaTable:C.loca.data,numGlyphs:E});i.scale(A);const{glyf:a,loca:s,isLocationLong:n}=i.write();C.glyf.data=a,C.loca.data=s,n!==!!e&&(C.head.data[50]=0,C.head.data[51]=n?1:0);const g=C.hmtx.data;for(let e=0;e>8&255,g[t+1]=255&i,Ss(g,t+2,Math.round(A[e]*Rs(g[t+2],g[t+3])))}}let f=E+1,p=!0;f>65535&&(p=!1,f=E,R("Not enough space in glyfs to duplicate first glyph."));let m=0,y=0;l>=65536&&C.maxp.length>=32&&(e.pos+=8,e.getUint16()>2&&(C.maxp.data[14]=0,C.maxp.data[15]=2),e.pos+=4,m=e.getUint16(),e.pos+=4,y=e.getUint16()),C.maxp.data[4]=f>>8,C.maxp.data[5]=255&f;const w=function(A,e,t,i){const a={functionsDefined:[],functionsUsed:[],functionsStackDeltas:[],tooComplexToFollowFunctions:!1,hintsValid:!0};if(A&&I(A,a),e&&I(e,a),A&&function(A,e){if(!A.tooComplexToFollowFunctions){if(A.functionsDefined.length>e)return R("TT: more functions defined than expected"),void(A.hintsValid=!1);for(let t=0,i=A.functionsUsed.length;te)return R("TT: invalid function id: "+t),void(A.hintsValid=!1);if(A.functionsUsed[t]&&!A.functionsDefined[t])return R("TT: undefined function: "+t),void(A.hintsValid=!1)}}}(a,i),t&&1&t.length){const A=new Uint8Array(t.length+1);A.set(t.data),t.data=A}return a.hintsValid}(C.fpgm,C.prep,C["cvt "],m);if(w||(delete C.fpgm,delete C.prep,delete C["cvt "]),function(A,e,t,i,a,s){if(!e)return void(t&&(t.data=null));A.pos=(A.start||0)+e.offset,A.pos+=4,A.pos+=2,A.pos+=2,A.pos+=2,A.pos+=2,A.pos+=2,A.pos+=2,A.pos+=2,A.pos+=2,A.pos+=2;const n=A.getUint16();A.pos+=8,A.pos+=2;let g=A.getUint16();0!==n&&(2&Fs(i.data[44],i.data[45])||(e.data[22]=0,e.data[23]=0)),g>a&&(S(`The numOfMetrics (${g}) should not be greater than the numGlyphs (${a}).`),g=a,e.data[34]=(65280&g)>>8,e.data[35]=255&g);const r=a-g-(t.length-4*g>>1);if(r>0){const A=new Uint8Array(t.length+2*r);A.set(t.data),s&&(A[t.length]=t.data[2],A[t.length+1]=t.data[3]),t.data=A}}(e,C.hhea,C.hmtx,C.head,f,p),!C.head)throw new K('Required "head" table is not found');!function(A,e,t){const i=A.data,a=(i[0]<<24)+(i[1]<<16)+(i[2]<<8)+i[3];a>>16!=1&&(S("Attempting to fix invalid version in head table: "+a),i[0]=0,i[1]=1,i[2]=0,i[3]=0);const s=Fs(i[50],i[51]);if(s<0||s>1){S("Attempting to fix invalid indexToLocFormat in head table: "+s);const A=e+1;if(t===A<<1)i[50]=0,i[51]=0;else{if(t!==A<<2)throw new K("Could not fix indexToLocFormat: "+s);i[50]=0,i[51]=1}}}(C.head,E,Q?C.loca.length:0);let D=Object.create(null);if(Q){const A=Fs(C.head.data[50],C.head.data[51]),e=function(A,e,t,i,a,s,n){let r,o,I;i?(r=4,o=function(A,e){return A[e]<<24|A[e+1]<<16|A[e+2]<<8|A[e+3]},I=function(A,e,t){A[e]=t>>>24&255,A[e+1]=t>>16&255,A[e+2]=t>>8&255,A[e+3]=255&t}):(r=2,o=function(A,e){return A[e]<<9|A[e+1]<<1},I=function(A,e,t){A[e]=t>>9&255,A[e+1]=t>>1&255});const c=s?t+1:t,C=r*(1+c),B=new Uint8Array(C);B.set(A.data.subarray(0,C)),A.data=B;const h=e.data,Q=h.length,l=new Uint8Array(Q);let E,u;const d=[];for(E=0,u=0;EQ&&(A=Q),d.push({index:E,offset:A,endOffset:0})}for(d.sort(((A,e)=>A.offset-e.offset)),E=0;EA.index-e.index)),E=0;En&&(n=A.sizeOfInstructions),m+=e,I(B,u,m)}if(0===m){const A=new Uint8Array([0,1,0,0,0,0,0,0,0,0,0,0,0,0,49,0]);for(E=0,u=r;Et+m?e.data=l.subarray(0,t+m):(e.data=new Uint8Array(t+m),e.data.set(l.subarray(0,m))),e.data.set(l.subarray(0,t),m),I(A.data,B.length-r,m+t)}else e.data=l.subarray(0,m);return{missingGlyphs:p,maxSizeOfInstructions:n}}(C.loca,C.glyf,E,A,w,p,y);D=e.missingGlyphs,l>=65536&&C.maxp.length>=32&&(C.maxp.data[26]=e.maxSizeOfInstructions>>8,C.maxp.data[27]=255&e.maxSizeOfInstructions)}if(!C.hhea)throw new K('Required "hhea" table is not found');0===C.hhea.data[10]&&0===C.hhea.data[11]&&(C.hhea.data[10]=255,C.hhea.data[11]=255);const b={unitsPerEm:Fs(C.head.data[18],C.head.data[19]),yMax:Rs(C.head.data[42],C.head.data[43]),yMin:Rs(C.head.data[38],C.head.data[39]),ascent:Rs(C.hhea.data[4],C.hhea.data[5]),descent:Rs(C.hhea.data[6],C.hhea.data[7]),lineGap:Rs(C.hhea.data[8],C.hhea.data[9])};this.ascent=b.ascent/b.unitsPerEm,this.descent=b.descent/b.unitsPerEm,this.lineGap=b.lineGap/b.unitsPerEm,this.cssFontInfo?.lineHeight?(this.lineHeight=this.cssFontInfo.metrics.lineHeight,this.lineGap=this.cssFontInfo.metrics.lineGap):this.lineHeight=this.ascent-this.descent+this.lineGap,C.post&&function(A,t,i){const a=(e.start||0)+A.offset;e.pos=a;const s=a+A.length,n=e.getInt32();let g;e.skip(28);let r,o=!0;switch(n){case 65536:g=Ia;break;case 131072:const A=e.getUint16();if(A!==i){o=!1;break}const a=[];for(r=0;r=32768){o=!1;break}a.push(A)}if(!o)break;const I=[],c=[];for(;e.pos65535)throw new K("Max size of CID is 65,535");let a=-1;e?a=i:void 0!==A[i]&&(a=A[i]),a>=0&&a>>0;let I=!1;if(g?.platformId!==a||g?.encodingId!==s){if(0!==a||0!==s&&1!==s&&3!==s)if(1===a&&0===s)I=!0;else if(3!==a||1!==s||!i&&g){if(t&&3===a&&0===s){I=!0;let t=!0;if(A>3;A.push(i),t=Math.max(i,t)}const i=[];for(let A=0;A<=t;A++)i.push({firstCode:e.getUint16(),entryCount:e.getUint16(),idDelta:Rs(e.getByte(),e.getByte()),idRangePos:e.pos+e.getUint16()});for(let t=0;t<256;t++)if(0===A[t])e.pos=i[0].idRangePos+2*t,B=e.getUint16(),c.push({charCode:t,glyphId:B});else{const a=i[A[t]];for(C=0;C>1;e.skip(6);const t=[];let i;for(i=0;i>1)-(A-i),a.offsetIndex=n,g=Math.max(g,n+a.end-a.start+1)):a.offsetIndex=-1}const r=[];for(C=0;C>>0;for(C=0;C>>0,t=e.getInt32()>>>0;let i=e.getInt32()>>>0;for(let e=A;e<=t;e++)c.push({charCode:e,glyphId:i++})}}}c.sort((function(A,e){return A.charCode-e.charCode}));for(let A=1;A=61440&&e<=61695&&(e&=255),k[e]=A.glyphId}else for(const A of s)k[A.charCode]=A.glyphId;if(t.glyphNames&&(n.length||this.differences.length))for(let A=0;A<256;++A){if(!g&&void 0!==k[A])continue;const e=this.differences[A]||n[A];if(!e)continue;const i=t.glyphNames.indexOf(e);i>0&&F(i)&&(k[A]=i)}}0===k.length&&(k[0]=0);let G=f-1;if(p||(G=0),!t.cssFontInfo){const A=Ys(k,F,G,this.toUnicode);this.toFontChar=A.toFontChar,C.cmap={tag:"cmap",data:vs(A.charCodeToGlyphId,A.toUnicodeExtraMap,f)},C["OS/2"]&&function(A,e){e.pos=(e.start||0)+A.offset;const t=e.getUint16();e.skip(60);const i=e.getUint16();return!(t<4&&768&i||e.getUint16()>e.getUint16()||(e.skip(6),0===e.getUint16()||(A.data[8]=A.data[9]=0,0)))}(C["OS/2"],e)||(C["OS/2"]={tag:"OS/2",data:Ks(t,A.charCodeToGlyphId,b)})}if(!Q)try{h=new ae(C["CFF "].data),B=new Yi(h,t,oa).parse(),B.duplicateFirstGlyph();const A=new Aa(B);C["CFF "].data=A.compile()}catch{R("Failed to compile font "+t.loadedName)}if(C.name){const[e,i]=r(C.name);C.name.data=Ps(A,e),this.psName=e[0][6]||null,t.composite||function(A,e,t){if(A.isInternalFont)return;if(A.hasIncludedToUnicodeMap)return;if(A.hasEncoding)return;if(A.toUnicode instanceof ba)return;if(!e)return;if(0===t.length)return;if(A.defaultEncoding===Ni)return;for(const A of t)if(!Js(A))return;const i=Ni,a=[],s=ea();for(const A in i){const e=i[A];if(""===e)continue;const t=s[e];void 0!==t&&(a[A]=String.fromCharCode(t))}a.length>0&&A.toUnicode.amend(a)}(t,this.isSymbolicFont,i)}else C.name={tag:"name",data:Ps(this.name)};const x=new ts(c.version);for(const A in C)x.addTable(A,C[A].data);return x.toArray()}convert(A,e,t){t.fixedPitch=!1,t.builtInEncoding&&function(A,e){if(A.isInternalFont)return;if(A.hasIncludedToUnicodeMap)return;if(e===A.defaultEncoding)return;if(A.toUnicode instanceof ba)return;const t=[],i=ea();for(const a in e){if(A.hasEncoding&&(A.baseEncodingName||void 0!==A.differences[a]))continue;const s=aa(e[a],i);-1!==s&&(t[a]=String.fromCharCode(s))}t.length>0&&A.toUnicode.amend(t)}(t,t.builtInEncoding);let i=1;e instanceof ka&&(i=e.numGlyphs-1);const s=e.getGlyphMapping(t);let n=null,g=s,r=null;t.cssFontInfo||(n=Ys(s,e.hasGlyphId.bind(e),i,this.toUnicode),this.toFontChar=n.toFontChar,g=n.charCodeToGlyphId,r=n.toUnicodeExtraMap);const o=e.numGlyphs;function I(A,e){let t=null;for(const i in A)e===A[i]&&(t||=[]).push(0|i);return t}function c(A,e){for(const t in A)if(e===A[t])return 0|t;return n.charCodeToGlyphId[n.nextAvailableFontCharCode]=e,n.nextAvailableFontCharCode++}const C=e.seacs;if(n&&C?.length){const A=t.fontMatrix||a,i=e.getCharset(),g=Object.create(null);for(let e in C){e|=0;const t=C[e],a=Gi[t[2]],r=Gi[t[3]],o=i.indexOf(a),B=i.indexOf(r);if(o<0||B<0)continue;const h={x:t[0]*A[0]+t[1]*A[2]+A[4],y:t[0]*A[1]+t[1]*A[3]+A[5]},Q=I(s,e);if(Q)for(const A of Q){const e=n.charCodeToGlyphId,t=c(e,o),i=c(e,B);g[A]={baseFontCharCode:t,accentFontCharCode:i,accentOffset:h}}}t.seacMap=g}const B=t.fontMatrix?1/Math.max(...t.fontMatrix.slice(0,4).map(Math.abs)):1e3,h=new ts("OTTO");return h.addTable("CFF ",e.data),h.addTable("OS/2",Ks(t,g)),h.addTable("cmap",vs(g,r,o)),h.addTable("head","\0\0\0\0\0\0\0\0\0\0_<õ\0\0"+Ns(B)+"\0\0\0\0ž\v~'\0\0\0\0ž\v~'\0\0"+Ns(t.descent)+"ÿ"+Ns(t.ascent)+Gs(t.italicAngle?2:0)+"\0\0\0\0\0\0\0"),h.addTable("hhea","\0\0\0"+Ns(t.ascent)+Ns(t.descent)+"\0\0ÿÿ\0\0\0\0\0\0"+Ns(t.capHeight)+Ns(Math.tan(t.italicAngle)*t.xHeight)+"\0\0\0\0\0\0\0\0\0\0\0\0"+Gs(o)),h.addTable("hmtx",function(){const A=e.charstrings,t=e.cff?e.cff.widths:null;let i="\0\0\0\0";for(let e=1,a=o;e=65520&&I<=65535?0:I>=62976&&I<=63743?ia()[I]||I:173===I?45:I}var I;this.isType3Font&&(a=t);let c=null;if(this.seacMap?.[A]){o=!0;const e=this.seacMap[A];t=e.baseFontCharCode,c={fontChar:String.fromCodePoint(e.accentFontCharCode),offset:e.accentOffset}}let C="";if("number"==typeof t&&(t<=1114111?C=String.fromCodePoint(t):R(`charToGlyph - invalid fontCharCode: ${t}`)),this.missingFile&&this.vertical&&1===C.length){const A=ha()[C.charCodeAt(0)];A&&(C=r=String.fromCharCode(A))}return s=new ks(A,C,r,c,i,g,a,e,o),this._glyphCache[A]=s}charsToGlyphs(A){let e=this._charsCache[A];if(e)return e;if(e=[],this.cMap){const t=Object.create(null),i=A.length;let a=0;for(;ae.length%2==1,a=this.toUnicode instanceof ba?A=>this.toUnicode.charCodeOf(A):A=>this.toUnicode.charCodeOf(String.fromCodePoint(A));for(let s=0,n=A.length;s55295&&(n<57344||n>65533)&&s++,this.toUnicode){const A=a(n);if(-1!==A){i()&&(e.push(t.join("")),t.length=0);for(let e=(this.cMap?this.cMap.getCharCodeLength(A):1)-1;e>=0;e--)t.push(String.fromCharCode(A>>8*e&255));continue}}i()||(e.push(t.join("")),t.length=0),t.push(String.fromCodePoint(n))}return e.push(t.join("")),e}}class Zs{constructor(A){this.error=A,this.loadedName="g_font_error",this.missingFile=!0}charsToGlyphs(){return[]}encodeString(A){return[A]}exportData(A=!1){return{error:this.error}}}class Os{constructor(){G("Cannot initialize Pattern.")}static parseShading(A,e,t,i,a){const s=A instanceof fA?A.dict:A,n=s.get("ShadingType");try{switch(n){case 2:case 3:return new Vs(s,e,t,i,a);case 4:case 5:case 6:case 7:return new $s(A,e,t,i,a);default:throw new K("Unsupported ShadingType: "+n)}}catch(A){if(A instanceof yA)throw A;return R(A),new An}}}class Xs{static SMALL_NUMBER=1e-6;getIR(){G("Abstract method `getIR` called.")}}class Vs extends Xs{constructor(A,e,t,i,a){super(),this.shadingType=A.get("ShadingType");let s=0;if(2===this.shadingType?s=4:3===this.shadingType&&(s=6),this.coordsArr=A.getArray("Coords"),!LA(this.coordsArr,s))throw new K("RadialAxialShading: Invalid /Coords array.");const n=oe.parse({cs:A.getRaw("CS")||A.getRaw("ColorSpace"),xref:e,resources:t,pdfFunctionFactory:i,localColorSpaceCache:a});this.bbox=YA(A.getArray("BBox"),null);let g=0,r=1;const o=A.getArray("Domain");LA(o,2)&&([g,r]=o);let I=!1,c=!1;const C=A.getArray("Extend");var B;if(B=C,2,Array.isArray(B)&&2===B.length&&B.every((A=>"boolean"==typeof A))&&([I,c]=C),!(3!==this.shadingType||I&&c)){const[A,e,t,i,a,s]=this.coordsArr,n=Math.hypot(A-i,e-a);t<=s+n&&s<=t+n&&R("Unsupported radial gradient.")}this.extendStart=I,this.extendEnd=c;const h=A.getRaw("Function"),Q=i.createFromArray(h),l=(r-g)/840,E=this.colorStops=[];if(g>=r||l<=0)return void S("Bad shading domain.");const u=new Float32Array(n.numComps),d=new Float32Array(1);let f,p=0;d[0]=g,Q(d,0,u,0);let m=n.getRgb(u,0);const y=V.makeHexColor(m[0],m[1],m[2]);E.push([0,y]);let w=1;d[0]=g+l,Q(d,0,u,0);let D=n.getRgb(u,0),b=D[0]-m[0]+1,k=D[1]-m[1]+1,F=D[2]-m[2]+1,G=D[0]-m[0]-1,N=D[1]-m[1]-1,x=D[2]-m[2]-1;for(let A=2;A<840;A++){d[0]=g+A*l,Q(d,0,u,0),f=n.getRgb(u,0);const e=A-p;if(b=Math.min(b,(f[0]-m[0]+1)/e),k=Math.min(k,(f[1]-m[1]+1)/e),F=Math.min(F,(f[2]-m[2]+1)/e),G=Math.max(G,(f[0]-m[0]-1)/e),N=Math.max(N,(f[1]-m[1]-1)/e),x=Math.max(x,(f[2]-m[2]-1)/e),!(G<=b&&N<=k&&x<=F)){const A=V.makeHexColor(D[0],D[1],D[2]);E.push([w/840,A]),b=f[0]-D[0]+1,k=f[1]-D[1]+1,F=f[2]-D[2]+1,G=f[0]-D[0]-1,N=f[1]-D[1]-1,x=f[2]-D[2]-1,p=w,m=D}w=A,D=f}const U=V.makeHexColor(D[0],D[1],D[2]);E.push([1,U]);let M="transparent";A.has("Background")&&(f=n.getRgb(A.get("Background"),0),M=V.makeHexColor(f[0],f[1],f[2])),I||(E.unshift([0,M]),E[1][0]+=Xs.SMALL_NUMBER),c||(E.at(-1)[0]-=Xs.SMALL_NUMBER,E.push([1,M])),this.colorStops=E}getIR(){const{coordsArr:A,shadingType:e}=this;let t,i,a,s,n;return 2===e?(i=[A[0],A[1]],a=[A[2],A[3]],s=null,n=null,t="axial"):3===e?(i=[A[0],A[1]],a=[A[3],A[4]],s=A[2],n=A[5],t="radial"):G(`getPattern type unknown: ${e}`),["RadialAxial",t,this.bbox,this.colorStops,i,a,s,n]}}class js{constructor(A,e){this.stream=A,this.context=e,this.buffer=0,this.bufferLength=0;const t=e.numComps;this.tmpCompsBuf=new Float32Array(t);const i=e.colorSpace.numComps;this.tmpCsCompsBuf=e.colorFn?new Float32Array(i):this.tmpCompsBuf}get hasData(){if(this.stream.end)return this.stream.pos0)return!0;const A=this.stream.getByte();return!(A<0||(this.buffer=A,this.bufferLength=8,0))}readBits(A){let e=this.buffer,t=this.bufferLength;if(32===A){if(0===t)return(this.stream.getByte()<<24|this.stream.getByte()<<16|this.stream.getByte()<<8|this.stream.getByte())>>>0;e=e<<24|this.stream.getByte()<<16|this.stream.getByte()<<8|this.stream.getByte();const A=this.stream.getByte();return this.buffer=A&(1<>t)>>>0}if(8===A&&0===t)return this.stream.getByte();for(;t>t}align(){this.buffer=0,this.bufferLength=0}readFlag(){return this.readBits(this.context.bitsPerFlag)}readCoordinate(){const A=this.context.bitsPerCoordinate,e=this.readBits(A),t=this.readBits(A),i=this.context.decode,a=A<32?1/((1<s?s:A,e=e>n?n:e,t=tA*a[e])):t;let n,g=-2;const r=[];for(const[A,e]of i.map(((A,e)=>[A,e])).sort((([A],[e])=>A-e)))-1!==A&&(A===g+1?(n.push(s[e]),g+=1):(g=A,n=[s[e]],r.push(A,n)));return r}(A),t=new CA(null);t.set("BaseFont",oA.get(A)),t.set("Type",oA.get("Font")),t.set("Subtype",oA.get("CIDFontType2")),t.set("Encoding",oA.get("Identity-H")),t.set("CIDToGIDMap",oA.get("Identity")),t.set("W",e),t.set("FirstChar",e[0]),t.set("LastChar",e.at(-2)+e.at(-1).length-1);const i=new CA(null);t.set("FontDescriptor",i);const a=new CA(null);return a.set("Ordering","Identity"),a.set("Registry","Adobe"),a.set("Supplement",0),t.set("CIDSystemInfo",a),t}class Zn{constructor(A){this.lexer=A,this.operators=[],this.token=null,this.prev=null}nextToken(){this.prev=this.token,this.token=this.lexer.getToken()}accept(A){return this.token.type===A&&(this.nextToken(),!0)}expect(A){if(this.accept(A))return!0;throw new K(`Unexpected symbol: found ${this.token.type} expected ${A}.`)}parse(){return this.nextToken(),this.expect(On.LBRACE),this.parseBlock(),this.expect(On.RBRACE),this.operators}parseBlock(){for(;;)if(this.accept(On.NUMBER))this.operators.push(this.prev.value);else if(this.accept(On.OPERATOR))this.operators.push(this.prev.value);else{if(!this.accept(On.LBRACE))return;this.parseCondition()}}parseCondition(){const A=this.operators.length;if(this.operators.push(null,null),this.parseBlock(),this.expect(On.RBRACE),this.accept(On.IF))this.operators[A]=this.operators.length,this.operators[A+1]="jz";else{if(!this.accept(On.LBRACE))throw new K("PS Function: error parsing conditional.");{const e=this.operators.length;this.operators.push(null,null);const t=this.operators.length;this.parseBlock(),this.expect(On.RBRACE),this.expect(On.IFELSE),this.operators[e]=this.operators.length,this.operators[e+1]="j",this.operators[A]=t,this.operators[A+1]="jz"}}}}const On={LBRACE:0,RBRACE:1,NUMBER:2,OPERATOR:3,IF:4,IFELSE:5};class Xn{static get opCache(){return U(this,"opCache",Object.create(null))}constructor(A,e){this.type=A,this.value=e}static getOperator(A){return Xn.opCache[A]||=new Xn(On.OPERATOR,A)}static get LBRACE(){return U(this,"LBRACE",new Xn(On.LBRACE,"{"))}static get RBRACE(){return U(this,"RBRACE",new Xn(On.RBRACE,"}"))}static get IF(){return U(this,"IF",new Xn(On.IF,"IF"))}static get IFELSE(){return U(this,"IFELSE",new Xn(On.IFELSE,"IFELSE"))}}class Vn{constructor(A){this.stream=A,this.nextChar(),this.strBuf=[]}nextChar(){return this.currentChar=this.stream.getByte()}getToken(){let A=!1,e=this.currentChar;for(;;){if(e<0)return sA;if(A)10!==e&&13!==e||(A=!1);else if(37===e)A=!0;else if(!MA(e))break;e=this.nextChar()}switch(0|e){case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:case 43:case 45:case 46:return new Xn(On.NUMBER,this.getNumber());case 123:return this.nextChar(),Xn.LBRACE;case 125:return this.nextChar(),Xn.RBRACE}const t=this.strBuf;for(t.length=0,t[0]=String.fromCharCode(e);(e=this.nextChar())>=0&&(e>=65&&e<=90||e>=97&&e<=122);)t.push(String.fromCharCode(e));const i=t.join("");switch(i.toLowerCase()){case"if":return Xn.IF;case"ifelse":return Xn.IFELSE;default:return Xn.getOperator(i)}}getNumber(){let A=this.currentChar;const e=this.strBuf;for(e.length=0,e[0]=String.fromCharCode(A);(A=this.nextChar())>=0&&(A>=48&&A<=57||45===A||46===A);)e.push(String.fromCharCode(A));const t=parseFloat(e.join(""));if(isNaN(t))throw new K(`Invalid floating point number: ${t}`);return t}}class jn{constructor(A){this._onlyRefs=!0===A?.onlyRefs,this._onlyRefs||(this._nameRefMap=new Map,this._imageMap=new Map),this._imageCache=new QA}getByName(A){this._onlyRefs&&G("Should not call `getByName` method.");const e=this._nameRefMap.get(A);return e?this.getByRef(e):this._imageMap.get(A)||null}getByRef(A){return this._imageCache.get(A)||null}set(A,e,t){G("Abstract method `set` called.")}}class zn extends jn{set(A,e=null,t){if("string"!=typeof A)throw new Error('LocalImageCache.set - expected "name" argument.');if(e){if(this._imageCache.has(e))return;return this._nameRefMap.set(A,e),void this._imageCache.put(e,t)}this._imageMap.has(A)||this._imageMap.set(A,t)}}class _n extends jn{set(A=null,e=null,t){if("string"!=typeof A&&!e)throw new Error('LocalColorSpaceCache.set - expected "name" and/or "ref" argument.');if(e){if(this._imageCache.has(e))return;return null!==A&&this._nameRefMap.set(A,e),void this._imageCache.put(e,t)}this._imageMap.has(A)||this._imageMap.set(A,t)}}class $n extends jn{constructor(A){super({onlyRefs:!0})}set(A=null,e,t){if(!e)throw new Error('LocalFunctionCache.set - expected "ref" argument.');this._imageCache.has(e)||this._imageCache.put(e,t)}}class Ag extends jn{set(A,e=null,t){if("string"!=typeof A)throw new Error('LocalGStateCache.set - expected "name" argument.');if(e){if(this._imageCache.has(e))return;return this._nameRefMap.set(A,e),void this._imageCache.put(e,t)}this._imageMap.has(A)||this._imageMap.set(A,t)}}class eg extends jn{constructor(A){super({onlyRefs:!0})}set(A=null,e,t){if(!e)throw new Error('LocalTilingPatternCache.set - expected "ref" argument.');this._imageCache.has(e)||this._imageCache.put(e,t)}}class tg extends jn{constructor(A){super({onlyRefs:!0})}set(A=null,e,t){if(!e)throw new Error('RegionalImageCache.set - expected "ref" argument.');this._imageCache.has(e)||this._imageCache.put(e,t)}}class ig{static NUM_PAGES_THRESHOLD=2;static MIN_IMAGES_TO_CACHE=10;static MAX_BYTE_SIZE=5e7;#D=new hA;constructor(){this._refCache=new QA,this._imageCache=new QA}get#b(){let A=0;for(const e of this._imageCache)A+=e.byteSize;return A}get#k(){return!(this._imageCache.size+A)):null}class ng{static getSampleArray(A,e,t,i){let a,s,n=1;for(a=0,s=A.length;a>r)*I,o&=(1<t?A=t:A0&&(C=s[c-1]);let B=i[1];c>1,o=a.length>>1,I=new og(g),c=Object.create(null);let C=8192;const B=new Float32Array(o);return function(A,e,t,i){let a,n,g="";const h=B;for(a=0;aA&&(n=A)),l[a]=n}C>0&&(C--,c[g]=l),t.set(l,i)}}}function gg(A){let e;if(A instanceof CA)e=A;else{if(!(A instanceof fA))return!1;e=A.dict}return e.has("FunctionType")}class rg{static MAX_STACK_SIZE=100;constructor(A){this.stack=A?Array.from(A):[]}push(A){if(this.stack.length>=rg.MAX_STACK_SIZE)throw new Error("PostScript function stack overflow.");this.stack.push(A)}pop(){if(this.stack.length<=0)throw new Error("PostScript function stack underflow.");return this.stack.pop()}copy(A){if(this.stack.length+A>=rg.MAX_STACK_SIZE)throw new Error("PostScript function stack overflow.");const e=this.stack;for(let t=e.length-A,i=A-1;i>=0;i--,t++)e.push(e[t])}index(A){this.push(this.stack[this.stack.length-A-1])}roll(A,e){const t=this.stack,i=t.length-A,a=t.length-1,s=i+(e-Math.floor(e/A)*A);for(let A=i,e=a;A0?e.push(n<>g);break;case"ceiling":n=e.pop(),e.push(Math.ceil(n));break;case"copy":n=e.pop(),e.copy(n);break;case"cos":n=e.pop(),e.push(Math.cos(n%360/180*Math.PI));break;case"cvi":n=0|e.pop(),e.push(n);break;case"cvr":break;case"div":g=e.pop(),n=e.pop(),e.push(n/g);break;case"dup":e.copy(1);break;case"eq":g=e.pop(),n=e.pop(),e.push(n===g);break;case"exch":e.roll(2,1);break;case"exp":g=e.pop(),n=e.pop(),e.push(n**g);break;case"false":e.push(!1);break;case"floor":n=e.pop(),e.push(Math.floor(n));break;case"ge":g=e.pop(),n=e.pop(),e.push(n>=g);break;case"gt":g=e.pop(),n=e.pop(),e.push(n>g);break;case"idiv":g=e.pop(),n=e.pop(),e.push(n/g|0);break;case"index":n=e.pop(),e.index(n);break;case"le":g=e.pop(),n=e.pop(),e.push(n<=g);break;case"ln":n=e.pop(),e.push(Math.log(n));break;case"log":n=e.pop(),e.push(Math.log10(n));break;case"lt":g=e.pop(),n=e.pop(),e.push(n=e?new Cg(e):A.max<=e?A:new hg(A,e)}class mg{compile(A,e,t){const i=[],a=[],s=e.length>>1,n=t.length>>1;let g,r,o,I,c,C,B,h,Q=0;for(let A=0;Ae.min&&(g.unshift("Math.max(",s,", "),g.push(")")),n4?(i=!0,e=0):(i=!1,e=1));const r=[];for(s=0;s=0&&"ET"===Ng[A];--A)Ng[A]="EN";for(let A=s+1;A0&&(e=Ng[s-1]);let t=c;A+1h&&Dg(h)&&(l=h);for(h=Q;h>=l;--h){let A=-1;for(s=0,n=r.length;s=0&&(Sg(Gg,A,s),A=-1):A<0&&(A=s);A>=0&&Sg(Gg,A,r.length)}for(s=0,n=Gg.length;s"!==A||(Gg[s]="")}return Rg(Gg.join(""),i)}const Ug={style:"normal",weight:"normal"},Mg={style:"normal",weight:"bold"},Lg={style:"italic",weight:"normal"},Jg={style:"italic",weight:"bold"},Hg=new Map([["Times-Roman",{local:["Times New Roman","Times-Roman","Times","Liberation Serif","Nimbus Roman","Nimbus Roman L","Tinos","Thorndale","TeX Gyre Termes","FreeSerif","Linux Libertine O","Libertinus Serif","DejaVu Serif","Bitstream Vera Serif","Ubuntu"],style:Ug,ultimate:"serif"}],["Times-Bold",{alias:"Times-Roman",style:Mg,ultimate:"serif"}],["Times-Italic",{alias:"Times-Roman",style:Lg,ultimate:"serif"}],["Times-BoldItalic",{alias:"Times-Roman",style:Jg,ultimate:"serif"}],["Helvetica",{local:["Helvetica","Helvetica Neue","Arial","Arial Nova","Liberation Sans","Arimo","Nimbus Sans","Nimbus Sans L","A030","TeX Gyre Heros","FreeSans","DejaVu Sans","Albany","Bitstream Vera Sans","Arial Unicode MS","Microsoft Sans Serif","Apple Symbols","Cantarell"],path:"LiberationSans-Regular.ttf",style:Ug,ultimate:"sans-serif"}],["Helvetica-Bold",{alias:"Helvetica",path:"LiberationSans-Bold.ttf",style:Mg,ultimate:"sans-serif"}],["Helvetica-Oblique",{alias:"Helvetica",path:"LiberationSans-Italic.ttf",style:Lg,ultimate:"sans-serif"}],["Helvetica-BoldOblique",{alias:"Helvetica",path:"LiberationSans-BoldItalic.ttf",style:Jg,ultimate:"sans-serif"}],["Courier",{local:["Courier","Courier New","Liberation Mono","Nimbus Mono","Nimbus Mono L","Cousine","Cumberland","TeX Gyre Cursor","FreeMono","Linux Libertine Mono O","Libertinus Mono"],style:Ug,ultimate:"monospace"}],["Courier-Bold",{alias:"Courier",style:Mg,ultimate:"monospace"}],["Courier-Oblique",{alias:"Courier",style:Lg,ultimate:"monospace"}],["Courier-BoldOblique",{alias:"Courier",style:Jg,ultimate:"monospace"}],["ArialBlack",{local:["Arial Black"],style:{style:"normal",weight:"900"},fallback:"Helvetica-Bold"}],["ArialBlack-Bold",{alias:"ArialBlack"}],["ArialBlack-Italic",{alias:"ArialBlack",style:{style:"italic",weight:"900"},fallback:"Helvetica-BoldOblique"}],["ArialBlack-BoldItalic",{alias:"ArialBlack-Italic"}],["ArialNarrow",{local:["Arial Narrow","Liberation Sans Narrow","Helvetica Condensed","Nimbus Sans Narrow","TeX Gyre Heros Cn"],style:Ug,fallback:"Helvetica"}],["ArialNarrow-Bold",{alias:"ArialNarrow",style:Mg,fallback:"Helvetica-Bold"}],["ArialNarrow-Italic",{alias:"ArialNarrow",style:Lg,fallback:"Helvetica-Oblique"}],["ArialNarrow-BoldItalic",{alias:"ArialNarrow",style:Jg,fallback:"Helvetica-BoldOblique"}],["Calibri",{local:["Calibri","Carlito"],style:Ug,fallback:"Helvetica"}],["Calibri-Bold",{alias:"Calibri",style:Mg,fallback:"Helvetica-Bold"}],["Calibri-Italic",{alias:"Calibri",style:Lg,fallback:"Helvetica-Oblique"}],["Calibri-BoldItalic",{alias:"Calibri",style:Jg,fallback:"Helvetica-BoldOblique"}],["Wingdings",{local:["Wingdings","URW Dingbats"],style:Ug}],["Wingdings-Regular",{alias:"Wingdings"}],["Wingdings-Bold",{alias:"Wingdings"}]]),Yg=new Map([["Arial-Black","ArialBlack"]]);function vg(A){const e=new Set(["thin","extralight","ultralight","demilight","semilight","light","book","regular","normal","medium","demibold","semibold","bold","extrabold","ultrabold","black","heavy","extrablack","ultrablack","roman","italic","oblique","ultracondensed","extracondensed","condensed","semicondensed","normal","semiexpanded","expanded","extraexpanded","ultraexpanded","bolditalic"]);return A.split(/[- ,+]+/g).filter((A=>!e.has(A.toLowerCase()))).join(" ")}function Kg({alias:A,local:e,path:t,fallback:i,style:a,ultimate:s},n,g,r=!0,o=!0,I=""){const c={style:null,ultimate:null};if(e){const A=I?` ${I}`:"";for(const t of e)n.push(`local(${t}${A})`)}if(A){const e=Hg.get(A),s=I||function(A){switch(A){case Mg:return"Bold";case Lg:return"Italic";case Jg:return"Bold Italic";default:if("bold"===A?.weight)return"Bold";if("italic"===A?.style)return"Italic"}return""}(a);Object.assign(c,Kg(e,n,g,r&&!i,o&&!t,s))}if(a&&(c.style=a),s&&(c.ultimate=s),r&&i){const A=Hg.get(i),{ultimate:e}=Kg(A,n,g,r,o&&!t,I);c.ultimate||=e}return o&&t&&g&&n.push(`url(${g}${t})`),c}function qg(A,e,t,i,a,s){if(i.startsWith("InvalidPDFjsFont_"))return null;"TrueType"!==s&&"Type1"!==s||!/^[A-Z]{6}\+/.test(i)||(i=i.slice(7));const n=i=Ba(i);let g=A.get(n);if(g)return g;let r=Hg.get(i);if(!r)for(const[A,e]of Yg)if(i.startsWith(A)){i=`${e}${i.substring(A.length)}`,r=Hg.get(i);break}let o=!1;r||(r=Hg.get(a),o=!0);const I=`${e.getDocId()}_s${e.createFontId()}`;if(!r){if(!XA(i))return R(`Cannot substitute the font because of its name: ${i}`),A.set(n,null),null;const e=/bold/gi.test(i),t=/oblique|italic/gi.test(i),a=e&&t&&Jg||e&&Mg||t&&Lg||Ug;return g={css:`"${vg(i)}",${I}`,guessFallback:!0,loadedName:I,baseFontName:i,src:`local(${i})`,style:a},A.set(n,g),g}const c=[];o&&XA(i)&&c.push(`local(${i})`);const{style:C,ultimate:B}=Kg(r,c,t),h=null===B,Q=h?"":`,${B}`;return g={css:`"${vg(i)}",${I}${Q}`,guessFallback:h,loadedName:I,baseFontName:i,src:c.join(","),style:C},A.set(n,g),g}class Tg{constructor(A,e){this._imgData=A,this._isMask=e}static needsToBeResized(A,e){if(A<=this._goodSquareLength&&e<=this._goodSquareLength)return!1;const{MAX_DIM:t}=this;if(A>t||e>t)return!0;const i=A*e;return this._hasMaxArea?i>this.MAX_AREA:!(i(this.MAX_AREA=this._goodSquareLength**2)))}static get MAX_DIM(){return U(this,"MAX_DIM",this._guessMax(2048,65537,0,1))}static get MAX_AREA(){return this._hasMaxArea=!0,U(this,"MAX_AREA",this._guessMax(Tg._goodSquareLength,this.MAX_DIM,128,0)**2)}static set MAX_AREA(A){A>=0&&(this._hasMaxArea=!0,U(this,"MAX_AREA",A))}static setMaxArea(A){this._hasMaxArea||(this.MAX_AREA=A>>2)}static _areGoodDims(A,e){try{const t=new OffscreenCanvas(A,e),i=t.getContext("2d");i.fillRect(0,0,1,1);const a=i.getImageData(0,0,1,1).data[3];return t.width=t.height=1,0!==a}catch{return!1}}static _guessMax(A,e,t,i){for(;A+t+1>3,n=t+3&-4;if(t!==n){const A=new Uint8Array(n*e);let i=0;for(let s=0,g=e*t;s>>8,e[t++]=255&a)}}else{if(!ArrayBuffer.isView(A))throw new Error("Invalid data format, must be a string or TypedArray.");e=A.slice(),t=e.byteLength}const i=t>>2,a=t-4*i,s=new Uint32Array(e.buffer,0,i);let n=0,g=0,r=this.h1,o=this.h2;const I=3432918353,c=461845907,C=11601,B=13715;for(let A=0;A>>17,n=n*c&Wg|n*B&Zg,r^=n,r=r<<13|r>>>19,r=5*r+3864292196):(g=s[A],g=g*I&Wg|g*C&Zg,g=g<<15|g>>>17,g=g*c&Wg|g*B&Zg,o^=g,o=o<<13|o>>>19,o=5*o+3864292196);switch(n=0,a){case 3:n^=e[4*i+2]<<16;case 2:n^=e[4*i+1]<<8;case 1:n^=e[4*i],n=n*I&Wg|n*C&Zg,n=n<<15|n>>>17,n=n*c&Wg|n*B&Zg,1&i?r^=n:o^=n}this.h1=r,this.h2=o}hexdigest(){let A=this.h1,e=this.h2;return A^=e>>>1,A=3981806797*A&Wg|36045*A&Zg,e=4283543511*e&Wg|(2950163797*(e<<16|A>>>16)&Wg)>>>16,A^=e>>>1,A=444984403*A&Wg|60499*A&Zg,e=3301882366*e&Wg|(3120437893*(e<<16|A>>>16)&Wg)>>>16,A^=e>>>1,(A>>>0).toString(16).padStart(8,"0")+(e>>>0).toString(16).padStart(8,"0")}}function Xg(A,e,t,i,a){let s=A;for(let A=0,t=e.length-1;A1e3&&(o=Math.max(o,C),B+=c+2,C=0,c=0),I.push({transform:e,x:C,y:B,w:t.width,h:t.height}),C+=t.width+2,c=Math.max(c,t.height)}const h=Math.max(o,C)+1,Q=B+c+1,l=new Uint8Array(h*Q*4),E=h<<2;for(let A=0;A=0;)e[s-4]=e[s],e[s-3]=e[s+1],e[s-2]=e[s+2],e[s-1]=e[s+3],e[s+t]=e[s+t-4],e[s+t+1]=e[s+t-3],e[s+t+2]=e[s+t-2],e[s+t+3]=e[s+t-1],s-=E}const u={width:h,height:Q};if(A.isOffscreenCanvasSupported){const A=new OffscreenCanvas(h,Q);A.getContext("2d").putImageData(new ImageData(new Uint8ClampedArray(l.buffer),h,Q),0,0),u.bitmap=A.transferToImageBitmap(),u.data=null}else u.kind=3,u.data=l;return t.splice(s,4*r,87),i.splice(s,4*r,[u,I]),s+1})),Xg(Vg,[l,u,D,E],null,(function(A,e){const t=A.fnArray,i=(e-(A.iCurr-3))%4;switch(i){case 0:return t[e]===l;case 1:return t[e]===u;case 2:return t[e]===D;case 3:return t[e]===E}throw new Error(`iterateImageMaskGroup - invalid pos: ${i}`)}),(function(A,e){const t=A.fnArray,i=A.argsArray,a=A.iCurr,s=a-3,n=a-2,g=a-1;let r=Math.floor((e-s)/4);if(r<10)return e-(e-s)%4;let o,I,c=!1;const C=i[g][0],B=i[n][0],h=i[n][1],Q=i[n][2],l=i[n][3];if(h===Q){c=!0,o=n+4;let A=g+4;for(let e=1;e=4&&t[s-4]===t[n]&&t[s-3]===t[g]&&t[s-2]===t[r]&&t[s-1]===t[o]&&i[s-4][0]===I&&i[s-4][1]===c&&(C++,B-=5);let h=B+4;for(let A=1;A=t)break}i=(i||Vg)[A[e]],i&&!Array.isArray(i)?(s.iCurr=e,e++,!i.checkFn||(0,i.checkFn)(s)?(a=i,i=null):i=null):e++}this.state=i,this.match=a,this.lastProcessed=e}flush(){for(;this.match;){const A=this.queue.fnArray.length;this.lastProcessed=(0,this.match.processFn)(this.context,A),this.match=null,this.state=null,this._optimize()}}reset(){this.state=null,this.match=null,this.lastProcessed=0}}class _g{static CHUNK_SIZE=1e3;static CHUNK_SIZE_ABOUT=this.CHUNK_SIZE-5;constructor(A=0,e){this._streamSink=e,this.fnArray=[],this.argsArray=[],this.optimizer=!e||256&A?new jg(this):new zg(this),this.dependencies=new Set,this._totalLength=0,this.weight=0,this._resolved=e?null:Promise.resolve()}set isOffscreenCanvasSupported(A){this.optimizer.isOffscreenCanvasSupported=A}get length(){return this.argsArray.length}get ready(){return this._resolved||this._streamSink.ready}get totalLength(){return this._totalLength+this.length}addOp(A,e){this.optimizer.push(A,e),this.weight++,this._streamSink&&(this.weight>=_g.CHUNK_SIZE||this.weight>=_g.CHUNK_SIZE_ABOUT&&(A===E||32===A))&&this.flush()}addImageOps(A,e,t){void 0!==t&&this.addOp(y,["OC",t]),this.addOp(A,e),void 0!==t&&this.addOp(w,[])}addDependency(A){this.dependencies.has(A)||(this.dependencies.add(A),this.addOp(1,[A]))}addDependencies(A){for(const e of A)this.addDependency(e)}addOpList(A){if(A instanceof _g){for(const e of A.dependencies)this.dependencies.add(e);for(let e=0,t=A.length;ei&&(A=i),A}function Ar(A,e,t,i,a,s){const n=a*s;let g;g=e<=8?new Uint8Array(n):e<=16?new Uint16Array(n):new Uint32Array(n);const r=t/a,o=i/s;let I,c,C,B,h=0;const Q=new Uint16Array(a),l=t;for(I=0;I0&&Number.isInteger(t.height)&&t.height>0&&(t.width!==C||t.height!==B)&&(R("PDFImage - using the Width/Height of the image data, rather than the image dictionary."),C=t.width,B=t.height),C<1||B<1)throw new K(`Invalid image width: ${C} or height: ${B}`);this.width=C,this.height=B,this.interpolate=o.get("I","Interpolate"),this.imageMask=o.get("IM","ImageMask")||!1,this.matte=o.get("Matte")||!1;let h=t.bitsPerComponent;if(!h&&(h=o.get("BPC","BitsPerComponent"),!h)){if(!this.imageMask)throw new K(`Bits per component missing in image: ${this.imageMask}`);h=1}if(this.bpc=h,!this.imageMask){let a=o.getRaw("CS")||o.getRaw("ColorSpace");const s=!!a;if(s)this.jpxDecoderOptions?.smaskInData&&(a=oA.get("DeviceRGBA"));else if(this.jpxDecoderOptions)a=oA.get("DeviceRGBA");else switch(t.numComps){case 1:a=oA.get("DeviceGray");break;case 3:a=oA.get("DeviceRGB");break;case 4:a=oA.get("DeviceCMYK");break;default:throw new Error(`Images with ${t.numComps} color components not supported.`)}this.colorSpace=oe.parse({cs:a,xref:A,resources:i?e:null,pdfFunctionFactory:g,localColorSpaceCache:r}),this.numComps=this.colorSpace.numComps,this.jpxDecoderOptions&&(this.jpxDecoderOptions.numComponents=s?this.numComp:0,this.jpxDecoderOptions.isIndexedColormap="Indexed"===this.colorSpace.name)}if(this.decode=o.getArray("D","Decode"),this.needsDecode=!1,this.decode&&(this.colorSpace&&!this.colorSpace.isDefaultDecode(this.decode,h)||n&&!oe.isDefaultDecode(this.decode,1))){this.needsDecode=!0;const A=(1<>3)*t,g=A.byteLength;let r,o;if(!i||a&&n!==g?a?(r=new Uint8Array(n),r.set(A),r.fill(255,g)):r=new Uint8Array(A):r=A,a)for(o=0;o>7&1,n[C+1]=c>>6&1,n[C+2]=c>>5&1,n[C+3]=c>>4&1,n[C+4]=c>>3&1,n[C+5]=c>>2&1,n[C+6]=c>>1&1,n[C+7]=1&c,C+=8;if(C>=1}}else{let t=0;for(c=0,C=0,I=s;C>i;a<0?a=0:a>o&&(a=o),n[C]=a,c&=(1<n[i+1]){e=255;break}}g[I]=e}}}if(g)for(I=0,C=3,c=e*i;I>3,I=e&&Tg.needsToBeResized(t,i);if("DeviceRGBA"===this.colorSpace.name){a.kind=3;const A=a.data=await this.getImageBytes(g*n*4,{});return e?I?Tg.createImage(a,!1):this.createBitmap(3,t,i,A):a}if(!A){let A;if("DeviceGray"===this.colorSpace.name&&1===r?A=1:"DeviceRGB"!==this.colorSpace.name||8!==r||this.needsDecode||(A=2),A&&!this.smask&&!this.mask&&t===n&&i===g){const s=await this.getImageBytes(g*o,{});if(e)return I?Tg.createImage({data:s,kind:A,width:t,height:i,interpolate:this.interpolate},this.needsDecode):this.createBitmap(A,n,g,s);if(a.kind=A,a.data=s,this.needsDecode){N(1===A,"PDFImage.createImageData: The image must be grayscale.");const e=a.data;for(let A=0,t=e.length;A>3,n=await this.getImageBytes(i*s,{internal:!0}),g=this.getComponents(n);let r,o;if(1===a){if(o=t*i,this.needsDecode)for(r=0;r>2,r=new Uint32Array(A.buffer,e,g);if(O.isLittleEndian){for(;n>>24|e<<8|4278190080,t[i+2]=e>>>16|a<<16|4278190080,t[i+3]=a>>>8|4278190080}for(let e=4*n,a=A.length;e>>8|255,t[i+2]=e<<16|a>>>16|255,t[i+3]=a<<8|255}for(let e=4*n,a=A.length;e0&&e.args[0].count++}class nr{static TIME_SLOT_DURATION_MS=20;static CHECK_TIME_EVERY=100;constructor(){this.reset()}check(){return!(++this.checkedc){const A="Image exceeded maximum allowed size and was removed.";if(this.options.ignoreErrors)return void R(A);throw new Error(A)}let C,B,h;if(g.has("OC")&&(C=await this.parseMarkedContentProps(g.get("OC"),A)),g.get("IM","ImageMask")){const A=g.get("I","Interpolate"),t=o+7>>3,n=e.getBytes(t*I),c=g.getArray("D","Decode");if(this.parsingType3Font){if(B=er.createRawMask({imgArray:n,width:o,height:I,imageIsFromDecodeStream:e instanceof Fe,inverseDecode:c?.[0]>0,interpolate:A}),B.cached=!!a,h=[B],i.addImageOps(D,h,C),a){const A={fn:D,args:h,optionalContent:C};s.set(a,r,A),r&&this._regionalImageCache.set(null,r,A)}return}if(B=await er.createMask({imgArray:n,width:o,height:I,imageIsFromDecodeStream:e instanceof Fe,inverseDecode:c?.[0]>0,interpolate:A,isOffscreenCanvasSupported:this.options.isOffscreenCanvasSupported}),B.isSingleOpaquePixel){if(i.addImageOps(90,[],C),a){const A={fn:90,args:[],optionalContent:C};s.set(a,r,A),r&&this._regionalImageCache.set(null,r,A)}return}const Q=`mask_${this.idFactory.createObjId()}`;if(i.addDependency(Q),B.dataLen=B.bitmap?B.width*B.height*4:B.data.length,this._sendImgData(Q,B),h=[{data:Q,width:B.width,height:B.height,interpolate:B.interpolate,count:1}],i.addImageOps(D,h,C),a){const A={objId:Q,fn:D,args:h,optionalContent:C};s.set(a,r,A),r&&this._regionalImageCache.set(null,r,A)}return}if(t&&o+I<200&&!g.has("SMask")&&!g.has("Mask")){try{const a=new er({xref:this.xref,res:A,image:e,isInline:t,pdfFunctionFactory:this._pdfFunctionFactory,localColorSpaceCache:n});B=await a.createImageData(!0,!1),i.isOffscreenCanvasSupported=this.options.isOffscreenCanvasSupported,i.addImageOps(86,[B],C)}catch(A){const e=`Unable to decode inline image: "${A}".`;if(!this.options.ignoreErrors)throw new Error(e);R(e)}return}let Q=`img_${this.idFactory.createObjId()}`,l=!1;if(this.parsingType3Font?Q=`${this.idFactory.getDocId()}_type3_${Q}`:a&&r&&(l=this.globalImageCache.shouldCache(r,this.pageIndex),l&&(N(!t,"Cannot cache an inline image globally."),Q=`${this.idFactory.getDocId()}_${Q}`)),i.addDependency(Q),h=[Q,o,I],i.addImageOps(b,h,C),l){if(this.globalImageCache.hasDecodeFailed(r))return this.globalImageCache.setData(r,{objId:Q,fn:b,args:h,optionalContent:C,byteSize:0}),void this._sendImgData(Q,null,l);if(o*I>25e4||g.has("SMask")||g.has("Mask")){const A=await this.handler.sendWithPromise("commonobj",[Q,"CopyLocalImage",{imageRef:r}]);if(A)return this.globalImageCache.setData(r,{objId:Q,fn:b,args:h,optionalContent:C,byteSize:0}),void this.globalImageCache.addByteSize(r,A)}}if(er.buildImage({xref:this.xref,res:A,image:e,isInline:t,pdfFunctionFactory:this._pdfFunctionFactory,localColorSpaceCache:n}).then((async A=>(B=await A.createImageData(!1,this.options.isOffscreenCanvasSupported),B.dataLen=B.bitmap?B.width*B.height*4:B.data.length,B.ref=r,l&&this.globalImageCache.addByteSize(r,B.dataLen),this._sendImgData(Q,B,l)))).catch((A=>(R(`Unable to decode image "${Q}": "${A}".`),r&&this.globalImageCache.addDecodeFailed(r),this._sendImgData(Q,null,l)))),a){const A={objId:Q,fn:b,args:h,optionalContent:C};s.set(a,r,A),r&&(this._regionalImageCache.set(null,r,A),l&&this.globalImageCache.setData(r,{objId:Q,fn:b,args:h,optionalContent:C,byteSize:0}))}}handleSMask(A,e,t,i,a,s){const n=A.get("G"),g={subtype:A.get("S").name,backdrop:A.get("BC")},r=A.get("TR");if(gg(r)){const A=this._pdfFunctionFactory.create(r),e=new Uint8Array(256),t=new Float32Array(1);for(let i=0;i<256;i++)t[0]=i/255,A(t,0,t,0),e[i]=255*t[0]|0;g.transferMap=e}return this.buildFormXObject(e,n,g,t,i,a.state.clone(),s)}handleTransferFunction(A){let e;if(Array.isArray(A))e=A;else{if(!gg(A))return null;e=[A]}const t=[];let i=0,a=0;for(const A of e){const e=this.xref.fetchIfRef(A);if(i++,lA(e,"Identity")){t.push(null);continue}if(!gg(e))return null;const s=this._pdfFunctionFactory.create(e),n=new Uint8Array(256),g=new Float32Array(1);for(let A=0;A<256;A++)g[0]=A/255,s(g,0,g,0),n[A]=255*g[0]|0;t.push(n),a++}return 1!==i&&4!==i||0===a?null:t}handleTilingType(A,e,t,i,a,s,n,g){const r=new _g,o=CA.merge({xref:this.xref,dictArray:[a.get("Resources"),t]});return this.getOperatorList({stream:i,task:n,resources:o,operatorList:r}).then((function(){const t=r.getIR(),i=en(t,a,e);s.addDependencies(r.dependencies),s.addOp(A,i),a.objId&&g.set(null,a.objId,{operatorListIR:t,dict:a})})).catch((A=>{if(!(A instanceof q)){if(!this.options.ignoreErrors)throw A;R(`handleTilingType - ignoring pattern: "${A}".`)}}))}async handleSetFont(A,e,t,i,a,s,n=null,g=null){const r=e?.[0]instanceof oA?e[0].name:null;let o=await this.loadFont(r,t,A,n,g);if(o.font.isType3Font)try{await o.loadType3Data(this,A,a),i.addDependencies(o.type3Dependencies)}catch(A){o=new rr({loadedName:"g_font_error",font:new Zs(`Type3 font load error: ${A}`),dict:o.font,evaluatorOptions:this.options})}return s.font=o.font,o.send(this.handler),o.loadedName}handleText(A,e){const t=e.font,i=t.charsToGlyphs(A);return t.data&&(4&e.textRenderingMode||"Pattern"===e.fillColorSpace.name||t.disableFontFace||this.options.disableFontFace)&&gr.buildFontPaths(t,i,this.handler,this.options),i}ensureStateFont(A){if(A.font)return;const e=new K("Missing setFont (Tf) operator before text rendering operator.");if(!this.options.ignoreErrors)throw e;R(`ensureStateFont: "${e}".`)}async setGState({resources:A,gState:e,operatorList:t,cacheKey:i,task:a,stateManager:s,localGStateCache:n,localColorSpaceCache:g}){const r=e.objId;let o=!0;const I=[];let c=Promise.resolve();for(const i of e.getKeys()){const n=e.get(i);switch(i){case"Type":break;case"LW":case"LC":case"LJ":case"ML":case"D":case"RI":case"FL":case"CA":case"ca":I.push([i,n]);break;case"Font":o=!1,c=c.then((()=>this.handleSetFont(A,null,n[0],t,a,s.state).then((function(A){t.addDependency(A),I.push([i,[A,n[1]]])}))));break;case"BM":I.push([i,ar(n)]);break;case"SMask":if(lA(n,"None")){I.push([i,!1]);break}n instanceof CA?(o=!1,c=c.then((()=>this.handleSMask(n,A,t,a,s,g))),I.push([i,!0])):R("Unsupported SMask type");break;case"TR":const e=this.handleTransferFunction(n);I.push([i,e]);break;case"OP":case"op":case"OPM":case"BG":case"BG2":case"UCR":case"UCR2":case"TR2":case"HT":case"SM":case"SA":case"AIS":case"TK":S("graphic state operator "+i);break;default:S("Unknown graphic state operator "+i)}}await c,I.length>0&&t.addOp(9,[I]),o&&n.set(i,r,I)}loadFont(A,e,t,i=null,a=null){const s=async()=>new rr({loadedName:"g_font_error",font:new Zs(`Font "${A}" is not available.`),dict:e,evaluatorOptions:this.options});let n;if(e)e instanceof BA&&(n=e);else{const e=t.get("Font");e&&(n=e.getRaw(A))}if(n){if(this.type3FontRefs?.has(n))return s();if(this.fontCache.has(n))return this.fontCache.get(n);try{e=this.xref.fetchIfRef(n)}catch(A){R(`loadFont - lookup failed: "${A}".`)}}if(!(e instanceof CA)){if(!this.options.ignoreErrors&&!this.parsingType3Font)return R(`Font "${A}" is not available.`),s();R(`Font "${A}" is not available -- attempting to fallback to a default font.`),e=i||gr.fallbackFontDict}if(e.cacheKey&&this.fontCache.has(e.cacheKey))return this.fontCache.get(e.cacheKey);const{promise:g,resolve:r}=Promise.withResolvers();let o;try{o=this.preEvaluateFont(e),o.cssFontInfo=a}catch(A){return R(`loadFont - preEvaluateFont failed: "${A}".`),s()}const{descriptor:I,hash:c}=o,C=n instanceof BA;let B;if(c&&I instanceof CA){const A=I.fontAliases||=Object.create(null);if(A[c]){const e=A[c].aliasRef;if(C&&e&&this.fontCache.has(e))return this.fontCache.putAlias(n,e),this.fontCache.get(n)}else A[c]={fontID:this.idFactory.createFontId()};C&&(A[c].aliasRef=n),B=A[c].fontID}else B=this.idFactory.createFontId();return N(B?.startsWith("f"),'The "fontID" must be (correctly) defined.'),C?this.fontCache.put(n,g):(e.cacheKey=`cacheKey_${B}`,this.fontCache.put(e.cacheKey,g)),e.loadedName=`${this.idFactory.getDocId()}_${B}`,this.translateFont(o).then((A=>{r(new rr({loadedName:e.loadedName,font:A,dict:e,evaluatorOptions:this.options}))})).catch((A=>{R(`loadFont - translateFont failed: "${A}".`),r(new rr({loadedName:e.loadedName,font:new Zs(A instanceof Error?A.message:A),dict:e,evaluatorOptions:this.options}))})),g}buildPath(A,e,t,i=!1){const a=A.length-1;if(t||(t=[]),a<0||91!==A.fnArray[a]){let a;switch(i&&(R(`Encountered path operator "${e}" inside of a text object.`),A.addOp(l,null)),e){case 19:const A=t[0]+t[2],e=t[1]+t[3];a=[Math.min(t[0],A),Math.min(t[1],e),Math.max(t[0],A),Math.max(t[1],e)];break;case 13:case 14:a=[t[0],t[1],t[0],t[1]];break;default:a=[1/0,1/0,-1/0,-1/0]}A.addOp(91,[[e],t,a]),i&&A.addOp(E,null)}else{const i=A.argsArray[a];i[0].push(e),i[1].push(...t);const s=i[2];switch(e){case 19:const A=t[0]+t[2],e=t[1]+t[3];s[0]=Math.min(s[0],t[0],A),s[1]=Math.min(s[1],t[1],e),s[2]=Math.max(s[2],t[0],A),s[3]=Math.max(s[3],t[1],e);break;case 13:case 14:s[0]=Math.min(s[0],t[0]),s[1]=Math.min(s[1],t[1]),s[2]=Math.max(s[2],t[0]),s[3]=Math.max(s[3],t[1])}}}parseColorSpace({cs:A,resources:e,localColorSpaceCache:t}){return oe.parseAsync({cs:A,xref:this.xref,resources:e,pdfFunctionFactory:this._pdfFunctionFactory,localColorSpaceCache:t}).catch((A=>{if(A instanceof q)return null;if(this.options.ignoreErrors)return R(`parseColorSpace - ignoring ColorSpace: "${A}".`),null;throw A}))}parseShading({shading:A,resources:e,localColorSpaceCache:t,localShadingPatternCache:i}){let a,s=i.get(A);if(s)return s;try{a=Os.parseShading(A,this.xref,e,this._pdfFunctionFactory,t).getIR()}catch(e){if(e instanceof q)return null;if(this.options.ignoreErrors)return R(`parseShading - ignoring shading: "${e}".`),i.set(A,null),null;throw e}return s=`pattern_${this.idFactory.createObjId()}`,this.parsingType3Font&&(s=`${this.idFactory.getDocId()}_type3_${s}`),i.set(A,s),this.parsingType3Font?this.handler.send("commonobj",[s,"Pattern",a]):this.handler.send("obj",[s,this.pageIndex,"Pattern",a]),s}handleColorN(A,e,t,i,a,s,n,g,r,o){const I=t.pop();if(I instanceof oA){const c=a.getRaw(I.name),C=c instanceof BA&&r.getByRef(c);if(C)try{const a=i.base?i.base.getRgb(t,0):null,s=en(C.operatorListIR,C.dict,a);return void A.addOp(e,s)}catch{}const B=this.xref.fetchIfRef(c);if(B){const a=B instanceof fA?B.dict:B,I=a.get("PatternType");if(1===I){const g=i.base?i.base.getRgb(t,0):null;return this.handleTilingType(e,g,s,B,a,A,n,r)}if(2===I){const t=a.get("Shading"),i=this.parseShading({shading:t,resources:s,localColorSpaceCache:g,localShadingPatternCache:o});if(i){const t=JA(a.getArray("Matrix"),null);A.addOp(e,["Shading",i,t])}return}throw new K(`Unknown PatternType: ${I}`)}}throw new K(`Unknown PatternName: ${I}`)}_parseVisibilityExpression(A,e,t){if(++e>10)return void R("Visibility expression is too deeply nested");const i=A.length,a=this.xref.fetchIfRef(A[0]);if(!(i<2)&&a instanceof oA){switch(a.name){case"And":case"Or":case"Not":t.push(a.name);break;default:return void R(`Invalid operator ${a.name} in visibility expression`)}for(let a=1;a0)return{type:"OCMD",expression:e}}const e=t.get("OCGs");if(Array.isArray(e)||e instanceof CA){const A=[];if(Array.isArray(e))for(const t of e)A.push(t.toString());else A.push(e.objId);return{type:i,ids:A,policy:t.get("P")instanceof oA?t.get("P").name:null,expression:null}}if(e instanceof BA)return{type:i,id:e.toString()}}return null}getOperatorList({stream:A,task:e,resources:t,operatorList:i,initialState:a=null,fallbackFontDict:s=null}){if(t||=CA.empty,a||=new cr,!i)throw new Error('getOperatorList: missing "operatorList" parameter');const n=this,g=this.xref;let r=!1;const o=new zn,I=new _n,c=new Ag,C=new eg,B=new Map,h=t.get("XObject")||CA.empty,Q=t.get("Pattern")||CA.empty,l=new or(a),u=new Cr(A,g,l),w=new nr;function D(A){for(let A=0,e=u.savedStatesDepth;A0&&i.addOp(9,[e]),A=null;continue}}return void b(new Promise((function(A,a){if(!M)throw new K("GState must be referred to by name.");const s=t.get("ExtGState");if(!(s instanceof CA))throw new K("ExtGState should be a dictionary.");const g=s.get(U);if(!(g instanceof CA))throw new K("GState should be a dictionary.");n.setGState({resources:t,gState:g,operatorList:i,cacheKey:U,task:e,stateManager:l,localGStateCache:c,localColorSpaceCache:I}).then(A,a)})).catch((function(A){if(!(A instanceof q)){if(!n.options.ignoreErrors)throw A;R(`getOperatorList - ignoring ExtGState: "${A}".`)}})));case 13:case 14:case 15:case 16:case 17:case 18:case 19:n.buildPath(i,a,A,r);continue;case 67:case 68:case 72:case 73:continue;case y:if(!(A[0]instanceof oA)){R(`Expected name for beginMarkedContentProps arg0=${A[0]}`),i.addOp(y,["OC",null]);continue}if("OC"===A[0].name)return void b(n.parseMarkedContentProps(A[1],t).then((A=>{i.addOp(y,["OC",A])})).catch((A=>{if(!(A instanceof q)){if(n.options.ignoreErrors)return R(`getOperatorList - ignoring beginMarkedContentProps: "${A}".`),void i.addOp(y,["OC",null]);throw A}})));A=[A[0].name,A[1]instanceof CA?A[1].get("MCID"):null];break;default:if(null!==A){for(G=0,N=A.length;G{if(!(A instanceof q)){if(this.options.ignoreErrors)return R(`getOperatorList - ignoring errors during "${e.name}" task: "${A}".`),void D();throw A}}))}getTextContent({stream:A,task:e,resources:t,stateManager:s=null,includeMarkedContent:n=!1,sink:g,seenStyles:r=new Set,viewBox:o,lang:I=null,markedContentData:c=null,disableNormalization:C=!1,keepWhiteSpace:B=!1}){t||=CA.empty,s||=new or(new Ir),n&&(c||={level:0});const h={items:[],styles:Object.create(null),lang:I},Q={initialized:!1,str:[],totalWidth:0,totalHeight:0,width:0,height:0,vertical:!1,prevTransform:null,textAdvanceScale:0,spaceInFlowMin:0,spaceInFlowMax:0,trackingSpaceMin:1/0,negativeSpaceMax:-1/0,notASpace:-1/0,transform:null,fontName:null,hasEOL:!1},l=[" "," "];let u=0;function p(A){const e=(u+1)%2,t=" "!==l[u]&&" "===l[e];return l[u]=A,u=e,!B&&t}function m(){return!B&&" "!==l[u]&&" "===l[(u+1)%2]}function D(){l[0]=l[1]=" ",u=0}const b=this,k=this.xref,F=[];let S=null;const G=new zn,N=new Ag,x=new Cr(A,k,s);let U;function M({width:A=0,height:e=0,transform:t=Q.prevTransform,fontName:i=Q.fontName}){h.items.push({str:" ",dir:"ltr",width:A,height:e,transform:t,fontName:i,hasEOL:!1})}function L(){const A=U.font,e=[U.fontSize*U.textHScale,0,0,U.fontSize,0,U.textRise];if(A.isType3Font&&(U.fontSize<=1||A.isCharBBox)&&!AA(U.fontMatrix,a)){const t=A.bbox[3]-A.bbox[1];t>0&&(e[3]*=t*U.fontMatrix[3])}return V.transform(U.ctm,V.transform(U.textMatrix,e))}function J(){if(Q.initialized)return Q;const{font:A,loadedName:e}=U;if(!r.has(e)&&(r.add(e),h.styles[e]={fontFamily:A.fallbackName,ascent:A.ascent,descent:A.descent,vertical:A.vertical},b.options.fontExtraProperties&&A.systemFontInfo)){const t=h.styles[e];t.fontSubstitution=A.systemFontInfo.css,t.fontSubstitutionLoadedName=A.systemFontInfo.loadedName}Q.fontName=e;const t=Q.transform=L();A.vertical?(Q.width=Q.totalWidth=Math.hypot(t[0],t[1]),Q.height=Q.totalHeight=0,Q.vertical=!0):(Q.width=Q.totalWidth=0,Q.height=Q.totalHeight=Math.hypot(t[2],t[3]),Q.vertical=!1);const i=Math.hypot(U.textLineMatrix[0],U.textLineMatrix[1]),a=Math.hypot(U.ctm[0],U.ctm[1]);Q.textAdvanceScale=a*i;const{fontSize:s}=U;return Q.trackingSpaceMin=.102*s,Q.notASpace=.03*s,Q.negativeSpaceMax=-.2*s,Q.spaceInFlowMin=.102*s,Q.spaceInFlowMax=.6*s,Q.hasEOL=!1,Q.initialized=!0,Q}function H(){if(!Q.initialized)return;const A=Math.hypot(U.textLineMatrix[0],U.textLineMatrix[1]),e=Math.hypot(U.ctm[0],U.ctm[1])*A;e!==Q.textAdvanceScale&&(Q.vertical?(Q.totalHeight+=Q.height*Q.textAdvanceScale,Q.height=0):(Q.totalWidth+=Q.width*Q.textAdvanceScale,Q.width=0),Q.textAdvanceScale=e)}async function Y(A,i){const s=await b.loadFont(A,i,t);if(s.font.isType3Font)try{await s.loadType3Data(b,t,e)}catch{}U.loadedName=s.loadedName,U.font=s.font,U.fontMatrix=s.font.fontMatrix||a}function v(A,e,t){const i=Math.hypot(t[0],t[1]);return[(t[0]*A+t[1]*e)/i,(t[2]*A+t[3]*e)/i]}function T(A){const e=L();let t=e[4],i=e[5];if(U.font?.vertical){if(to[2]||i+Ao[3])return!1}else if(t+Ao[2]||io[3])return!1;if(!U.font||!Q.prevTransform)return!0;let a=Q.prevTransform[4],s=Q.prevTransform[5];if(a===t&&s===i)return!0;let n=-1;switch(e[0]&&0===e[1]&&0===e[2]?n=e[0]>0?0:180:e[1]&&0===e[0]&&0===e[3]&&(n=e[1]>0?90:270),n){case 0:break;case 90:[t,i]=[i,t],[a,s]=[s,a];break;case 180:[t,i,a,s]=[-t,-i,-a,-s];break;case 270:[t,i]=[-i,-t],[a,s]=[-s,-a];break;default:[t,i]=v(t,i,e),[a,s]=v(a,s,Q.prevTransform)}if(U.font.vertical){const A=(s-i)/Q.textAdvanceScale,e=t-a,n=Math.sign(Q.height);return A.5*Q.width?(W(),!0):(D(),O(),!0):Math.abs(e)>Q.width?(W(),!0):(A<=n*Q.notASpace&&D(),A<=n*Q.trackingSpaceMin?m()?(D(),O(),M({height:Math.abs(A)})):Q.height+=A:Z(A,Q.prevTransform,n)||(0===Q.str.length?(D(),M({height:Math.abs(A)})):Q.height+=A),Math.abs(e)>.25*Q.width&&O(),!0)}const g=(t-a)/Q.textAdvanceScale,r=i-s,I=Math.sign(Q.width);return g.5*Q.height?(W(),!0):(D(),O(),!0):Math.abs(r)>Q.height?(W(),!0):(g<=I*Q.notASpace&&D(),g<=I*Q.trackingSpaceMin?m()?(D(),O(),M({width:Math.abs(g)})):Q.width+=g:Z(g,Q.prevTransform,I)||(0===Q.str.length?(D(),M({width:Math.abs(g)})):Q.width+=g),Math.abs(r)>.25*Q.height&&O(),!0)}function P({chars:A,extraSpacing:e}){const t=U.font;if(!A){const A=U.charSpacing+e;return A&&(t.vertical?U.translateTextMatrix(0,-A):U.translateTextMatrix(A*U.textHScale,0)),void(B&&T(0))}const i=t.charsToGlyphs(A),a=U.fontMatrix[0]*U.fontSize;for(let A=0,s=i.length;Ae?e.normalize("NFKC"):iA.get(t))));const i=xg(e,-1,A.vertical);return{str:i.str,dir:i.dir,width:Math.abs(A.totalWidth),height:Math.abs(A.totalHeight),transform:A.transform,fontName:A.fontName,hasEOL:A.hasEOL}}(Q)),Q.initialized=!1,Q.str.length=0)}function X(A=!1){const e=h.items.length;0!==e&&(A&&e<10||(g.enqueue(h,e),h.items=[],h.styles=Object.create(null)))}const j=new nr;return new Promise((function A(a,Q){const l=function(e){X(!0),Promise.all([e,g.ready]).then((function(){try{A(a,Q)}catch(A){Q(A)}}),Q)};e.ensureNotTerminated(),j.reset();const u={};let p,m=[];for(;!(p=j.check())&&(m.length=0,u.args=m,x.read(u));){const A=U;U=s.state;const a=u.fn;switch(m=u.args,0|a){case d:var D=m[0].name,M=m[1];if(U.font&&D===U.fontName&&M===U.fontSize)break;return O(),U.fontName=D,U.fontSize=M,void l(Y(D,null));case 39:U.textRise=m[0];break;case 35:U.textHScale=m[0]/100;break;case 36:U.leading=m[0];break;case 40:U.translateTextLineMatrix(m[0],m[1]),U.textMatrix=U.textLineMatrix.slice();break;case 41:U.leading=-m[1],U.translateTextLineMatrix(m[0],m[1]),U.textMatrix=U.textLineMatrix.slice();break;case 43:U.carriageReturn();break;case 42:U.setTextMatrix(m[0],m[1],m[2],m[3],m[4],m[5]),U.setTextLineMatrix(m[0],m[1],m[2],m[3],m[4],m[5]),H();break;case 33:U.charSpacing=m[0];break;case 34:U.wordSpacing=m[0];break;case 31:U.textMatrix=i.slice(),U.textLineMatrix=i.slice();break;case 45:if(!s.state.font){b.ensureStateFont(s.state);continue}const a=(U.font.vertical?1:-1)*U.fontSize/1e3,Q=m[0];for(let A=0,e=Q.length;A0){const A=F.join("");F.length=0,P({chars:A,extraSpacing:0})}break;case f:if(!s.state.font){b.ensureStateFont(s.state);continue}P({chars:m[0],extraSpacing:0});break;case 46:if(!s.state.font){b.ensureStateFont(s.state);continue}U.carriageReturn(),P({chars:m[0],extraSpacing:0});break;case 47:if(!s.state.font){b.ensureStateFont(s.state);continue}U.wordSpacing=m[0],U.charSpacing=m[1],U.carriageReturn(),P({chars:m[2],extraSpacing:0});break;case 66:O(),S||(S=t.get("XObject")||CA.empty);var L=m[0]instanceof oA,J=m[0].name;if(L&&G.getByName(J))break;return void l(new Promise((function(A,i){if(!L)throw new K("XObject must be referred to by name.");let a=S.getRaw(J);if(a instanceof BA){if(G.getByRef(a))return void A();if(b.globalImageCache.getData(a,b.pageIndex))return void A();a=k.fetch(a)}if(!(a instanceof fA))throw new K("XObject should be a stream");const h=a.dict.get("Subtype");if(!(h instanceof oA))throw new K("XObject should have a Name subtype");if("Form"!==h.name)return G.set(J,a.dict.objId,!0),void A();const Q=s.state.clone(),l=new or(Q),E=JA(a.dict.getArray("Matrix"),null);E&&l.transform(E),X();const u={enqueueInvoked:!1,enqueue(A,e){this.enqueueInvoked=!0,g.enqueue(A,e)},get desiredSize(){return g.desiredSize},get ready(){return g.ready}};b.getTextContent({stream:a,task:e,resources:a.dict.get("Resources")||t,stateManager:l,includeMarkedContent:n,sink:u,seenStyles:r,viewBox:o,lang:I,markedContentData:c,disableNormalization:C,keepWhiteSpace:B}).then((function(){u.enqueueInvoked||G.set(J,a.dict.objId,!0),A()}),i)})).catch((function(A){if(!(A instanceof q)){if(!b.options.ignoreErrors)throw A;R(`getTextContent - ignoring XObject: "${A}".`)}})));case 9:if(L=m[0]instanceof oA,J=m[0].name,L&&N.getByName(J))break;return void l(new Promise((function(A,e){if(!L)throw new K("GState must be referred to by name.");const i=t.get("ExtGState");if(!(i instanceof CA))throw new K("ExtGState should be a dictionary.");const a=i.get(J);if(!(a instanceof CA))throw new K("GState should be a dictionary.");const s=a.get("Font");if(!s)return N.set(J,a.objId,!0),void A();O(),U.fontName=null,U.fontSize=s[1],Y(null,s[0]).then(A,e)})).catch((function(A){if(!(A instanceof q)){if(!b.options.ignoreErrors)throw A;R(`getTextContent - ignoring ExtGState: "${A}".`)}})));case 69:O(),n&&(c.level++,h.items.push({type:"beginMarkedContent",tag:m[0]instanceof oA?m[0].name:null}));break;case y:if(O(),n){c.level++;let A=null;m[1]instanceof CA&&(A=m[1].get("MCID")),h.items.push({type:"beginMarkedContentProps",id:Number.isInteger(A)?`${b.idFactory.getPageObjId()}_mc${A}`:null,tag:m[0]instanceof oA?m[0].name:null})}break;case w:if(O(),n){if(0===c.level)break;c.level--,h.items.push({type:"endMarkedContent"})}break;case E:!A||A.font===U.font&&A.fontSize===U.fontSize&&A.fontName===U.fontName||O()}if(h.items.length>=g.desiredSize){p=!0;break}}p?l(ir):(O(),X(),a())})).catch((A=>{if(!(A instanceof q)){if(this.options.ignoreErrors)return R(`getTextContent - ignoring errors during "${e.name}" task: "${A}".`),O(),void X();throw A}}))}async extractDataStructures(A,e){const t=this.xref;let i;const a=this.readToUnicode(e.toUnicode);if(e.composite){const t=A.get("CIDSystemInfo");t instanceof CA&&(e.cidSystemInfo={registry:z(t.get("Registry")),ordering:z(t.get("Ordering")),supplement:t.get("Supplement")});try{const e=A.get("CIDToGIDMap");e instanceof fA&&(i=e.getBytes())}catch(A){if(!this.options.ignoreErrors)throw A;R(`extractDataStructures - ignoring CIDToGIDMap data: "${A}".`)}}const s=[];let n,g=null;if(A.has("Encoding")){if(n=A.get("Encoding"),n instanceof CA){if(g=n.get("BaseEncoding"),g=g instanceof oA?g.name:null,n.has("Differences")){const A=n.get("Differences");let e=0;for(const i of A){const A=t.fetchIfRef(i);if("number"==typeof A)e=A;else{if(!(A instanceof oA))throw new K(`Invalid entry in 'Differences' array: ${A}`);s[e++]=A.name}}}}else if(n instanceof oA)g=n.name;else{const A="Encoding is not a Name nor a Dict";if(!this.options.ignoreErrors)throw new K(A);R(A)}"MacRomanEncoding"!==g&&"MacExpertEncoding"!==g&&"WinAnsiEncoding"!==g&&(g=null)}const r=!e.file||e.isInternalFont,o=da()[e.name];if(g&&r&&o&&(g=null),g)e.defaultEncoding=Mi(g);else{const A=!!(4&e.flags),t=!!(32&e.flags);n=Gi,"TrueType"!==e.type||t||(n=Ni),(A||o)&&(n=Ri,r&&(/Symbol/i.test(e.name)?n=xi:/Dingbats/i.test(e.name)?n=Ui:/Wingdings/i.test(e.name)&&(n=Ni))),e.defaultEncoding=n}e.differences=s,e.baseEncodingName=g,e.hasEncoding=!!g||s.length>0,e.dict=A,e.toUnicode=await a;const I=await this.buildToUnicode(e);return e.toUnicode=I,i&&(e.cidToGidMap=this.readCidToGidMap(i,I)),e}_simpleFontToUnicode(A,e=!1){N(!A.composite,"Must be a simple font.");const t=[],i=A.defaultEncoding.slice(),a=A.baseEncodingName,s=A.differences;for(const A in s){const e=s[A];".notdef"!==e&&(i[A]=e)}const n=ea();for(const s in i){let g=i[s];if(""===g)continue;let r=n[g];if(void 0!==r){t[s]=String.fromCharCode(r);continue}let o=0;switch(g[0]){case"G":3===g.length&&(o=parseInt(g.substring(1),16));break;case"g":5===g.length&&(o=parseInt(g.substring(1),16));break;case"C":case"c":if(g.length>=3&&g.length<=4){const t=g.substring(1);if(e){o=parseInt(t,16);break}if(o=+t,Number.isNaN(o)&&Number.isInteger(parseInt(t,16)))return this._simpleFontToUnicode(A,!0)}break;case"u":r=aa(g,n),-1!==r&&(o=r);break;default:switch(g){case"f_h":case"f_t":case"T_h":t[s]=g.replaceAll("_","");continue}}if(o>0&&o<=1114111&&Number.isInteger(o)){if(a&&o===+s){const A=Mi(a);if(A&&(g=A[s])){t[s]=String.fromCharCode(n[g]);continue}}t[s]=String.fromCodePoint(o)}}return t}async buildToUnicode(A){if(A.hasIncludedToUnicodeMap=A.toUnicode?.length>0,A.hasIncludedToUnicodeMap)return!A.composite&&A.hasEncoding&&(A.fallbackToUnicode=this._simpleFontToUnicode(A)),A.toUnicode;if(!A.composite)return new Da(this._simpleFontToUnicode(A));if(A.composite&&(A.cMap.builtInCMap&&!(A.cMap instanceof Ii)||"Adobe"===A.cidSystemInfo?.registry&&("GB1"===A.cidSystemInfo.ordering||"CNS1"===A.cidSystemInfo.ordering||"Japan1"===A.cidSystemInfo.ordering||"Korea1"===A.cidSystemInfo.ordering))){const{registry:e,ordering:t}=A.cidSystemInfo,i=oA.get(`${e}-${t}-UCS2`),a=await wi.create({encoding:i,fetchBuiltInCMap:this._fetchBuiltInCMapBound,useCMap:null}),s=[],n=[];return A.cMap.forEach((function(A,e){if(e>65535)throw new K("Max size of CID is 65,535");const t=a.lookup(e);if(t){n.length=0;for(let A=0,e=t.length;A>1;(0!==a||e.has(s))&&(t[s]=a)}return t}extractWidths(A,e,t){const i=this.xref;let a=[],s=0;const n=[];let g;if(t.composite){const e=A.get("DW");s="number"==typeof e?Math.ceil(e):1e3;const r=A.get("W");if(Array.isArray(r))for(let A=0,e=r.length;A{const e=r.get(A),a=new _g;return i.getOperatorList({stream:e,task:t,resources:o,operatorList:a}).then((()=>{49===a.fnArray[0]&&this._removeType3ColorOperators(a,h),I[A]=a.getIR();for(const A of a.dependencies)n.add(A)})).catch((function(e){R(`Type3 font resource "${A}" is not available.`);const t=new _g;I[A]=t.getIR()}))}));return this.type3Loaded=g.then((()=>{s.charProcOperatorList=I,this._bbox&&(s.isCharBBox=!0,s.bbox=this._bbox)})),this.type3Loaded}_removeType3ColorOperators(A,e=NaN){const t=V.normalizeRect(A.argsArray[0].slice(2)),i=t[2]-t[0],a=t[3]-t[1],s=Math.hypot(i,a);0===i||0===a?(A.fnArray.splice(0,1),A.argsArray.splice(0,1)):(0===e||Math.round(s/e)>=10)&&(this._bbox||(this._bbox=[1/0,1/0,-1/0,-1/0]),this._bbox[0]=Math.min(this._bbox[0],t[0]),this._bbox[1]=Math.min(this._bbox[1],t[1]),this._bbox[2]=Math.max(this._bbox[2],t[2]),this._bbox[3]=Math.max(this._bbox[3],t[3]));let n=0,g=A.length;for(;n=13&&s<=28,a.variableArgs)g>n&&S(`Command ${i}: expected [0, ${n}] args, but received ${g} args.`);else{if(g!==n){const A=this.nonProcessedArgs;for(;g>n;)A.push(e.shift()),g--;for(;gCr.MAX_INVALID_PATH_OPS)throw new K(`Invalid ${A}`);R(`Skipping ${A}`),null!==e&&(e.length=0);continue}}return this.preprocessCommand(s,e),A.fn=s,A.args=e,!0}if(t===sA)return!1;if(null!==t&&(null===e&&(e=[]),e.push(t),e.length>33))throw new K("Too many arguments")}}preprocessCommand(A,e){switch(0|A){case l:this.stateManager.save();break;case E:this.stateManager.restore();break;case u:this.stateManager.transform(e)}}}class Br extends Cr{constructor(A){super(new se(A))}parse(){const A={fn:0,args:[]},e={fontSize:0,fontName:"",fontColor:new Uint8ClampedArray(3)};try{for(;A.args.length=0,this.read(A);){if(0!==this.savedStatesDepth)continue;const{fn:t,args:i}=A;switch(0|t){case d:const[A,t]=i;A instanceof oA&&(e.fontName=A.name),"number"==typeof t&&t>0&&(e.fontSize=t);break;case m:oe.singletons.rgb.getRgbItem(i,0,e.fontColor,0);break;case 57:oe.singletons.gray.getRgbItem(i,0,e.fontColor,0);break;case 61:oe.singletons.cmyk.getRgbItem(i,0,e.fontColor,0)}}}catch(A){R(`parseDefaultAppearance - ignoring errors: "${A}".`)}return e}}function hr(A){return new Br(A).parse()}class Qr extends Cr{constructor(A,e,t){super(A),this.stream=A,this.evaluatorOptions=e,this.xref=t,this.resources=A.dict?.get("Resources")}parse(){const A={fn:0,args:[]};let e={scaleFactor:1,fontSize:0,fontName:"",fontColor:new Uint8ClampedArray(3),fillColorSpace:oe.singletons.gray},t=!1;const i=[];try{for(;A.args.length=0,!t&&this.read(A);){const{fn:a,args:s}=A;switch(0|a){case l:i.push({scaleFactor:e.scaleFactor,fontSize:e.fontSize,fontName:e.fontName,fontColor:e.fontColor.slice(),fillColorSpace:e.fillColorSpace});break;case E:e=i.pop()||e;break;case 42:e.scaleFactor*=Math.hypot(s[0],s[1]);break;case d:const[A,a]=s;A instanceof oA&&(e.fontName=A.name),"number"==typeof a&&a>0&&(e.fontSize=a*e.scaleFactor);break;case 51:e.fillColorSpace=oe.parse({cs:s[0],xref:this.xref,resources:this.resources,pdfFunctionFactory:this._pdfFunctionFactory,localColorSpaceCache:this._localColorSpaceCache});break;case 54:e.fillColorSpace.getRgbItem(s,0,e.fontColor,0);break;case m:oe.singletons.rgb.getRgbItem(s,0,e.fontColor,0);break;case 57:oe.singletons.gray.getRgbItem(s,0,e.fontColor,0);break;case 61:oe.singletons.cmyk.getRgbItem(s,0,e.fontColor,0);break;case f:case 45:case 46:case 47:t=!0}}}catch(A){R(`parseAppearanceStream - ignoring errors: "${A}".`)}return this.stream.reset(),delete e.scaleFactor,delete e.fillColorSpace,e}get _localColorSpaceCache(){return U(this,"_localColorSpaceCache",new _n)}get _pdfFunctionFactory(){return U(this,"_pdfFunctionFactory",new ag({xref:this.xref,isEvalSupported:this.evaluatorOptions.isEvalSupported}))}}function lr(A,e){return A[0]===A[1]&&A[1]===A[2]?`${zA(A[0]/255)} ${e?"g":"G"}`:Array.from(A,(A=>zA(A/255))).join(" ")+" "+(e?"rg":"RG")}class Er{constructor(A,e){this.xref=A,this.widths=null,this.firstChar=1/0,this.lastChar=-1/0,this.fontFamily=e;const t=new OffscreenCanvas(1,1);this.ctxMeasure=t.getContext("2d",{willReadFrequently:!0}),Er._fontNameId||(Er._fontNameId=1),this.fontName=oA.get(`InvalidPDFjsFont_${e}_${Er._fontNameId++}`)}get fontDescriptorRef(){if(!Er._fontDescriptorRef){const A=new CA(this.xref);A.set("Type",oA.get("FontDescriptor")),A.set("FontName",this.fontName),A.set("FontFamily","MyriadPro Regular"),A.set("FontBBox",[0,0,0,0]),A.set("FontStretch",oA.get("Normal")),A.set("FontWeight",400),A.set("ItalicAngle",0),Er._fontDescriptorRef=this.xref.getNewPersistentRef(A)}return Er._fontDescriptorRef}get descendantFontRef(){const A=new CA(this.xref);A.set("BaseFont",this.fontName),A.set("Type",oA.get("Font")),A.set("Subtype",oA.get("CIDFontType0")),A.set("CIDToGIDMap",oA.get("Identity")),A.set("FirstChar",this.firstChar),A.set("LastChar",this.lastChar),A.set("FontDescriptor",this.fontDescriptorRef),A.set("DW",1e3);const e=[],t=[...this.widths.entries()].sort();let i=null,a=null;for(const[A,s]of t)i?A===i+a.length?a.push(s):(e.push(i,a),i=A,a=[s]):(i=A,a=[s]);i&&e.push(i,a),A.set("W",e);const s=new CA(this.xref);return s.set("Ordering","Identity"),s.set("Registry","Adobe"),s.set("Supplement",0),A.set("CIDSystemInfo",s),this.xref.getNewPersistentRef(A)}get baseFontRef(){const A=new CA(this.xref);return A.set("BaseFont",this.fontName),A.set("Type",oA.get("Font")),A.set("Subtype",oA.get("Type0")),A.set("Encoding",oA.get("Identity-H")),A.set("DescendantFonts",[this.descendantFontRef]),A.set("ToUnicode",oA.get("Identity-H")),this.xref.getNewPersistentRef(A)}get resources(){const A=new CA(this.xref),e=new CA(this.xref);return e.set(this.fontName.name,this.baseFontRef),A.set("Font",e),A}_createContext(){return this.widths=new Map,this.ctxMeasure.font=`1000px ${this.fontFamily}`,this.ctxMeasure}createFontResources(A){const e=this._createContext();for(const t of A.split(/\r\n?|\n/))for(const A of t.split("")){const t=A.charCodeAt(0);if(this.widths.has(t))continue;const i=e.measureText(A),a=Math.ceil(i.width);this.widths.set(t,a),this.firstChar=Math.min(t,this.firstChar),this.lastChar=Math.max(t,this.lastChar)}return this.resources}static getFirstPositionInfo(A,e,t){const[i,a,n,g]=A;let r=n-i,o=g-a;e%180!=0&&([r,o]=[o,r]);const I=s*t;return{coords:[0,o+.35*t-I],bbox:[0,0,r,o],matrix:0!==e?te(e,o,I):void 0}}createAppearance(A,e,t,i,a,n){const g=this._createContext(),r=[];let o=-1/0;for(const e of A.split(/\r\n?|\n/)){r.push(e);const A=g.measureText(e).width;o=Math.max(o,A);for(const A of ZA(e)){const e=String.fromCodePoint(A);let t=this.widths.get(A);if(void 0===t){const i=g.measureText(e);t=Math.ceil(i.width),this.widths.set(A,t),this.firstChar=Math.min(A,this.firstChar),this.lastChar=Math.max(A,this.lastChar)}}}o*=i/1e3;const[I,c,C,B]=e;let h=C-I,Q=B-c;t%180!=0&&([h,Q]=[Q,h]);let l=1;o>h&&(l=h/o);let E=1;const u=s*i,d=.35*i,f=u*r.length;f>Q&&(E=Q/f);const p=i*Math.min(l,E),m=["q",`0 0 ${zA(h)} ${zA(Q)} re W n`,"BT",`1 0 0 1 0 ${zA(Q+d)} Tm 0 Tc ${lr(a,!0)}`,`/${this.fontName.name} ${zA(p)} Tf`],{resources:y}=this;if(1!==(n="number"==typeof n&&n>=0&&n<=1?n:1)){m.push("/R0 gs");const A=new CA(this.xref),e=new CA(this.xref);e.set("ca",n),e.set("CA",n),e.set("Type",oA.get("ExtGState")),A.set("R0",e),y.set("ExtGState",A)}const w=zA(u);for(const A of r)m.push(`0 -${w} Td <${Ae(A)}> Tj`);m.push("ET","Q");const D=m.join("\n"),b=new CA(this.xref);if(b.set("Subtype",oA.get("Form")),b.set("Type",oA.get("XObject")),b.set("BBox",[0,0,h,Q]),b.set("Length",D.length),b.set("Resources",y),t){const A=te(t,h,Q);b.set("Matrix",A)}const k=new se(D);return k.dict=b,k}}class ur{constructor(A,e,t){this.root=A,this.xref=e,this._type=t}getAll(){const A=new Map;if(!this.root)return A;const e=this.xref,t=new hA;t.put(this.root);const i=[this.root];for(;i.length>0;){const a=e.fetchIfRef(i.shift());if(!(a instanceof CA))continue;if(a.has("Kids")){const A=a.get("Kids");if(!Array.isArray(A))continue;for(const e of A){if(t.has(e))throw new K(`Duplicate entry in "${this._type}" tree.`);i.push(e),t.put(e)}continue}const s=a.get(this._type);if(Array.isArray(s))for(let t=0,i=s.length;t10)return R(`Search depth limit reached for "${this._type}" tree.`),null;const a=t.get("Kids");if(!Array.isArray(a))return null;let s=0,n=a.length-1;for(;s<=n;){const i=s+n>>1,g=e.fetchIfRef(a[i]),r=g.get("Limits");if(Ae.fetchIfRef(r[1]))){t=g;break}s=i+1}}if(s>n)return null}const a=t.get(this._type);if(Array.isArray(a)){let t=0,i=a.length-2;for(;t<=i;){const s=t+i>>1,n=s+(1&s),g=e.fetchIfRef(a[n]);if(Ag))return a[n+1];t=n+2}}}return null}get(A){return this.xref.fetchIfRef(this.getRaw(A))}}class dr extends ur{constructor(A,e){super(A,e,"Names")}}class fr extends ur{constructor(A,e){super(A,e,"Nums")}}function pr(){zs=Object.create(null),nA=Object.create(null),gA=Object.create(null),rA=Object.create(null),ra.clear(),zt.cleanup()}function mr(A){return A instanceof CA?A.has("UF")?A.get("UF"):A.has("F")?A.get("F"):A.has("Unix")?A.get("Unix"):A.has("Mac")?A.get("Mac"):A.has("DOS")?A.get("DOS"):null:null}class yr{#F=!1;constructor(A,e,t=!1){A instanceof CA&&(this.xref=e,this.root=A,A.has("FS")&&(this.fs=A.get("FS")),A.has("RF")&&R("Related file specifications are not supported"),t||(A.has("EF")?this.#F=!0:R("Non-embedded file specifications are not supported")))}get filename(){let A="";const e=mr(this.root);return e&&"string"==typeof e&&(A=z(e).replaceAll("\\\\","\\").replaceAll("\\/","/").replaceAll("\\","/")),U(this,"filename",A||"unnamed")}get content(){if(!this.#F)return null;this._contentRef||=mr(this.root?.get("EF"));let A=null;if(this._contentRef){const e=this.xref.fetchIfRef(this._contentRef);e instanceof fA?A=e.getBytes():R("Embedded file specification points to non-existing/invalid content")}else R("Embedded file specification does not have any content");return A}get description(){let A="";const e=this.root?.get("Desc");return e&&"string"==typeof e&&(A=z(e)),U(this,"description",A)}get serializable(){return{rawFilename:this.filename,filename:(A=this.filename,A.substring(A.lastIndexOf("/")+1)),content:this.content,description:this.description};var A}}function wr(A,e){const t=A[e];return" "===t||"\n"===t||"\r"===t||"\t"===t}class Dr{_resolveEntities(A){return A.replaceAll(/&([^;]+);/g,((A,e)=>{if("#x"===e.substring(0,2))return String.fromCodePoint(parseInt(e.substring(2),16));if("#"===e.substring(0,1))return String.fromCodePoint(parseInt(e.substring(1),10));switch(e){case"lt":return"<";case"gt":return">";case"amp":return"&";case"quot":return'"';case"apos":return"'"}return this.onResolveEntity(e)}))}_parseContent(A,e){const t=[];let i=e;function a(){for(;i"!==A[i]&&"/"!==A[i];)++i;const s=A.substring(e,i);for(a();i"!==A[i]&&"/"!==A[i]&&"?"!==A[i];){a();let e="",s="";for(;i"!==A[t]&&"?"!==A[t]&&"/"!==A[t];)++t;const i=A.substring(e,t);!function(){for(;t"!==A[t+1]);)++t;return{name:i,value:A.substring(a,t),parsed:t-e}}parseXml(A){let e=0;for(;e",t),e<0)return void this.onError(-9);this.onEndElement(A.substring(t,e)),t=e+1;break;case"?":++t;const i=this._parseProcessingInstruction(A,t);if("?>"!==A.substring(t+i.parsed,t+i.parsed+2))return void this.onError(-3);this.onPi(i.name,i.value),t+=i.parsed+2;break;case"!":if("--"===A.substring(t+1,t+3)){if(e=A.indexOf("--\x3e",t+3),e<0)return void this.onError(-5);this.onComment(A.substring(t+3,e)),t=e+3}else if("[CDATA["===A.substring(t+1,t+8)){if(e=A.indexOf("]]>",t+8),e<0)return void this.onError(-2);this.onCdata(A.substring(t+8,e)),t=e+3}else{if("DOCTYPE"!==A.substring(t+1,t+8))return void this.onError(-6);{const i=A.indexOf("[",t+8);let a=!1;if(e=A.indexOf(">",t+8),e<0)return void this.onError(-4);if(i>0&&e>i){if(e=A.indexOf("]>",t+8),e<0)return void this.onError(-4);a=!0}const s=A.substring(t+8,e+(a?1:0));this.onDoctype(s),t=e+(a?2:1)}}break;default:const a=this._parseContent(A,t);if(null===a)return void this.onError(-6);let s=!1;if("/>"===A.substring(t+a.parsed,t+a.parsed+2))s=!0;else if(">"!==A.substring(t+a.parsed,t+a.parsed+1))return void this.onError(-9);this.onBeginElement(a.name,a.attributes,s),t+=a.parsed+(s?2:1)}}else{for(;t0}searchNode(A,e){if(e>=A.length)return this;const t=A[e];if(t.name.startsWith("#")&&e0)i.push([a,0]),a=a.childNodes[0];else{if(0===i.length)return null;for(;0!==i.length;){const[A,e]=i.pop(),t=e+1;if(t");for(const e of this.childNodes)e.dump(A);A.push(``)}else this.nodeValue?A.push(`>${OA(this.nodeValue)}`):A.push("/>")}else A.push(OA(this.nodeValue))}}class kr extends Dr{constructor({hasAttributes:A=!1,lowerCaseName:e=!1}){super(),this._currentFragment=null,this._stack=null,this._errorCode=0,this._hasAttributes=A,this._lowerCaseName=e}parseFromString(A){if(this._currentFragment=[],this._stack=[],this._errorCode=0,this.parseXml(A),0!==this._errorCode)return;const[e]=this._currentFragment;return e?{documentElement:e}:void 0}onText(A){if(function(A){for(let e=0,t=A.length;e\\376\\377([^<]+)/g,(function(A,e){const t=e.replaceAll(/\\([0-3])([0-7])([0-7])/g,(function(A,e,t,i){return String.fromCharCode(64*e+8*t+1*i)})).replaceAll(/&(amp|apos|gt|lt|quot);/g,(function(A,e){switch(e){case"amp":return"&";case"apos":return"'";case"gt":return">";case"lt":return"<";case"quot":return'"'}throw new Error(`_repair: ${e} isn't defined.`)})),i=[">"];for(let A=0,e=t.length;A=32&&e<127&&60!==e&&62!==e&&38!==e?i.push(String.fromCharCode(e)):i.push("&#x"+(65536+e).toString(16).substring(1)+";")}return i.join("")}))}_getSequence(A){const e=A.nodeName;return"rdf:bag"!==e&&"rdf:seq"!==e&&"rdf:alt"!==e?null:A.childNodes.filter((A=>"rdf:li"===A.nodeName))}_parseArray(A){if(!A.hasChildNodes())return;const[e]=A.childNodes,t=this._getSequence(e)||[];this._metadataMap.set(A.nodeName,t.map((A=>A.textContent.trim())))}_parse(A){let e=A.documentElement;if("rdf:rdf"!==e.nodeName)for(e=e.firstChild;e&&"rdf:rdf"!==e.nodeName;)e=e.nextSibling;if(e&&"rdf:rdf"===e.nodeName&&e.hasChildNodes())for(const A of e.childNodes)if("rdf:description"===A.nodeName)for(const e of A.childNodes){const A=e.nodeName;switch(A){case"#text":continue;case"dc:creator":case"dc:subject":this._parseArray(e);continue}this._metadataMap.set(A,e.textContent.trim())}}get serializable(){return{parsedData:this._metadataMap,rawData:this._data}}}class Sr extends Fe{constructor(A,e,t){super(e),this.str=A,this.dict=A.dict,this.decrypt=t,this.nextChunk=null,this.initialized=!1}readBlock(){let A;if(this.initialized?A=this.nextChunk:(A=this.str.getBytes(512),this.initialized=!0),!A||0===A.length)return void(this.eof=!0);this.nextChunk=this.str.getBytes(512);const e=this.nextChunk?.length>0;A=(0,this.decrypt)(A,!e);const t=this.bufferLength,i=t+A.length;this.ensureBuffer(i).set(A,t),this.bufferLength=i}}class Rr{constructor(A){this.a=0,this.b=0;const e=new Uint8Array(256),t=A.length;for(let A=0;A<256;++A)e[A]=A;for(let i=0,a=0;i<256;++i){const s=e[i];a=a+s+A[i%t]&255,e[i]=e[a],e[a]=s}this.s=e}encryptBlock(A){let e=this.a,t=this.b;const i=this.s,a=A.length,s=new Uint8Array(a);for(let n=0;n>5&255,I[c++]=a>>13&255,I[c++]=a>>21&255,I[c++]=a>>>29&255,I[c++]=0,I[c++]=0,I[c++]=0;const h=new Int32Array(16);for(c=0;c>>32-g)|0,a=s}s=s+a|0,n=n+o|0,g=g+B|0,r=r+Q|0}return new Uint8Array([255&s,s>>8&255,s>>16&255,s>>>24&255,255&n,n>>8&255,n>>16&255,n>>>24&255,255&g,g>>8&255,g>>16&255,g>>>24&255,255&r,r>>8&255,r>>16&255,r>>>24&255])}}();class Nr{constructor(A,e){this.high=0|A,this.low=0|e}and(A){this.high&=A.high,this.low&=A.low}xor(A){this.high^=A.high,this.low^=A.low}or(A){this.high|=A.high,this.low|=A.low}shiftRight(A){A>=32?(this.low=this.high>>>A-32|0,this.high=0):(this.low=this.low>>>A|this.high<<32-A,this.high=this.high>>>A|0)}shiftLeft(A){A>=32?(this.high=this.low<>>32-A,this.low<<=A)}rotateRight(A){let e,t;32&A?(t=this.low,e=this.high):(e=this.low,t=this.high),A&=31,this.low=e>>>A|t<<32-A,this.high=t>>>A|e<<32-A}not(){this.high=~this.high,this.low=~this.low}add(A){const e=(this.low>>>0)+(A.low>>>0);let t=(this.high>>>0)+(A.high>>>0);e>4294967295&&(t+=1),this.low=0|e,this.high=0|t}copyTo(A,e){A[e]=this.high>>>24&255,A[e+1]=this.high>>16&255,A[e+2]=this.high>>8&255,A[e+3]=255&this.high,A[e+4]=this.low>>>24&255,A[e+5]=this.low>>16&255,A[e+6]=this.low>>8&255,A[e+7]=255&this.low}assign(A){this.high=A.high,this.low=A.low}}const xr=function(){function A(A,e){return A>>>e|A<<32-e}function e(A,e,t){return A&e^~A&t}function t(A,e,t){return A&e^A&t^e&t}function i(e){return A(e,2)^A(e,13)^A(e,22)}function a(e){return A(e,6)^A(e,11)^A(e,25)}function s(e){return A(e,7)^A(e,18)^e>>>3}const n=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];return function(g,r,o){let I=1779033703,c=3144134277,C=1013904242,B=2773480762,h=1359893119,Q=2600822924,l=528734635,E=1541459225;const u=64*Math.ceil((o+9)/64),d=new Uint8Array(u);let f,p;for(f=0;f>>29&255,d[f++]=o>>21&255,d[f++]=o>>13&255,d[f++]=o>>5&255,d[f++]=o<<3&255;const y=new Uint32Array(64);for(f=0;f>>10)+y[p-7]+s(y[p-15])+y[p-16];let g,r,o=I,u=c,m=C,D=B,b=h,k=Q,F=l,S=E;for(p=0;p<64;++p)g=S+a(b)+e(b,k,F)+n[p]+y[p],r=i(o)+t(o,u,m),S=F,F=k,k=b,b=D+g|0,D=m,m=u,u=o,o=g+r|0;I=I+o|0,c=c+u|0,C=C+m|0,B=B+D|0,h=h+b|0,Q=Q+k|0,l=l+F|0,E=E+S|0}var w;return new Uint8Array([I>>24&255,I>>16&255,I>>8&255,255&I,c>>24&255,c>>16&255,c>>8&255,255&c,C>>24&255,C>>16&255,C>>8&255,255&C,B>>24&255,B>>16&255,B>>8&255,255&B,h>>24&255,h>>16&255,h>>8&255,255&h,Q>>24&255,Q>>16&255,Q>>8&255,255&Q,l>>24&255,l>>16&255,l>>8&255,255&l,E>>24&255,E>>16&255,E>>8&255,255&E])}}(),Ur=function(){function A(A,e,t,i,a){A.assign(e),A.and(t),a.assign(e),a.not(),a.and(i),A.xor(a)}function e(A,e,t,i,a){A.assign(e),A.and(t),a.assign(e),a.and(i),A.xor(a),a.assign(t),a.and(i),A.xor(a)}function t(A,e,t){A.assign(e),A.rotateRight(28),t.assign(e),t.rotateRight(34),A.xor(t),t.assign(e),t.rotateRight(39),A.xor(t)}function i(A,e,t){A.assign(e),A.rotateRight(14),t.assign(e),t.rotateRight(18),A.xor(t),t.assign(e),t.rotateRight(41),A.xor(t)}function a(A,e,t){A.assign(e),A.rotateRight(1),t.assign(e),t.rotateRight(8),A.xor(t),t.assign(e),t.shiftRight(7),A.xor(t)}function s(A,e,t){A.assign(e),A.rotateRight(19),t.assign(e),t.rotateRight(61),A.xor(t),t.assign(e),t.shiftRight(6),A.xor(t)}const n=[new Nr(1116352408,3609767458),new Nr(1899447441,602891725),new Nr(3049323471,3964484399),new Nr(3921009573,2173295548),new Nr(961987163,4081628472),new Nr(1508970993,3053834265),new Nr(2453635748,2937671579),new Nr(2870763221,3664609560),new Nr(3624381080,2734883394),new Nr(310598401,1164996542),new Nr(607225278,1323610764),new Nr(1426881987,3590304994),new Nr(1925078388,4068182383),new Nr(2162078206,991336113),new Nr(2614888103,633803317),new Nr(3248222580,3479774868),new Nr(3835390401,2666613458),new Nr(4022224774,944711139),new Nr(264347078,2341262773),new Nr(604807628,2007800933),new Nr(770255983,1495990901),new Nr(1249150122,1856431235),new Nr(1555081692,3175218132),new Nr(1996064986,2198950837),new Nr(2554220882,3999719339),new Nr(2821834349,766784016),new Nr(2952996808,2566594879),new Nr(3210313671,3203337956),new Nr(3336571891,1034457026),new Nr(3584528711,2466948901),new Nr(113926993,3758326383),new Nr(338241895,168717936),new Nr(666307205,1188179964),new Nr(773529912,1546045734),new Nr(1294757372,1522805485),new Nr(1396182291,2643833823),new Nr(1695183700,2343527390),new Nr(1986661051,1014477480),new Nr(2177026350,1206759142),new Nr(2456956037,344077627),new Nr(2730485921,1290863460),new Nr(2820302411,3158454273),new Nr(3259730800,3505952657),new Nr(3345764771,106217008),new Nr(3516065817,3606008344),new Nr(3600352804,1432725776),new Nr(4094571909,1467031594),new Nr(275423344,851169720),new Nr(430227734,3100823752),new Nr(506948616,1363258195),new Nr(659060556,3750685593),new Nr(883997877,3785050280),new Nr(958139571,3318307427),new Nr(1322822218,3812723403),new Nr(1537002063,2003034995),new Nr(1747873779,3602036899),new Nr(1955562222,1575990012),new Nr(2024104815,1125592928),new Nr(2227730452,2716904306),new Nr(2361852424,442776044),new Nr(2428436474,593698344),new Nr(2756734187,3733110249),new Nr(3204031479,2999351573),new Nr(3329325298,3815920427),new Nr(3391569614,3928383900),new Nr(3515267271,566280711),new Nr(3940187606,3454069534),new Nr(4118630271,4000239992),new Nr(116418474,1914138554),new Nr(174292421,2731055270),new Nr(289380356,3203993006),new Nr(460393269,320620315),new Nr(685471733,587496836),new Nr(852142971,1086792851),new Nr(1017036298,365543100),new Nr(1126000580,2618297676),new Nr(1288033470,3409855158),new Nr(1501505948,4234509866),new Nr(1607167915,987167468),new Nr(1816402316,1246189591)];return function(g,r,o,I=!1){let c,C,B,h,Q,l,E,u;I?(c=new Nr(3418070365,3238371032),C=new Nr(1654270250,914150663),B=new Nr(2438529370,812702999),h=new Nr(355462360,4144912697),Q=new Nr(1731405415,4290775857),l=new Nr(2394180231,1750603025),E=new Nr(3675008525,1694076839),u=new Nr(1203062813,3204075428)):(c=new Nr(1779033703,4089235720),C=new Nr(3144134277,2227873595),B=new Nr(1013904242,4271175723),h=new Nr(2773480762,1595750129),Q=new Nr(1359893119,2917565137),l=new Nr(2600822924,725511199),E=new Nr(528734635,4215389547),u=new Nr(1541459225,327033209));const d=128*Math.ceil((o+17)/128),f=new Uint8Array(d);let p,m;for(p=0;p>>29&255,f[p++]=o>>21&255,f[p++]=o>>13&255,f[p++]=o>>5&255,f[p++]=o<<3&255;const w=new Array(80);for(p=0;p<80;p++)w[p]=new Nr(0,0);let D=new Nr(0,0),b=new Nr(0,0),k=new Nr(0,0),F=new Nr(0,0),S=new Nr(0,0),R=new Nr(0,0),G=new Nr(0,0),N=new Nr(0,0);const x=new Nr(0,0),U=new Nr(0,0),M=new Nr(0,0),L=new Nr(0,0);let J,H;for(p=0;p=1;--A){t=s[13],s[13]=s[9],s[9]=s[5],s[5]=s[1],s[1]=t,t=s[14],i=s[10],s[14]=s[6],s[10]=s[2],s[6]=t,s[2]=i,t=s[15],i=s[11],a=s[7],s[15]=s[3],s[11]=t,s[7]=i,s[3]=a;for(let A=0;A<16;++A)s[A]=this._inv_s[s[A]];for(let t=0,i=16*A;t<16;++t,++i)s[t]^=e[i];for(let A=0;A<16;A+=4){const e=this._mix[s[A]],i=this._mix[s[A+1]],a=this._mix[s[A+2]],n=this._mix[s[A+3]];t=e^i>>>8^i<<24^a>>>16^a<<16^n>>>24^n<<8,s[A]=t>>>24&255,s[A+1]=t>>16&255,s[A+2]=t>>8&255,s[A+3]=255&t}}t=s[13],s[13]=s[9],s[9]=s[5],s[5]=s[1],s[1]=t,t=s[14],i=s[10],s[14]=s[6],s[10]=s[2],s[6]=t,s[2]=i,t=s[15],i=s[11],a=s[7],s[15]=s[3],s[11]=t,s[7]=i,s[3]=a;for(let A=0;A<16;++A)s[A]=this._inv_s[s[A]],s[A]^=e[A];return s}_encrypt(A,e){const t=this._s;let i,a,s;const n=new Uint8Array(16);n.set(A);for(let A=0;A<16;++A)n[A]^=e[A];for(let A=1;A=i;--t)if(A[t]!==e){e=0;break}g-=e,s[s.length-1]=A.subarray(0,16-e)}}const r=new Uint8Array(g);for(let A=0,e=0,t=s.length;A=256&&(g=255&(27^g)));for(let e=0;e<4;++e)t[A]=i^=t[A-32],A++,t[A]=a^=t[A-32],A++,t[A]=s^=t[A-32],A++,t[A]=n^=t[A-32],A++}return t}}class Yr{checkOwnerPassword(A,e,t,i){const a=new Uint8Array(A.length+56);return a.set(A,0),a.set(e,A.length),a.set(t,A.length+e.length),AA(xr(a,0,a.length),i)}checkUserPassword(A,e,t){const i=new Uint8Array(A.length+8);return i.set(A,0),i.set(e,A.length),AA(xr(i,0,i.length),t)}getOwnerKey(A,e,t,i){const a=new Uint8Array(A.length+56);a.set(A,0),a.set(e,A.length),a.set(t,A.length+e.length);const s=xr(a,0,a.length);return new Hr(s).decryptBlock(i,!1,new Uint8Array(16))}getUserKey(A,e,t){const i=new Uint8Array(A.length+8);i.set(A,0),i.set(e,A.length);const a=xr(i,0,i.length);return new Hr(a).decryptBlock(t,!1,new Uint8Array(16))}}class vr{_hash(A,e,t){let i=xr(e,0,e.length).subarray(0,32),a=[0],s=0;for(;s<64||a.at(-1)>s-32;){const e=A.length+i.length+t.length,r=new Uint8Array(e);let o=0;r.set(A,o),o+=A.length,r.set(i,o),o+=i.length,r.set(t,o);const I=new Uint8Array(64*e);for(let A=0,t=0;A<64;A++,t+=e)I.set(r,t);a=new Jr(i.subarray(0,16)).encrypt(I,i.subarray(16,32));const c=a.slice(0,16).reduce(((A,e)=>A+e),0)%3;0===c?i=xr(a,0,a.length):1===c?(n=a,0,g=a.length,i=Ur(n,0,g,!0)):2===c&&(i=Ur(a,0,a.length)),s++}var n,g;return i.subarray(0,32)}checkOwnerPassword(A,e,t,i){const a=new Uint8Array(A.length+56);return a.set(A,0),a.set(e,A.length),a.set(t,A.length+e.length),AA(this._hash(A,a,t),i)}checkUserPassword(A,e,t){const i=new Uint8Array(A.length+8);return i.set(A,0),i.set(e,A.length),AA(this._hash(A,i,[]),t)}getOwnerKey(A,e,t,i){const a=new Uint8Array(A.length+56);a.set(A,0),a.set(e,A.length),a.set(t,A.length+e.length);const s=this._hash(A,a,t);return new Hr(s).decryptBlock(i,!1,new Uint8Array(16))}getUserKey(A,e,t){const i=new Uint8Array(A.length+8);i.set(A,0),i.set(e,A.length);const a=this._hash(A,i,[]);return new Hr(a).decryptBlock(t,!1,new Uint8Array(16))}}class Kr{constructor(A,e){this.StringCipherConstructor=A,this.StreamCipherConstructor=e}createStream(A,e){const t=new this.StreamCipherConstructor;return new Sr(A,e,(function(A,e){return t.decryptBlock(A,e)}))}decryptString(A){const e=new this.StringCipherConstructor;let t=P(A);return t=e.decryptBlock(t,!0),T(t)}encryptString(A){const e=new this.StringCipherConstructor;if(e instanceof Lr){const t=16-A.length%16;A+=String.fromCharCode(t).repeat(t);const i=new Uint8Array(16);if("undefined"!=typeof crypto)crypto.getRandomValues(i);else for(let A=0;A<16;A++)i[A]=Math.floor(256*Math.random());let a=P(A);a=e.encrypt(a,i);const s=new Uint8Array(16+a.length);return s.set(i),s.set(a,16),T(s)}let t=P(A);return t=e.encrypt(t),T(t)}}class qr{static#S=new Uint8Array([40,191,78,94,78,117,138,65,100,0,78,86,255,250,1,8,46,46,0,182,208,104,62,128,47,12,169,254,100,83,105,122]);#R(A,e,t,i,a,s,n,g,r,o,I,c){if(e){const A=Math.min(127,e.length);e=e.subarray(0,A)}else e=[];const C=6===A?new vr:new Yr;return C.checkUserPassword(e,g,n)?C.getUserKey(e,r,I):e.length&&C.checkOwnerPassword(e,i,s,t)?C.getOwnerKey(e,a,s,o):null}#G(A,e,t,i,a,s,n,g){const r=40+t.length+A.length,o=new Uint8Array(r);let I,c,C=0;if(e)for(c=Math.min(32,e.length);C>8&255,o[C++]=a>>16&255,o[C++]=a>>>24&255,I=0,c=A.length;I=4&&!g&&(o[C++]=255,o[C++]=255,o[C++]=255,o[C++]=255);let B=Gr(o,0,C);const h=n>>3;if(s>=3)for(I=0;I<50;++I)B=Gr(B,0,h);const Q=B.subarray(0,h);let l,E;if(s>=3){for(C=0;C<32;++C)o[C]=qr.#S[C];for(I=0,c=A.length;I>3;if(t>=3)for(g=0;g<50;++g)r=Gr(r,0,r.length);let I,c;if(t>=3){c=e;const A=new Uint8Array(o);for(g=19;g>=0;g--){for(let e=0;e>8&255,a[n++]=A>>16&255,a[n++]=255&e,a[n++]=e>>8&255,i&&(a[n++]=115,a[n++]=65,a[n++]=108,a[n++]=84),Gr(a,0,n).subarray(0,Math.min(t.length+5,16))}#U(A,e,t,i,a){if(!(e instanceof oA))throw new K("Invalid crypt filter name.");const s=this,n=A.get(e.name)?.get("CFM");if(!n||"None"===n.name)return function(){return new Mr};if("V2"===n.name)return function(){return new Rr(s.#x(t,i,a,!1))};if("AESV2"===n.name)return function(){return new Jr(s.#x(t,i,a,!0))};if("AESV3"===n.name)return function(){return new Hr(a)};throw new K("Unknown crypto method")}constructor(A,e,t){const i=A.get("Filter");if(!lA(i,"Standard"))throw new K("unknown encryption method");this.filterName=i.name,this.dict=A;const a=A.get("V");if(!Number.isInteger(a)||1!==a&&2!==a&&4!==a&&5!==a)throw new K("unsupported encryption algorithm");this.algorithm=a;let s=A.get("Length");if(!s)if(a<=3)s=40;else{const e=A.get("CF"),t=A.get("StmF");e instanceof CA&&t instanceof oA&&(e.suppressEncryption=!0,s=e.get(t.name)?.get("Length")||128,s<40&&(s<<=3))}if(!Number.isInteger(s)||s<40||s%8!=0)throw new K("invalid key length");const n=P(A.get("O")),g=P(A.get("U")),r=n.subarray(0,32),o=g.subarray(0,32),I=A.get("P"),c=A.get("R"),C=(4===a||5===a)&&!1!==A.get("EncryptMetadata");this.encryptMetadata=C;const B=P(e);let h,Q;if(t){if(6===c)try{t=$(t)}catch{R("CipherTransformFactory: Unable to convert UTF8 encoded password.")}h=P(t)}if(5!==a)Q=this.#G(B,h,r,o,I,c,s,C);else{const e=n.subarray(32,40),t=n.subarray(40,48),i=g.subarray(0,48),a=g.subarray(32,40),s=g.subarray(40,48),I=P(A.get("OE")),C=P(A.get("UE")),B=P(A.get("Perms"));Q=this.#R(c,h,r,e,t,i,o,a,s,I,C,B)}if(!Q&&!t)throw new L("No password given",1);if(!Q&&t){const A=this.#N(h,r,c,s);Q=this.#G(B,A,r,o,I,c,s,C)}if(!Q)throw new L("Incorrect Password",2);if(this.encryptionKey=Q,a>=4){const e=A.get("CF");e instanceof CA&&(e.suppressEncryption=!0),this.cf=e,this.stmf=A.get("StmF")||oA.get("Identity"),this.strf=A.get("StrF")||oA.get("Identity"),this.eff=A.get("EFF")||this.stmf}}createCipherTransform(A,e){if(4===this.algorithm||5===this.algorithm)return new Kr(this.#U(this.cf,this.strf,A,e,this.encryptionKey),this.#U(this.cf,this.stmf,A,e,this.encryptionKey));const t=this.#x(A,e,this.encryptionKey,!1),i=function(){return new Rr(t)};return new Kr(i,i)}}async function Tr(A,e,t,{encrypt:i=null}){const a=i?.createCipherTransform(A.num,A.gen);t.push(`${A.num} ${A.gen} obj\n`),e instanceof CA?await Pr(e,t,a):e instanceof fA?await Wr(e,t,a):(Array.isArray(e)||ArrayBuffer.isView(e))&&await Zr(e,t,a),t.push("\nendobj\n")}async function Pr(A,e,t){e.push("<<");for(const i of A.getKeys())e.push(` /${KA(i)} `),await Or(A.getRaw(i),e,t);e.push(">>")}async function Wr(A,e,t){let i=A.getBytes();const{dict:a}=A,[s,n]=await Promise.all([a.getAsync("Filter"),a.getAsync("DecodeParms")]),g=lA(Array.isArray(s)?await a.xref.fetchIfRefAsync(s[0]):s,"FlateDecode");if(i.length>=256||g)try{const A=new CompressionStream("deflate"),e=A.writable.getWriter();e.write(i),e.close();const t=await new Response(A.readable).arrayBuffer();let r,o;i=new Uint8Array(t),s?g||(r=Array.isArray(s)?[oA.get("FlateDecode"),...s]:[oA.get("FlateDecode"),s],n&&(o=Array.isArray(n)?[null,...n]:[null,n])):r=oA.get("FlateDecode"),r&&a.set("Filter",r),o&&a.set("DecodeParms",o)}catch(A){S(`writeStream - cannot compress data: "${A}".`)}let r=T(i);t&&(r=t.encryptString(r)),a.set("Length",r.length),await Pr(a,e,t),e.push(" stream\n",r,"\nendstream")}async function Zr(A,e,t){e.push("[");let i=!0;for(const a of A)i?i=!1:e.push(" "),await Or(a,e,t);e.push("]")}async function Or(A,e,t){A instanceof oA?e.push(`/${KA(A.name)}`):A instanceof BA?e.push(`${A.num} ${A.gen} R`):Array.isArray(A)||ArrayBuffer.isView(A)?await Zr(A,e,t):"string"==typeof A?(t&&(A=t.encryptString(A)),e.push(`(${qA(A)})`)):"number"==typeof A?e.push(zA(A)):"boolean"==typeof A?e.push(A.toString()):A instanceof CA?await Pr(A,e,t):A instanceof fA?await Wr(A,e,t):null===A?e.push("null"):R(`Unhandled value in writer: ${typeof A}, please file a bug.`)}function Xr(A,e,t,i){for(let a=e+t-1;a>t-1;a--)i[a]=255&A,A>>=8;return t+e}function Vr(A,e,t){for(let i=0,a=A.length;i0){const i=function(A,e){const t=Math.floor(Date.now()/1e3),i=e.filename||"",a=[t.toString(),i,A.toString()];let s=a.reduce(((A,e)=>A+e.length),0);for(const A of Object.values(e.info))a.push(A),s+=A.length;const n=new Uint8Array(s);let g=0;for(const A of a)Vr(A,g,n),g+=A.length;return T(Gr(n))}(A,e);t.set("ID",[e.fileIds[0],i])}}async function _r({originalData:A,xrefInfo:e,newRefs:t,xref:i=null,hasXfa:a=!1,xfaDatasetsRef:s=null,hasXfaDatasetsEntry:n=!1,needAppearances:g,acroFormRef:r=null,acroForm:o=null,xfaData:I=null,useXrefStream:c=!1}){await async function({xref:A,acroForm:e,acroFormRef:t,hasXfa:i,hasXfaDatasetsEntry:a,xfaDatasetsRef:s,needAppearances:n,newRefs:g}){if(!i||a||s||R("XFA - Cannot save it"),!n&&(!i||!s||a))return;const r=e.clone();if(i&&!a){const A=e.get("XFA").slice();A.splice(2,0,"datasets"),A.splice(3,0,s),r.set("XFA",A)}n&&r.set("NeedAppearances",!0);const o=[];await Tr(t,r,o,A),g.push({ref:t,data:o.join("")})}({xref:i,acroForm:o,acroFormRef:r,hasXfa:a,hasXfaDatasetsEntry:n,xfaDatasetsRef:s,needAppearances:g,newRefs:t}),a&&function({xfaData:A,xfaDatasetsRef:e,newRefs:t,xref:i}){null===A&&(A=function(A,e){const t=new kr({hasAttributes:!0}).parseFromString(A);for(const{xfa:A}of e){if(!A)continue;const{path:e,value:i}=A;if(!e)continue;const a=vA(e);let s=t.documentElement.searchNode(a,0);!s&&a.length>1&&(s=t.documentElement.searchNode([a.at(-1)],0)),s?s.childNodes=Array.isArray(i)?i.map((A=>new br("value",A))):[new br("#text",i)]:R(`Node not found for path: ${e}`)}const i=[];return t.documentElement.dump(i),i.join("")}(i.fetchIfRef(e).getString(),t));const a=i.encrypt;a&&(A=a.createCipherTransform(e.num,e.gen).encryptString(A));const s=`${e.num} ${e.gen} obj\n<< /Type /EmbeddedFile /Length ${A.length}>>\nstream\n`+A+"\nendstream\nendobj\n";t.push({ref:e,data:s})}({xfaData:I,xfaDatasetsRef:s,newRefs:t,xref:i});const C=[];let B=A.length;const h=A.at(-1);10!==h&&13!==h&&(C.push("\n"),B+=1);const Q=function(A,e,t){const i=new CA(null);i.set("Prev",A.startXRef);const a=A.newRef;return t?(e.push({ref:a,data:""}),i.set("Size",a.num+1),i.set("Type",oA.get("XRef"))):i.set("Size",a.num),null!==A.rootRef&&i.set("Root",A.rootRef),null!==A.infoRef&&i.set("Info",A.infoRef),null!==A.encryptRef&&i.set("Encrypt",A.encryptRef),i}(e,t,c);t=t.sort(((A,e)=>A.ref.num-e.ref.num));for(const{data:A}of t)null!==A&&C.push(A);await(c?async function(A,e,t,i,a){const s=[];let n=0,g=0;for(const{ref:A,data:i}of t){let t;n=Math.max(n,e),null!==i?(t=Math.min(A.gen,65535),s.push([1,e,t]),e+=i.length):(t=Math.min(A.gen+1,65535),s.push([0,0,t])),g=Math.max(g,t)}i.set("Index",jr(t));const r=[1,ie(n),ie(g)];i.set("W",r),zr(e,A,i);const o=r.reduce(((A,e)=>A+e),0),I=new Uint8Array(o*s.length),c=new ae(I);c.dict=i;let C=0;for(const[A,e,t]of s)C=Xr(A,r[0],C,I),C=Xr(e,r[1],C,I),C=Xr(t,r[2],C,I);await Tr(A.newRef,c,a,{}),a.push("startxref\n",e.toString(),"\n%%EOF\n")}(e,B,t,Q,C):async function(A,e,t,i,a){a.push("xref\n");const s=jr(t);let n=0;for(const{ref:A,data:i}of t)A.num===s[n]&&(a.push(`${s[n]} ${s[n+1]}\n`),n+=2),null!==i?(a.push(`${e.toString().padStart(10,"0")} ${Math.min(A.gen,65535).toString().padStart(5,"0")} n\r\n`),e+=i.length):a.push(`0000000000 ${Math.min(A.gen+1,65535).toString().padStart(5,"0")} f\r\n`);zr(e,A,i),a.push("trailer\n"),await Pr(i,a),a.push("\nstartxref\n",e.toString(),"\n%%EOF\n")}(e,B,t,Q,C));const l=C.reduce(((A,e)=>A+e.length),A.length),E=new Uint8Array(l);E.set(A);let u=A.length;for(const A of C)Vr(A,u,E),u+=A.length;return E}class $r{constructor(A,e){this.dict=A,this.ref=e instanceof BA?e:null,this.roleMap=new Map,this.structParentIds=null}init(){this.readRoleMap()}#M(A,e,t){if(!(A instanceof BA)||e<0)return;this.structParentIds||=new QA;let i=this.structParentIds.get(A);i||(i=[],this.structParentIds.put(A,i)),i.push([e,t])}addAnnotationIdToPage(A,e){this.#M(A,e,4)}readRoleMap(){const A=this.dict.get("RoleMap");A instanceof CA&&A.forEach(((A,e)=>{e instanceof oA&&this.roleMap.set(A,e.name)}))}static async canCreateStructureTree({catalogRef:A,pdfManager:e,newAnnotationsByPage:t}){if(!(A instanceof BA))return R("Cannot save the struct tree: no catalog reference."),!1;let i=0,a=!0;for(const[A,s]of t){const{ref:t}=await e.getPage(A);if(!(t instanceof BA)){R(`Cannot save the struct tree: page ${A} has no ref.`),a=!0;break}for(const A of s)A.accessibilityData?.type&&(A.parentTreeId=i++,a=!1)}if(a){for(const A of t.values())for(const e of A)delete e.parentTreeId;return!1}return!0}static async createStructureTree({newAnnotationsByPage:A,xref:e,catalogRef:t,pdfManager:i,newRefs:a}){const s=i.catalog.cloneDict(),n=new QA;n.put(t,s);const g=e.getNewTemporaryRef();s.set("StructTreeRoot",g);const r=new CA(e);r.set("Type",oA.get("StructTreeRoot"));const o=e.getNewTemporaryRef();r.set("ParentTree",o);const I=[];r.set("K",I),n.put(g,r);const c=new CA(e),C=[];c.set("Nums",C);const B=await this.#L({newAnnotationsByPage:A,structTreeRootRef:g,structTreeRoot:null,kids:I,nums:C,xref:e,pdfManager:i,newRefs:a,cache:n});r.set("ParentTreeNextKey",B),n.put(o,c);const h=[];for(const[A,t]of n.items())h.length=0,await Tr(A,t,h,e),a.push({ref:A,data:h.join("")})}async canUpdateStructTree({pdfManager:A,xref:e,newAnnotationsByPage:t}){if(!this.ref)return R("Cannot update the struct tree: no root reference."),!1;let i=this.dict.get("ParentTreeNextKey");if(!Number.isInteger(i)||i<0)return R("Cannot update the struct tree: invalid next key."),!1;const a=this.dict.get("ParentTree");if(!(a instanceof CA))return R("Cannot update the struct tree: ParentTree isn't a dict."),!1;const s=a.get("Nums");if(!Array.isArray(s))return R("Cannot update the struct tree: nums isn't an array."),!1;const n=new fr(a,e);for(const e of t.keys()){const{pageDict:t}=await A.getPage(e);if(!t.has("StructParents"))continue;const i=t.get("StructParents");if(!Number.isInteger(i)||!Array.isArray(n.get(i)))return R(`Cannot save the struct tree: page ${e} has a wrong id.`),!1}let g=!0;for(const[e,a]of t){const{pageDict:t}=await A.getPage(e);$r.#J({elements:a,xref:this.dict.xref,pageDict:t,numberTree:n});for(const A of a)A.accessibilityData?.type&&(A.accessibilityData.structParent>=0||(A.parentTreeId=i++),g=!1)}if(g){for(const A of t.values())for(const e of A)delete e.parentTreeId,delete e.structTreeParent;return!1}return!0}async updateStructureTree({newAnnotationsByPage:A,pdfManager:e,newRefs:t}){const i=this.dict.xref,a=this.dict.clone(),s=this.ref,n=new QA;n.put(s,a);let g,r=a.getRaw("ParentTree");r instanceof BA?g=i.fetch(r):(g=r,r=i.getNewTemporaryRef(),a.set("ParentTree",r)),g=g.clone(),n.put(r,g);let o=g.getRaw("Nums"),I=null;o instanceof BA&&(I=o,o=i.fetch(I)),o=o.slice(),I||g.set("Nums",o);const c=await $r.#L({newAnnotationsByPage:A,structTreeRootRef:s,structTreeRoot:this,kids:null,nums:o,xref:i,pdfManager:e,newRefs:t,cache:n});if(-1===c)return;a.set("ParentTreeNextKey",c),I&&n.put(I,o);const C=[];for(const[A,e]of n.items())C.length=0,await Tr(A,e,C,i),t.push({ref:A,data:C.join("")})}static async#L({newAnnotationsByPage:A,structTreeRootRef:e,structTreeRoot:t,kids:i,nums:a,xref:s,pdfManager:n,newRefs:g,cache:r}){const o=oA.get("OBJR");let I,c=-1;const C=[];for(const[B,h]of A){const A=await n.getPage(B),{ref:Q}=A,l=Q instanceof BA;for(const{accessibilityData:n,ref:E,parentTreeId:u,structTreeParent:d}of h){if(!n?.type)continue;const{structParent:h}=n;if(t&&Number.isInteger(h)&&h>=0){let e=(I||=new Map).get(B);void 0===e&&(e=new to(t,A.pageDict).collectObjects(Q),I.set(B,e));const i=e?.get(h);if(i){const A=s.fetch(i).clone();$r.#H(A,n),C.length=0,await Tr(i,A,C,s),g.push({ref:i,data:C.join("")});continue}}c=Math.max(c,u);const f=s.getNewTemporaryRef(),p=new CA(s);$r.#H(p,n),await this.#Y({structTreeParent:d,tagDict:p,newTagRef:f,structTreeRootRef:e,fallbackKids:i,xref:s,cache:r});const m=new CA(s);p.set("K",m),m.set("Type",o),l&&m.set("Pg",Q),m.set("Obj",E),r.put(f,p),a.push(u,f)}}return c+1}static#H(A,{type:e,title:t,lang:i,alt:a,expanded:s,actualText:n}){A.set("S",oA.get(e)),t&&A.set("T",$A(t)),i&&A.set("Lang",$A(i)),a&&A.set("Alt",$A(a)),s&&A.set("E",$A(s)),n&&A.set("ActualText",$A(n))}static#J({elements:A,xref:e,pageDict:t,numberTree:i}){const a=new Map;for(const e of A)if(e.structTreeParentId){const A=parseInt(e.structTreeParentId.split("_mc")[1],10);let t=a.get(A);t||(t=[],a.set(A,t)),t.push(e)}const s=t.get("StructParents");if(!Number.isInteger(s))return;const n=i.get(s),g=(A,t,i)=>{const s=a.get(A);if(s){const A=t.getRaw("P"),a=e.fetchIfRef(A);if(A instanceof BA&&a instanceof CA){const A={ref:i,dict:t};for(const e of s)e.structTreeParent=A}return!0}return!1};for(const A of n){if(!(A instanceof BA))continue;const t=e.fetch(A),i=t.get("K");if(Number.isInteger(i))g(i,t,A);else if(Array.isArray(i))for(let a of i){if(a=e.fetchIfRef(a),Number.isInteger(a)&&g(a,t,A))break;if(!(a instanceof CA))continue;if(!lA(a.get("Type"),"MCR"))break;const i=a.get("MCID");if(Number.isInteger(i)&&g(i,t,A))break}}}static async#Y({structTreeParent:A,tagDict:e,newTagRef:t,structTreeRootRef:i,fallbackKids:a,xref:s,cache:n}){let g,r=null;A?(({ref:r}=A),g=A.dict.getRaw("P")||i):g=i,e.set("P",g);const o=s.fetchIfRef(g);if(!o)return void a.push(t);let I=n.get(g);I||(I=o.clone(),n.put(g,I));const c=I.getRaw("K");let C=c instanceof BA?n.get(c):null;if(!C){C=s.fetchIfRef(c),C=Array.isArray(C)?C.slice():[c];const A=s.getNewTemporaryRef();I.set("K",A),n.put(A,C)}const B=C.indexOf(r);C.splice(B>=0?B+1:C.length,0,t)}}class Ao{constructor(A,e){this.tree=A,this.dict=e,this.kids=[],this.parseKids()}get role(){const A=this.dict.get("S"),e=A instanceof oA?A.name:"",{root:t}=this.tree;return t.roleMap.has(e)?t.roleMap.get(e):e}parseKids(){let A=null;const e=this.dict.getRaw("Pg");e instanceof BA&&(A=e.toString());const t=this.dict.get("K");if(Array.isArray(t))for(const e of t){const t=this.parseKid(A,e);t&&this.kids.push(t)}else{const e=this.parseKid(A,t);e&&this.kids.push(e)}}parseKid(A,e){if(Number.isInteger(e))return this.tree.pageDict.objId!==A?null:new eo({type:1,mcid:e,pageObjId:A});let t=null;if(e instanceof BA?t=this.dict.xref.fetch(e):e instanceof CA&&(t=e),!t)return null;const i=t.getRaw("Pg");i instanceof BA&&(A=i.toString());const a=t.get("Type")instanceof oA?t.get("Type").name:null;if("MCR"===a){if(this.tree.pageDict.objId!==A)return null;const e=t.getRaw("Stm");return new eo({type:2,refObjId:e instanceof BA?e.toString():null,pageObjId:A,mcid:t.get("MCID")})}if("OBJR"===a){if(this.tree.pageDict.objId!==A)return null;const e=t.getRaw("Obj");return new eo({type:3,refObjId:e instanceof BA?e.toString():null,pageObjId:A})}return new eo({type:5,dict:t})}}class eo{constructor({type:A,dict:e=null,mcid:t=null,pageObjId:i=null,refObjId:a=null}){this.type=A,this.dict=e,this.mcid=t,this.pageObjId=i,this.refObjId=a,this.parentNode=null}}class to{constructor(A,e){this.root=A,this.rootDict=A?A.dict:null,this.pageDict=e,this.nodes=[]}collectObjects(A){if(!(this.root&&this.rootDict&&A instanceof BA))return null;const e=this.rootDict.get("ParentTree");if(!e)return null;const t=this.root.structParentIds?.get(A);if(!t)return null;const i=new Map,a=new fr(e,this.rootDict.xref);for(const[A]of t){const e=a.getRaw(A);e instanceof BA&&i.set(A,e)}return i}parse(A){if(!(this.root&&this.rootDict&&A instanceof BA))return;const e=this.rootDict.get("ParentTree");if(!e)return;const t=this.pageDict.get("StructParents"),i=this.root.structParentIds?.get(A);if(!Number.isInteger(t)&&!i)return;const a=new Map,s=new fr(e,this.rootDict.xref);if(Number.isInteger(t)){const A=s.get(t);if(Array.isArray(A))for(const e of A)e instanceof BA&&this.addNode(this.rootDict.xref.fetch(e),a)}if(i)for(const[A,e]of i){const t=s.get(A);if(t){const A=this.addNode(this.rootDict.xref.fetchIfRef(t),a);1===A?.kids?.length&&3===A.kids[0].type&&(A.kids[0].type=e)}}}addNode(A,e,t=0){if(t>40)return R("StructTree MAX_DEPTH reached."),null;if(!(A instanceof CA))return null;if(e.has(A))return e.get(A);const i=new Ao(this,A);e.set(A,i);const a=A.get("P");if(!a||lA(a.get("Type"),"StructTreeRoot"))return this.addTopLevelNode(A,i)||e.delete(A),i;const s=this.addNode(a,e,t+1);if(!s)return i;let n=!1;for(const e of s.kids)5===e.type&&e.dict===A&&(e.parentNode=i,n=!0);return n||e.delete(A),i}addTopLevelNode(A,e){const t=this.rootDict.get("K");if(!t)return!1;if(t instanceof CA)return t.objId===A.objId&&(this.nodes[0]=e,!0);if(!Array.isArray(t))return!0;let i=!1;for(let a=0;a40)return void R("StructTree too deep to be fully serialized.");const a=Object.create(null);a.role=e.role,a.children=[],t.children.push(a);let s=e.dict.get("Alt");"string"!=typeof s&&(s=e.dict.get("ActualText")),"string"==typeof s&&(a.alt=z(s));const n=e.dict.get("A");if(n instanceof CA){const A=YA(n.getArray("BBox"),null);if(A)a.bbox=A;else{const A=n.get("Width"),e=n.get("Height");"number"==typeof A&&A>0&&"number"==typeof e&&e>0&&(a.bbox=[0,0,A,e])}}const g=e.dict.get("Lang");"string"==typeof g&&(a.lang=z(g));for(const t of e.kids){const e=5===t.type?t.parentNode:null;e?A(e,a,i+1):1===t.type||2===t.type?a.children.push({type:"content",id:`p${t.pageObjId}_mc${t.mcid}`}):3===t.type?a.children.push({type:"object",id:t.refObjId}):4===t.type&&a.children.push({type:"annotation",id:`pdfjs_internal_id_${t.refObjId}`})}}const e=Object.create(null);e.children=[],e.role="Root";for(const t of this.nodes)t&&A(t,e);return e}}function io(A){if(!Array.isArray(A)||A.length<2)return!1;const[e,t,...i]=A;if(!(e instanceof BA||Number.isInteger(e)))return!1;if(!(t instanceof oA))return!1;const a=i.length;let s=!0;switch(t.name){case"XYZ":if(a<2||a>3)return!1;break;case"Fit":case"FitB":return 0===a;case"FitH":case"FitBH":case"FitV":case"FitBV":if(a>1)return!1;break;case"FitR":if(4!==a)return!1;s=!1;break;default:return!1}for(const A of i)if(!("number"==typeof A||s&&null===A))return!1;return!0}function ao(A){return A instanceof CA&&(A=A.get("D")),io(A)?A:null}function so(A){let e=A.get("D");if(e){if(e instanceof oA&&(e=e.name),"string"==typeof e)return z(e);if(io(e))return JSON.stringify(e)}return null}class no{constructor(A,e){if(this.pdfManager=A,this.xref=e,this._catDict=e.getCatalogObj(),!(this._catDict instanceof CA))throw new K("Catalog object is not a dictionary.");this.toplevelPagesDict,this._actualNumPages=null,this.fontCache=new QA,this.builtInCMapCache=new Map,this.standardFontDataCache=new Map,this.globalImageCache=new ig,this.pageKidsCountCache=new QA,this.pageIndexCache=new QA,this.pageDictCache=new QA,this.nonBlendModesSet=new hA,this.systemFontCache=new Map}cloneDict(){return this._catDict.clone()}get version(){const A=this._catDict.get("Version");if(A instanceof oA){if(pA.test(A.name))return U(this,"version",A.name);R(`Invalid PDF catalog version: ${A.name}`)}return U(this,"version",null)}get lang(){const A=this._catDict.get("Lang");return U(this,"lang",A&&"string"==typeof A?z(A):null)}get needsRendering(){const A=this._catDict.get("NeedsRendering");return U(this,"needsRendering","boolean"==typeof A&&A)}get collection(){let A=null;try{const e=this._catDict.get("Collection");e instanceof CA&&e.size>0&&(A=e)}catch(A){if(A instanceof yA)throw A;S("Cannot fetch Collection entry; assuming no collection is present.")}return U(this,"collection",A)}get acroForm(){let A=null;try{const e=this._catDict.get("AcroForm");e instanceof CA&&e.size>0&&(A=e)}catch(A){if(A instanceof yA)throw A;S("Cannot fetch AcroForm entry; assuming no forms are present.")}return U(this,"acroForm",A)}get acroFormRef(){const A=this._catDict.getRaw("AcroForm");return U(this,"acroFormRef",A instanceof BA?A:null)}get metadata(){const A=this._catDict.getRaw("Metadata");if(!(A instanceof BA))return U(this,"metadata",null);let e=null;try{const t=this.xref.fetch(A,!this.xref.encrypt?.encryptMetadata);if(t instanceof fA&&t.dict instanceof CA){const A=t.dict.get("Type"),i=t.dict.get("Subtype");if(lA(A,"Metadata")&&lA(i,"XML")){const A=_(t.getString());A&&(e=new Fr(A).serializable)}}}catch(A){if(A instanceof yA)throw A;S(`Skipping invalid Metadata: "${A}".`)}return U(this,"metadata",e)}get markInfo(){let A=null;try{A=this._readMarkInfo()}catch(A){if(A instanceof yA)throw A;R("Unable to read mark info.")}return U(this,"markInfo",A)}_readMarkInfo(){const A=this._catDict.get("MarkInfo");if(!(A instanceof CA))return null;const e={Marked:!1,UserProperties:!1,Suspects:!1};for(const t in e){const i=A.get(t);"boolean"==typeof i&&(e[t]=i)}return e}get structTreeRoot(){let A=null;try{A=this._readStructTreeRoot()}catch(A){if(A instanceof yA)throw A;R("Unable read to structTreeRoot info.")}return U(this,"structTreeRoot",A)}_readStructTreeRoot(){const A=this._catDict.getRaw("StructTreeRoot"),e=this.xref.fetchIfRef(A);if(!(e instanceof CA))return null;const t=new $r(e,A);return t.init(),t}get toplevelPagesDict(){const A=this._catDict.get("Pages");if(!(A instanceof CA))throw new K("Invalid top-level pages dictionary.");return U(this,"toplevelPagesDict",A)}get documentOutline(){let A=null;try{A=this._readDocumentOutline()}catch(A){if(A instanceof yA)throw A;R("Unable to read document outline.")}return U(this,"documentOutline",A)}_readDocumentOutline(){let A=this._catDict.get("Outlines");if(!(A instanceof CA))return null;if(A=A.getRaw("First"),!(A instanceof BA))return null;const e={items:[]},t=[{obj:A,parent:e}],i=new hA;i.put(A);const a=this.xref,s=new Uint8ClampedArray(3);for(;t.length>0;){const e=t.shift(),n=a.fetchIfRef(e.obj);if(null===n)continue;n.has("Title")||R("Invalid outline item encountered.");const g={url:null,dest:null,action:null};no.parseDestDictionary({destDict:n,resultObj:g,docBaseUrl:this.baseUrl,docAttachments:this.attachments});const r=n.get("Title"),o=n.get("F")||0,I=n.getArray("C"),c=n.get("Count");let C=s;!LA(I,3)||0===I[0]&&0===I[1]&&0===I[2]||(C=oe.singletons.rgb.getRgb(I,0));const B={action:g.action,attachment:g.attachment,dest:g.dest,url:g.url,unsafeUrl:g.unsafeUrl,newWindow:g.newWindow,setOCGState:g.setOCGState,title:"string"==typeof r?z(r):"",color:C,count:Number.isInteger(c)?c:void 0,bold:!!(2&o),italic:!!(1&o),items:[]};e.parent.items.push(B),A=n.getRaw("First"),A instanceof BA&&!i.has(A)&&(t.push({obj:A,parent:B}),i.put(A)),A=n.getRaw("Next"),A instanceof BA&&!i.has(A)&&(t.push({obj:A,parent:e.parent}),i.put(A))}return e.items.length>0?e.items:null}get permissions(){let A=null;try{A=this._readPermissions()}catch(A){if(A instanceof yA)throw A;R("Unable to read permissions.")}return U(this,"permissions",A)}_readPermissions(){const A=this.xref.trailer.get("Encrypt");if(!(A instanceof CA))return null;let e=A.get("P");if("number"!=typeof e)return null;e+=2**32;const t=[];for(const A in r){const i=r[A];e&i&&t.push(i)}return t}get optionalContentConfig(){let A=null;try{const e=this._catDict.get("OCProperties");if(!e)return U(this,"optionalContentConfig",null);const t=e.get("D");if(!t)return U(this,"optionalContentConfig",null);const i=e.get("OCGs");if(!Array.isArray(i))return U(this,"optionalContentConfig",null);const a=[],s=new hA;for(const A of i)A instanceof BA&&!s.has(A)&&(s.put(A),a.push(this.#v(A)));A=this.#K(t,s),A.groups=a}catch(A){if(A instanceof yA)throw A;R(`Unable to read optional content config: ${A}`)}return U(this,"optionalContentConfig",A)}#v(A){const e=this.xref.fetch(A),t={id:A.toString(),name:null,intent:null,usage:{print:null,view:null}},i=e.get("Name");"string"==typeof i&&(t.name=z(i));let a=e.getArray("Intent");Array.isArray(a)||(a=[a]),a.every((A=>A instanceof oA))&&(t.intent=a.map((A=>A.name)));const s=e.get("Usage");if(!(s instanceof CA))return t;const n=t.usage,g=s.get("Print");if(g instanceof CA){const A=g.get("PrintState");if(A instanceof oA)switch(A.name){case"ON":case"OFF":n.print={printState:A.name}}}const r=s.get("View");if(r instanceof CA){const A=r.get("ViewState");if(A instanceof oA)switch(A.name){case"ON":case"OFF":n.view={viewState:A.name}}}return t}#K(A,e){function t(A){const t=[];if(Array.isArray(A))for(const i of A)i instanceof BA&&e.has(i)&&t.push(i.toString());return t}function i(A,t=0){if(!Array.isArray(A))return null;const i=[];for(const s of A){if(s instanceof BA&&e.has(s)){n.put(s),i.push(s.toString());continue}const A=a(s,t);A&&i.push(A)}if(t>0)return i;const s=[];for(const A of e)n.has(A)||s.push(A.toString());return s.length&&i.push({name:null,order:s}),i}function a(A,e){if(++e>g)return R("parseNestedOrder - reached MAX_NESTED_LEVELS."),null;const t=s.fetchIfRef(A);if(!Array.isArray(t))return null;const a=s.fetchIfRef(t[0]);if("string"!=typeof a)return null;const n=i(t.slice(1),e);return n&&n.length?{name:z(a),order:n}:null}const s=this.xref,n=new hA,g=10;return{name:"string"==typeof A.get("Name")?z(A.get("Name")):null,creator:"string"==typeof A.get("Creator")?z(A.get("Creator")):null,baseState:A.get("BaseState")instanceof oA?A.get("BaseState").name:null,on:t(A.get("ON")),off:t(A.get("OFF")),order:i(A.get("Order")),groups:null}}setActualNumPages(A=null){this._actualNumPages=A}get hasActualNumPages(){return null!==this._actualNumPages}get _pagesCount(){const A=this.toplevelPagesDict.get("Count");if(!Number.isInteger(A))throw new K("Page count in top-level pages dictionary is not an integer.");return U(this,"_pagesCount",A)}get numPages(){return this.hasActualNumPages?this._actualNumPages:this._pagesCount}get destinations(){const A=this._readDests(),e=Object.create(null);if(A instanceof dr)for(const[t,i]of A.getAll()){const A=ao(i);A&&(e[z(t)]=A)}else A instanceof CA&&A.forEach((function(A,t){const i=ao(t);i&&(e[A]=i)}));return U(this,"destinations",e)}getDestination(A){const e=this._readDests();if(e instanceof dr){const t=ao(e.get(A));if(t)return t;const i=this.destinations[A];if(i)return R(`Found "${A}" at an incorrect position in the NameTree.`),i}else if(e instanceof CA){const t=ao(e.get(A));if(t)return t}return null}_readDests(){const A=this._catDict.get("Names");return A?.has("Dests")?new dr(A.getRaw("Dests"),this.xref):this._catDict.has("Dests")?this._catDict.get("Dests"):void 0}get pageLabels(){let A=null;try{A=this._readPageLabels()}catch(A){if(A instanceof yA)throw A;R("Unable to read page labels.")}return U(this,"pageLabels",A)}_readPageLabels(){const A=this._catDict.getRaw("PageLabels");if(!A)return null;const e=new Array(this.numPages);let t=null,i="";const a=new fr(A,this.xref).getAll();let s="",n=1;for(let A=0,g=this.numPages;A=1))throw new K("Invalid start in PageLabel dictionary.");n=A}else n=1}switch(t){case"D":s=n;break;case"R":case"r":s=RA(n,"r"===t);break;case"A":case"a":const A=26,e="a"===t?97:65,i=n-1;s=String.fromCharCode(e+i%A).repeat(Math.floor(i/A)+1);break;default:if(t)throw new K(`Invalid style "${t}" in PageLabel dictionary.`);s=""}e[A]=i+s,n++}return e}get pageLayout(){const A=this._catDict.get("PageLayout");let e="";if(A instanceof oA)switch(A.name){case"SinglePage":case"OneColumn":case"TwoColumnLeft":case"TwoColumnRight":case"TwoPageLeft":case"TwoPageRight":e=A.name}return U(this,"pageLayout",e)}get pageMode(){const A=this._catDict.get("PageMode");let e="UseNone";if(A instanceof oA)switch(A.name){case"UseNone":case"UseOutlines":case"UseThumbs":case"FullScreen":case"UseOC":case"UseAttachments":e=A.name}return U(this,"pageMode",e)}get viewerPreferences(){const A=this._catDict.get("ViewerPreferences");if(!(A instanceof CA))return U(this,"viewerPreferences",null);let e=null;for(const t of A.getKeys()){const i=A.get(t);let a;switch(t){case"HideToolbar":case"HideMenubar":case"HideWindowUI":case"FitWindow":case"CenterWindow":case"DisplayDocTitle":case"PickTrayByPDFSize":"boolean"==typeof i&&(a=i);break;case"NonFullScreenPageMode":if(i instanceof oA)switch(i.name){case"UseNone":case"UseOutlines":case"UseThumbs":case"UseOC":a=i.name;break;default:a="UseNone"}break;case"Direction":if(i instanceof oA)switch(i.name){case"L2R":case"R2L":a=i.name;break;default:a="L2R"}break;case"ViewArea":case"ViewClip":case"PrintArea":case"PrintClip":if(i instanceof oA)switch(i.name){case"MediaBox":case"CropBox":case"BleedBox":case"TrimBox":case"ArtBox":a=i.name;break;default:a="CropBox"}break;case"PrintScaling":if(i instanceof oA)switch(i.name){case"None":case"AppDefault":a=i.name;break;default:a="AppDefault"}break;case"Duplex":if(i instanceof oA)switch(i.name){case"Simplex":case"DuplexFlipShortEdge":case"DuplexFlipLongEdge":a=i.name;break;default:a="None"}break;case"PrintPageRange":Array.isArray(i)&&i.length%2==0&&i.every(((A,e,t)=>Number.isInteger(A)&&A>0&&(0===e||A>=t[e-1])&&A<=this.numPages))&&(a=i);break;case"NumCopies":Number.isInteger(i)&&i>0&&(a=i);break;default:R(`Ignoring non-standard key in ViewerPreferences: ${t}.`);continue}void 0!==a?(e||(e=Object.create(null)),e[t]=a):R(`Bad value, for key "${t}", in ViewerPreferences: ${i}.`)}return U(this,"viewerPreferences",e)}get openAction(){const A=this._catDict.get("OpenAction"),e=Object.create(null);if(A instanceof CA){const t=new CA(this.xref);t.set("A",A);const i={url:null,dest:null,action:null};no.parseDestDictionary({destDict:t,resultObj:i}),Array.isArray(i.dest)?e.dest=i.dest:i.action&&(e.action=i.action)}else Array.isArray(A)&&(e.dest=A);return U(this,"openAction",Z(e)>0?e:null)}get attachments(){const A=this._catDict.get("Names");let e=null;if(A instanceof CA&&A.has("EmbeddedFiles")){const t=new dr(A.getRaw("EmbeddedFiles"),this.xref);for(const[A,i]of t.getAll()){const t=new yr(i,this.xref);e||(e=Object.create(null)),e[z(A)]=t.serializable}}return U(this,"attachments",e)}get xfaImages(){const A=this._catDict.get("Names");let e=null;if(A instanceof CA&&A.has("XFAImages")){const t=new dr(A.getRaw("XFAImages"),this.xref);for(const[A,i]of t.getAll())e||(e=new CA(this.xref)),e.set(z(A),i)}return U(this,"xfaImages",e)}_collectJavaScript(){const A=this._catDict.get("Names");let e=null;function t(A,t){if(!(t instanceof CA))return;if(!lA(t.get("S"),"JavaScript"))return;let i=t.get("JS");if(i instanceof fA)i=i.getString();else if("string"!=typeof i)return;i=z(i).replaceAll("\0",""),i&&(e||=new Map).set(A,i)}if(A instanceof CA&&A.has("JavaScript")){const e=new dr(A.getRaw("JavaScript"),this.xref);for(const[A,i]of e.getAll())t(z(A),i)}const i=this._catDict.get("OpenAction");return i&&t("OpenAction",i),e}get jsActions(){const A=this._collectJavaScript();let e=PA(this.xref,this._catDict,h);if(A){e||=Object.create(null);for(const[t,i]of A)t in e?e[t].push(i):e[t]=[i]}return U(this,"jsActions",e)}async fontFallback(A,e){const t=await Promise.all(this.fontCache);for(const i of t)if(i.loadedName===A)return void i.fallback(e)}async cleanup(A=!1){pr(),this.globalImageCache.clear(A),this.pageKidsCountCache.clear(),this.pageIndexCache.clear(),this.pageDictCache.clear(),this.nonBlendModesSet.clear();const e=await Promise.all(this.fontCache);for(const{dict:A}of e)delete A.cacheKey;this.fontCache.clear(),this.builtInCMapCache.clear(),this.standardFontDataCache.clear(),this.systemFontCache.clear()}async getPageDict(A){const e=[this.toplevelPagesDict],t=new hA,i=this._catDict.getRaw("Pages");i instanceof BA&&t.put(i);const a=this.xref,s=this.pageKidsCountCache,n=this.pageIndexCache,g=this.pageDictCache;let r=0;for(;e.length;){const i=e.pop();if(i instanceof BA){const o=s.get(i);if(o>=0&&r+o<=A){r+=o;continue}if(t.has(i))throw new K("Pages tree contains circular reference.");t.put(i);const I=await(g.get(i)||a.fetchAsync(i));if(I instanceof CA){let e=I.getRaw("Type");if(e instanceof BA&&(e=await a.fetchAsync(e)),lA(e,"Page")||!I.has("Kids")){if(s.has(i)||s.put(i,1),n.has(i)||n.put(i,r),r===A)return[I,i];r++;continue}}e.push(I);continue}if(!(i instanceof CA))throw new K("Page dictionary kid reference points to wrong type of object.");const{objId:o}=i;let I=i.getRaw("Count");if(I instanceof BA&&(I=await a.fetchAsync(I)),Number.isInteger(I)&&I>=0&&(o&&!s.has(o)&&s.put(o,I),r+I<=A)){r+=I;continue}let c=i.getRaw("Kids");if(c instanceof BA&&(c=await a.fetchAsync(c)),!Array.isArray(c)){let e=i.getRaw("Type");if(e instanceof BA&&(e=await a.fetchAsync(e)),lA(e,"Page")||!i.has("Kids")){if(r===A)return[i,null];r++;continue}throw new K("Page dictionary kids object is not an array.")}for(let A=c.length-1;A>=0;A--){const t=c[A];e.push(t),i===this.toplevelPagesDict&&t instanceof BA&&!g.has(t)&&g.put(t,a.fetchAsync(t))}}throw new Error(`Page index ${A} not found.`)}async getAllPageDicts(A=!1){const{ignoreErrors:e}=this.pdfManager.evaluatorOptions,t=[{currentNode:this.toplevelPagesDict,posInKids:0}],i=new hA,a=this._catDict.getRaw("Pages");a instanceof BA&&i.put(a);const s=new Map,n=this.xref,g=this.pageIndexCache;let r=0;function o(t){if(t instanceof DA&&!A)throw t;A&&e&&0===r&&(R(`getAllPageDicts - Skipping invalid first page: "${t}".`),t=CA.empty),s.set(r++,[t,null])}for(;t.length>0;){const A=t.at(-1),{currentNode:e,posInKids:a}=A;let C=e.getRaw("Kids");if(C instanceof BA)try{C=await n.fetchAsync(C)}catch(A){o(A);break}if(!Array.isArray(C)){o(new K("Page dictionary kids object is not an array."));break}if(a>=C.length){t.pop();continue}const B=C[a];let h;if(B instanceof BA){if(i.has(B)){o(new K("Pages tree contains circular reference."));break}i.put(B);try{h=await n.fetchAsync(B)}catch(A){o(A);break}}else h=B;if(!(h instanceof CA)){o(new K("Page dictionary kid reference points to wrong type of object."));break}let Q=h.getRaw("Type");if(Q instanceof BA)try{Q=await n.fetchAsync(Q)}catch(A){o(A);break}lA(Q,"Page")||!h.has("Kids")?(I=h,(c=B instanceof BA?B:null)&&!g.has(c)&&g.put(c,r),s.set(r++,[I,c])):t.push({currentNode:h,posInKids:0}),A.posInKids++}var I,c;return s}getPageIndex(A){const e=this.pageIndexCache.get(A);if(void 0!==e)return Promise.resolve(e);const t=this.xref;let i=0;const a=e=>function(e){let i,a=0;return t.fetchAsync(e).then((function(t){if(dA(e,A)&&!uA(t,"Page")&&!(t instanceof CA&&!t.has("Type")&&t.has("Contents")))throw new K("The reference does not point to a /Page dictionary.");if(!t)return null;if(!(t instanceof CA))throw new K("Node must be a dictionary.");return i=t.getRaw("Parent"),t.getAsync("Parent")})).then((function(A){if(!A)return null;if(!(A instanceof CA))throw new K("Parent must be a dictionary.");return A.getAsync("Kids")})).then((function(A){if(!A)return null;const s=[];let n=!1;for(const i of A){if(!(i instanceof BA))throw new K("Kid must be a reference.");if(dA(i,e)){n=!0;break}s.push(t.fetchAsync(i).then((function(A){if(!(A instanceof CA))throw new K("Kid node must be a dictionary.");A.has("Count")?a+=A.get("Count"):a++})))}if(!n)throw new K("Kid reference not found in parent's kids.");return Promise.all(s).then((function(){return[a,i]}))}))}(e).then((e=>{if(!e)return this.pageIndexCache.put(A,i),i;const[t,s]=e;return i+=t,a(s)}));return a(A)}get baseUrl(){const A=this._catDict.get("URI");if(A instanceof CA){const e=A.get("Base");if("string"==typeof e){const A=x(e,null,{tryConvertEncoding:!0});if(A)return U(this,"baseUrl",A.href)}}return U(this,"baseUrl",this.pdfManager.docBaseUrl)}static parseDestDictionary({destDict:A,resultObj:e,docBaseUrl:t=null,docAttachments:i=null}){if(!(A instanceof CA))return void R("parseDestDictionary: `destDict` must be a dictionary.");let a,s,n=A.get("A");if(n instanceof CA||(A.has("Dest")?n=A.get("Dest"):(n=A.get("AA"),n instanceof CA&&(n.has("D")?n=n.get("D"):n.has("U")&&(n=n.get("U"))))),n instanceof CA){const A=n.get("S");if(!(A instanceof oA))return void R("parseDestDictionary: Invalid type in Action dictionary.");const t=A.name;switch(t){case"ResetForm":const A=n.get("Flags"),g=0==(1&("number"==typeof A?A:0)),r=[],o=[];for(const A of n.get("Fields")||[])A instanceof BA?o.push(A.toString()):"string"==typeof A&&r.push(z(A));e.resetForm={fields:r,refs:o,include:g};break;case"URI":a=n.get("URI"),a instanceof oA&&(a="/"+a.name);break;case"GoTo":s=n.get("D");break;case"Launch":case"GoToR":const I=n.get("F");if(I instanceof CA){const A=new yr(I,null,!0),{rawFilename:e}=A.serializable;a=e}else"string"==typeof I&&(a=I);const c=so(n);c&&"string"==typeof a&&(a=a.split("#",1)[0]+"#"+c);const C=n.get("NewWindow");"boolean"==typeof C&&(e.newWindow=C);break;case"GoToE":const B=n.get("T");let h;if(i&&B instanceof CA){const A=B.get("R"),e=B.get("N");lA(A,"C")&&"string"==typeof e&&(h=i[z(e)])}if(h){e.attachment=h;const A=so(n);A&&(e.attachmentDest=A)}else R('parseDestDictionary - unimplemented "GoToE" action.');break;case"Named":const Q=n.get("N");Q instanceof oA&&(e.action=Q.name);break;case"SetOCGState":const l=n.get("State"),E=n.get("PreserveRB");if(!Array.isArray(l)||0===l.length)break;const u=[];for(const A of l)if(A instanceof oA)switch(A.name){case"ON":case"OFF":case"Toggle":u.push(A.name)}else A instanceof BA&&u.push(A.toString());if(u.length!==l.length)break;e.setOCGState={state:u,preserveRB:"boolean"!=typeof E||E};break;case"JavaScript":const d=n.get("JS");let f;d instanceof fA?f=d.getString():"string"==typeof d&&(f=d);const p=f&&jA(z(f));if(p){a=p.url,e.newWindow=p.newWindow;break}default:if("JavaScript"===t||"SubmitForm"===t)break;R(`parseDestDictionary - unsupported action: "${t}".`)}}else A.has("Dest")&&(s=A.get("Dest"));if("string"==typeof a){const A=x(a,t,{addDefaultProtocol:!0,tryConvertEncoding:!0});A&&(e.url=A.href),e.unsafeUrl=a}s&&(s instanceof oA&&(s=s.name),"string"==typeof s?e.dest=z(s):io(s)&&(e.dest=s))}}function go(A,e){if(A instanceof CA)A=A.getRawValues();else if(A instanceof fA)A=A.dict.getRawValues();else if(!Array.isArray(A))return;for(const i of A)((t=i)instanceof BA||t instanceof CA||t instanceof fA||Array.isArray(t))&&e.push(i);var t}class ro{constructor(A,e,t){this.dict=A,this.keys=e,this.xref=t,this.refSet=null}async load(){if(this.xref.stream.isDataLoaded)return;const{keys:A,dict:e}=this;this.refSet=new hA;const t=[];for(const i of A){const A=e.getRaw(i);void 0!==A&&t.push(A)}return this._walk(t)}async _walk(A){const e=[],t=[];for(;A.length;){let i=A.pop();if(i instanceof BA){if(this.refSet.has(i))continue;try{this.refSet.put(i),i=this.xref.fetch(i)}catch(A){if(!(A instanceof yA)){R(`ObjectLoader._walk - requesting all data: "${A}".`),this.refSet=null;const{manager:e}=this.xref.stream;return e.requestAllChunks()}e.push(i),t.push({begin:A.begin,end:A.end})}}if(i instanceof fA){const A=i.getBaseStreams();if(A){let a=!1;for(const e of A)e.isDataLoaded||(a=!0,t.push({begin:e.start,end:e.end}));a&&e.push(i)}}go(i,A)}if(t.length){await this.xref.stream.manager.requestRanges(t);for(const A of e)A instanceof BA&&this.refSet.remove(A);return this._walk(e)}this.refSet=null}}const oo=Symbol(),Io=Symbol(),co=Symbol(),Co=Symbol(),Bo=Symbol(),ho=Symbol(),Qo=Symbol(),lo=Symbol(),Eo=Symbol(),uo=Symbol("content"),fo=Symbol("data"),po=Symbol(),mo=Symbol("extra"),yo=Symbol(),wo=Symbol(),Do=Symbol(),bo=Symbol(),ko=Symbol(),Fo=Symbol(),So=Symbol(),Ro=Symbol(),Go=Symbol(),No=Symbol(),xo=Symbol(),Uo=Symbol(),Mo=Symbol(),Lo=Symbol(),Jo=Symbol(),Ho=Symbol(),Yo=Symbol(),vo=Symbol(),Ko=Symbol(),qo=Symbol(),To=Symbol(),Po=Symbol(),Wo=Symbol(),Zo=Symbol(),Oo=Symbol(),Xo=Symbol(),Vo=Symbol(),jo=Symbol(),zo=Symbol(),_o=Symbol(),$o=Symbol(),AI=Symbol(),eI=Symbol("namespaceId"),tI=Symbol("nodeName"),iI=Symbol(),aI=Symbol(),sI=Symbol(),nI=Symbol(),gI=Symbol(),rI=Symbol(),oI=Symbol(),II=Symbol(),cI=Symbol("root"),CI=Symbol(),BI=Symbol(),hI=Symbol(),QI=Symbol(),lI=Symbol(),EI=Symbol(),uI=Symbol(),dI=Symbol(),fI=Symbol(),pI=Symbol(),mI=Symbol(),yI=Symbol("uid"),wI=Symbol(),DI={config:{id:0,check:A=>A.startsWith("http://www.xfa.org/schema/xci/")},connectionSet:{id:1,check:A=>A.startsWith("http://www.xfa.org/schema/xfa-connection-set/")},datasets:{id:2,check:A=>A.startsWith("http://www.xfa.org/schema/xfa-data/")},form:{id:3,check:A=>A.startsWith("http://www.xfa.org/schema/xfa-form/")},localeSet:{id:4,check:A=>A.startsWith("http://www.xfa.org/schema/xfa-locale-set/")},pdf:{id:5,check:A=>"http://ns.adobe.com/xdp/pdf/"===A},signature:{id:6,check:A=>"http://www.w3.org/2000/09/xmldsig#"===A},sourceSet:{id:7,check:A=>A.startsWith("http://www.xfa.org/schema/xfa-source-set/")},stylesheet:{id:8,check:A=>"http://www.w3.org/1999/XSL/Transform"===A},template:{id:9,check:A=>A.startsWith("http://www.xfa.org/schema/xfa-template/")},xdc:{id:10,check:A=>A.startsWith("http://www.xfa.org/schema/xdc/")},xdp:{id:11,check:A=>"http://ns.adobe.com/xdp/"===A},xfdf:{id:12,check:A=>"http://ns.adobe.com/xfdf/"===A},xhtml:{id:13,check:A=>"http://www.w3.org/1999/xhtml"===A},xmpmeta:{id:14,check:A=>"http://ns.adobe.com/xmpmeta/"===A}},bI={pt:A=>A,cm:A=>A/2.54*72,mm:A=>A/25.4*72,in:A=>72*A,px:A=>A},kI=/([+-]?\d+\.?\d*)(.*)/;function FI(A){return A.startsWith("'")||A.startsWith('"')?A.slice(1,-1):A}function SI({data:A,defaultValue:e,validate:t}){if(!A)return e;A=A.trim();const i=parseInt(A,10);return!isNaN(i)&&t(i)?i:e}function RI({data:A,defaultValue:e,validate:t}){if(!A)return e;A=A.trim();const i=parseFloat(A);return!isNaN(i)&&t(i)?i:e}function GI({data:A,defaultValue:e,validate:t}){return A&&t(A=A.trim())?A:e}function NI(A,e){return GI({data:A,defaultValue:e[0],validate:A=>e.includes(A)})}function xI(A,e="0"){if(e||="0",!A)return xI(e);const t=A.trim().match(kI);if(!t)return xI(e);const[,i,a]=t,s=parseFloat(i);if(isNaN(s))return xI(e);if(0===s)return 0;const n=bI[a];return n?n(s):s}function UI(A){if(!A)return{num:1,den:1};const e=A.trim().split(/\s*:\s*/).map((A=>parseFloat(A))).filter((A=>!isNaN(A)));if(1===e.length&&e.push(1),0===e.length)return{num:1,den:1};const[t,i]=e;return{num:t,den:i}}function MI(A){return A?A.trim().split(/\s+/).map((A=>({excluded:"-"===A[0],viewname:A.substring(1)}))):[]}class LI{static get FAILURE(){return U(this,"FAILURE",new LI(!1,null,null,null))}static get EMPTY(){return U(this,"EMPTY",new LI(!0,null,null,null))}constructor(A,e,t,i){this.success=A,this.html=e,this.bbox=t,this.breakNode=i}isBreak(){return!!this.breakNode}static breakNode(A){return new LI(!1,null,null,A)}static success(A,e=null){return new LI(!0,A,e,null)}}class JI{constructor(A){this.fonts=new Map,this.cache=new Map,this.warned=new Set,this.defaultFont=null,this.add(A)}add(A,e=null){for(const e of A)this.addPdfFont(e);for(const A of this.fonts.values())A.regular||(A.regular=A.italic||A.bold||A.bolditalic);if(!e||0===e.size)return;const t=this.fonts.get("PdfJS-Fallback-PdfJS-XFA");for(const A of e)this.fonts.set(A,t)}addPdfFont(A){const e=A.cssFontInfo,t=e.fontFamily;let i=this.fonts.get(t);i||(i=Object.create(null),this.fonts.set(t,i),this.defaultFont||(this.defaultFont=i));let a="";const s=parseFloat(e.fontWeight);0!==parseFloat(e.italicAngle)?a=s>=700?"bolditalic":"italic":s>=700&&(a="bold"),a||((A.name.includes("Bold")||A.psName?.includes("Bold"))&&(a="bold"),(A.name.includes("Italic")||A.name.endsWith("It")||A.psName?.includes("Italic")||A.psName?.endsWith("It"))&&(a+="italic")),a||(a="regular"),i[a]=A}getDefault(){return this.defaultFont}find(A,e=!0){let t=this.fonts.get(A)||this.cache.get(A);if(t)return t;const i=/,|-|_| |bolditalic|bold|italic|regular|it/gi;let a=A.replaceAll(i,"");if(t=this.fonts.get(a),t)return this.cache.set(A,t),t;a=a.toLowerCase();const s=[];for(const[A,e]of this.fonts.entries())A.replaceAll(i,"").toLowerCase().startsWith(a)&&s.push(e);if(0===s.length)for(const[,A]of this.fonts.entries())A.regular.name?.replaceAll(i,"").toLowerCase().startsWith(a)&&s.push(A);if(0===s.length){a=a.replaceAll(/psmt|mt/gi,"");for(const[A,e]of this.fonts.entries())A.replaceAll(i,"").toLowerCase().startsWith(a)&&s.push(e)}if(0===s.length)for(const A of this.fonts.values())A.regular.name?.replaceAll(i,"").toLowerCase().startsWith(a)&&s.push(A);return s.length>=1?(1!==s.length&&e&&R(`XFA - Too many choices to guess the correct font: ${A}`),this.cache.set(A,s[0]),s[0]):(e&&!this.warned.has(A)&&(this.warned.add(A),R(`XFA - Cannot find the font: ${A}`)),null)}}function HI(A,e){return"italic"===A.posture?"bold"===A.weight?e.bolditalic:e.italic:"bold"===A.weight?e.bold:e.regular}class YI{constructor(A,e,t,i){if(this.lineHeight=t,this.paraMargin=e||{top:0,bottom:0,left:0,right:0},!A)return void([this.pdfFont,this.xfaFont]=this.defaultFont(i));this.xfaFont={typeface:A.typeface,posture:A.posture,weight:A.weight,size:A.size,letterSpacing:A.letterSpacing};const a=i.find(A.typeface);a?(this.pdfFont=HI(A,a),this.pdfFont||([this.pdfFont,this.xfaFont]=this.defaultFont(i))):[this.pdfFont,this.xfaFont]=this.defaultFont(i)}defaultFont(A){const e=A.find("Helvetica",!1)||A.find("Myriad Pro",!1)||A.find("Arial",!1)||A.getDefault();if(e?.regular){const A=e.regular;return[A,{typeface:A.cssFontInfo.fontFamily,posture:"normal",weight:"normal",size:10,letterSpacing:0}]}return[null,{typeface:"Courier",posture:"normal",weight:"normal",size:10,letterSpacing:0}]}}class vI{constructor(A,e,t,i){this.fontFinder=i,this.stack=[new YI(A,e,t,i)]}pushData(A,e,t){const i=this.stack.at(-1);for(const e of["typeface","posture","weight","size","letterSpacing"])A[e]||(A[e]=i.xfaFont[e]);for(const A of["top","bottom","left","right"])isNaN(e[A])&&(e[A]=i.paraMargin[A]);const a=new YI(A,e,t||i.lineHeight,this.fontFinder);a.pdfFont||(a.pdfFont=i.pdfFont),this.stack.push(a)}popFont(){this.stack.pop()}topFont(){return this.stack.at(-1)}}class KI{constructor(A,e,t,i){this.glyphs=[],this.fontSelector=new vI(A,e,t,i),this.extraHeight=0}pushData(A,e,t){this.fontSelector.pushData(A,e,t)}popFont(A){return this.fontSelector.popFont()}addPara(){const A=this.fontSelector.topFont();this.extraHeight+=A.paraMargin.top+A.paraMargin.bottom}addString(A){if(!A)return;const e=this.fontSelector.topFont(),t=e.xfaFont.size;if(e.pdfFont){const i=e.xfaFont.letterSpacing,a=e.pdfFont,s=a.lineHeight||1.2,n=e.lineHeight||Math.max(1.2,s)*t,g=s-(void 0===a.lineGap?.2:a.lineGap),r=Math.max(1,g)*t,o=t/1e3,I=a.defaultWidth||a.charsToGlyphs(" ")[0].width;for(const e of A.split(/[\u2029\n]/)){const A=a.encodeString(e).join(""),t=a.charsToGlyphs(A);for(const A of t){const e=A.width||I;this.glyphs.push([e*o+i,n,r,A.unicode,!1])}this.glyphs.push([0,0,0,"\n",!0])}this.glyphs.pop()}else{for(const e of A.split(/[\u2029\n]/)){for(const A of e.split(""))this.glyphs.push([t,1.2*t,t,A,!1]);this.glyphs.push([0,0,0,"\n",!0])}this.glyphs.pop()}}compute(A){let e=-1,t=0,i=0,a=0,s=0,n=0,g=!1,r=!0;for(let o=0,I=this.glyphs.length;oA?(i=Math.max(i,s),s=0,a+=n,n=l,e=-1,t=0,g=!0,r=!1):(n=Math.max(l,n),t=s,s+=I,e=o):s+I>A?(a+=n,n=l,-1!==e?(o=e,i=Math.max(i,t),s=0,e=-1,t=0):(i=Math.max(i,s),s=I),g=!0,r=!1):(s+=I,n=Math.max(l,n))}return i=Math.max(i,s),a+=n+this.extraHeight,{width:1.02*i,height:a,isBroken:g}}}const qI=/^[^.[]+/,TI=/^[^\]]+/,PI=new Map([["$data",(A,e)=>A.datasets?A.datasets.data:A],["$record",(A,e)=>(A.datasets?A.datasets.data:A)[Uo]()[0]],["$template",(A,e)=>A.template],["$connectionSet",(A,e)=>A.connectionSet],["$form",(A,e)=>A.form],["$layout",(A,e)=>A.layout],["$host",(A,e)=>A.host],["$dataWindow",(A,e)=>A.dataWindow],["$event",(A,e)=>A.event],["!",(A,e)=>A.datasets],["$xfa",(A,e)=>A],["xfa",(A,e)=>A],["$",(A,e)=>e]]),WI=new WeakMap;function ZI(A,e,t=!0){let i=A.match(qI);if(!i)return null;let[a]=i;const s=[{name:a,cacheName:"."+a,index:0,js:null,formCalc:null,operator:0}];let n=a.length;for(;n0&&I.push(A)}if(0!==I.length||g||0!==r)A=isFinite(o)?I.filter((A=>oA[o])):I.flat();else{const t=e[Ho]();if(!(e=t))return null;r=-1,A=[e]}}return 0===A.length?null:A}function XI(A,e,t){const i=ZI(t);if(!i)return null;if(i.some((A=>1===A.operator)))return null;const a=PI.get(i[0].name);let s=0;a?(A=a(A,e),s=1):A=e||A;for(let e=i.length;sA[uI]())).join("")}get[zI](){const A=Object.getPrototypeOf(this);if(!A._attributes){const e=A._attributes=new Set;for(const A of Object.getOwnPropertyNames(this)){if(null===this[A]||this[A]instanceof hc||this[A]instanceof Qc)break;e.add(A)}}return U(this,zI,A._attributes)}[Xo](A){let e=this;for(;e;){if(e===A)return!0;e=e[Ho]()}return!1}[Ho](){return this[rc]}[Jo](){return this[Ho]()}[Uo](A=null){return A?this[A]:this[_I]}[po](){const A=Object.create(null);this[uo]&&(A.$content=this[uo]);for(const e of Object.getOwnPropertyNames(this)){const t=this[e];null!==t&&(t instanceof hc?A[e]=t[po]():t instanceof Qc?t.isEmpty()||(A[e]=t.dump()):A[e]=t)}return A}[mI](){return null}[fI](){return LI.EMPTY}*[Mo](){for(const A of this[Uo]())yield A}*[tc](A,e){for(const t of this[Mo]())if(!A||e===A.has(t[tI])){const A=this[ko](),e=t[fI](A);e.success||(this[mo].failingNode=t),yield e}}[wo](){return null}[Io](A,e){this[mo].children.push(A)}[ko](){}[Co]({filter:A=null,include:e=!0}){if(this[mo].generator){const A=this[ko](),e=this[mo].failingNode[fI](A);if(!e.success)return e;e.html&&this[Io](e.html,e.bbox),delete this[mo].failingNode}else this[mo].generator=this[tc](A,e);for(;;){const A=this[mo].generator.next();if(A.done)break;const e=A.value;if(!e.success)return e;e.html&&this[Io](e.html,e.bbox)}return this[mo].generator=null,LI.EMPTY}[QI](A){this[Ic]=new Set(Object.keys(A))}[ac](A){const e=this[zI],t=this[Ic];return[...A].filter((A=>e.has(A)&&!t.has(A)))}[CI](A,e=new Set){for(const t of this[_I])t[oc](A,e)}[oc](A,e){const t=this[ic](A,e);t?this[VI](t,A,e):this[CI](A,e)}[ic](A,e){const{use:t,usehref:i}=this;if(!t&&!i)return null;let a=null,s=null,n=null,g=t;if(i?(g=i,i.startsWith("#som(")&&i.endsWith(")")?s=i.slice("#som(".length,-1):i.startsWith(".#som(")&&i.endsWith(")")?s=i.slice(".#som(".length,-1):i.startsWith("#")?n=i.slice(1):i.startsWith(".#")&&(n=i.slice(2))):t.startsWith("#")?n=t.slice(1):s=t,this.use=this.usehref="",n?a=A.get(n):(a=OI(A.get(cI),this,s,!0,!1),a&&(a=a[0])),!a)return R(`XFA - Invalid prototype reference: ${g}.`),null;if(a[tI]!==this[tI])return R(`XFA - Incompatible prototype: ${a[tI]} !== ${this[tI]}.`),null;if(e.has(a))return R("XFA - Cycle detected in prototypes use."),null;e.add(a);const r=a[ic](A,e);return r&&a[VI](r,A,e),a[CI](A,e),e.delete(a),a}[VI](A,e,t){if(t.has(A))R("XFA - Cycle detected in prototypes use.");else{!this[uo]&&A[uo]&&(this[uo]=A[uo]),new Set(t).add(A);for(const e of this[ac](A[Ic]))this[e]=A[e],this[Ic]&&this[Ic].add(e);for(const i of Object.getOwnPropertyNames(this)){if(this[zI].has(i))continue;const a=this[i],s=A[i];if(a instanceof Qc){for(const A of a[_I])A[oc](e,t);for(let i=a[_I].length,n=s[_I].length;ihc[$I](A))):"object"==typeof A&&null!==A?Object.assign({},A):A}[lo](){const A=Object.create(Object.getPrototypeOf(this));for(const e of Object.getOwnPropertySymbols(this))try{A[e]=this[e]}catch{U(A,e,this[e])}A[yI]=`${A[tI]}${Cc++}`,A[_I]=[];for(const e of Object.getOwnPropertyNames(this)){if(this[zI].has(e)){A[e]=hc[$I](this[e]);continue}const t=this[e];A[e]=t instanceof Qc?new Qc(t[nc]):null}for(const e of this[_I]){const t=e[tI],i=e[lo]();A[_I].push(i),i[rc]=A,null===A[t]?A[t]=i:A[t][_I].push(i)}return A}[Uo](A=null){return A?this[_I].filter((e=>e[tI]===A)):this[_I]}[Fo](A){return this[A]}[So](A,e,t=!0){return Array.from(this[Ro](A,e,t))}*[Ro](A,e,t=!0){if("parent"!==A){for(const t of this[_I])t[tI]===A&&(yield t),t.name===A&&(yield t),(e||t[_o]())&&(yield*t[Ro](A,e,!1));t&&this[zI].has(A)&&(yield new lc(this,A,this[A]))}else yield this[rc]}}class Qc{constructor(A=1/0){this[nc]=A,this[_I]=[]}get isXFAObject(){return!1}get isXFAObjectArray(){return!0}push(A){return this[_I].length<=this[nc]?(this[_I].push(A),!0):(R(`XFA - node "${A[tI]}" accepts no more than ${this[nc]} children`),!1)}isEmpty(){return 0===this[_I].length}dump(){return 1===this[_I].length?this[_I][0][po]():this[_I].map((A=>A[po]()))}[lo](){const A=new Qc(this[nc]);return A[_I]=this[_I].map((A=>A[lo]())),A}get children(){return this[_I]}clear(){this[_I].length=0}}class lc{constructor(A,e,t){this[rc]=A,this[tI]=e,this[uo]=t,this[Eo]=!1,this[yI]="attribute"+Cc++}[Ho](){return this[rc]}[Oo](){return!0}[Go](){return this[uo].trim()}[lI](A){A=A.value||"",this[uo]=A.toString()}[uI](){return this[uo]}[Xo](A){return this[rc]===A||this[rc][Xo](A)}}class Ec extends hc{constructor(A,e,t={}){if(super(A,e),this[uo]="",this[Ac]=null,"#text"!==e){const A=new Map;this[jI]=A;for(const[e,i]of Object.entries(t))A.set(e,new lc(this,e,i));if(t.hasOwnProperty(iI)){const A=t[iI].xfa.dataNode;void 0!==A&&("dataGroup"===A?this[Ac]=!1:"dataValue"===A&&(this[Ac]=!0))}}this[Eo]=!1}[pI](A){const e=this[tI];if("#text"===e)return void A.push(OA(this[uo]));const t=$(e),i=this[eI]===Bc?"xfa:":"";A.push(`<${i}${t}`);for(const[e,t]of this[jI].entries()){const i=$(e);A.push(` ${i}="${OA(t[uo])}"`)}if(null!==this[Ac]&&(this[Ac]?A.push(' xfa:dataNode="dataValue"'):A.push(' xfa:dataNode="dataGroup"')),this[uo]||0!==this[_I].length){if(A.push(">"),this[uo])"string"==typeof this[uo]?A.push(OA(this[uo])):this[uo][pI](A);else for(const e of this[_I])e[pI](A);A.push(``)}else A.push("/>")}[aI](A){if(this[uo]){const A=new Ec(this[eI],"#text");this[co](A),A[uo]=this[uo],this[uo]=""}return this[co](A),!0}[nI](A){this[uo]+=A}[yo](){if(this[uo]&&this[_I].length>0){const A=new Ec(this[eI],"#text");this[co](A),A[uo]=this[uo],delete this[uo]}}[fI](){return"#text"===this[tI]?LI.success({name:"#text",value:this[uo]}):LI.EMPTY}[Uo](A=null){return A?this[_I].filter((e=>e[tI]===A)):this[_I]}[bo](){return this[jI]}[Fo](A){const e=this[jI].get(A);return void 0!==e?e:this[Uo](A)}*[Ro](A,e){const t=this[jI].get(A);t&&(yield t);for(const t of this[_I])t[tI]===A&&(yield t),e&&(yield*t[Ro](A,e))}*[Do](A,e){const t=this[jI].get(A);!t||e&&t[Eo]||(yield t);for(const t of this[_I])yield*t[Do](A,e)}*[xo](A,e,t){for(const i of this[_I])i[tI]!==A||t&&i[Eo]||(yield i),e&&(yield*i[xo](A,e,t))}[Oo](){return null===this[Ac]?0===this[_I].length||this[_I][0][eI]===DI.xhtml.id:this[Ac]}[Go](){return null===this[Ac]?0===this[_I].length?this[uo].trim():this[_I][0][eI]===DI.xhtml.id?this[_I][0][uI]().trim():null:this[uo].trim()}[lI](A){A=A.value||"",this[uo]=A.toString()}[po](A=!1){const e=Object.create(null);A&&(e.$ns=this[eI]),this[uo]&&(e.$content=this[uo]),e.$name=this[tI],e.children=[];for(const t of this[_I])e.children.push(t[po](A));e.attributes=Object.create(null);for(const[A,t]of this[jI])e.attributes[A]=t[uo];return e}}class uc extends hc{constructor(A,e){super(A,e),this[uo]=""}[nI](A){this[uo]+=A}[yo](){}}class dc extends uc{constructor(A,e,t){super(A,e),this[gc]=t}[yo](){this[uo]=GI({data:this[uo],defaultValue:this[gc][0],validate:A=>this[gc].includes(A)})}[Bo](A){super[Bo](A),delete this[gc]}}class fc extends uc{[yo](){this[uo]=this[uo].trim()}}class pc extends uc{constructor(A,e,t,i){super(A,e),this[ec]=t,this[cc]=i}[yo](){this[uo]=SI({data:this[uo],defaultValue:this[ec],validate:this[cc]})}[Bo](A){super[Bo](A),delete this[ec],delete this[cc]}}class mc extends pc{constructor(A,e){super(A,e,0,(A=>1===A))}}class yc extends pc{constructor(A,e){super(A,e,1,(A=>0===A))}}function wc(A){return"string"==typeof A?"0px":Number.isInteger(A)?`${A}px`:`${A.toFixed(2)}px`}const Dc={anchorType(A,e){const t=A[Jo]();if(t&&(!t.layout||"position"===t.layout))switch("transform"in e||(e.transform=""),A.anchorType){case"bottomCenter":e.transform+="translate(-50%, -100%)";break;case"bottomLeft":e.transform+="translate(0,-100%)";break;case"bottomRight":e.transform+="translate(-100%,-100%)";break;case"middleCenter":e.transform+="translate(-50%,-50%)";break;case"middleLeft":e.transform+="translate(0,-50%)";break;case"middleRight":e.transform+="translate(-100%,-50%)";break;case"topCenter":e.transform+="translate(-50%,0)";break;case"topRight":e.transform+="translate(-100%,0)"}},dimensions(A,e){const t=A[Jo]();let i=A.w;const a=A.h;if(t.layout?.includes("row")){const e=t[mo],a=A.colSpan;let s;-1===a?(s=e.columnWidths.slice(e.currentColumn).reduce(((A,e)=>A+e),0),e.currentColumn=0):(s=e.columnWidths.slice(e.currentColumn,e.currentColumn+a).reduce(((A,e)=>A+e),0),e.currentColumn=(e.currentColumn+A.colSpan)%e.columnWidths.length),isNaN(s)||(i=A.w=s)}e.width=""!==i?wc(i):"auto",e.height=""!==a?wc(a):"auto"},position(A,e){const t=A[Jo]();t?.layout&&"position"!==t.layout||(e.position="absolute",e.left=wc(A.x),e.top=wc(A.y))},rotate(A,e){A.rotate&&("transform"in e||(e.transform=""),e.transform+=`rotate(-${A.rotate}deg)`,e.transformOrigin="top left")},presence(A,e){switch(A.presence){case"invisible":e.visibility="hidden";break;case"hidden":case"inactive":e.display="none"}},hAlign(A,e){if("para"===A[tI])switch(A.hAlign){case"justifyAll":e.textAlign="justify-all";break;case"radix":e.textAlign="left";break;default:e.textAlign=A.hAlign}else switch(A.hAlign){case"left":e.alignSelf="start";break;case"center":e.alignSelf="center";break;case"right":e.alignSelf="end"}},margin(A,e){A.margin&&(e.margin=A.margin[mI]().margin)}};function bc(A,e){"position"===A[Jo]().layout&&(A.minW>0&&(e.minWidth=wc(A.minW)),A.maxW>0&&(e.maxWidth=wc(A.maxW)),A.minH>0&&(e.minHeight=wc(A.minH)),A.maxH>0&&(e.maxHeight=wc(A.maxH)))}function kc(A,e,t,i,a,s){const n=new KI(e,t,i,a);return"string"==typeof A?n.addString(A):A[gI](n),n.compute(s)}function Fc(A,e){let t=null,i=null,a=!1;if((!A.w||!A.h)&&A.value){let s=0,n=0;A.margin&&(s=A.margin.leftInset+A.margin.rightInset,n=A.margin.topInset+A.margin.bottomInset);let g=null,r=null;A.para&&(r=Object.create(null),g=""===A.para.lineHeight?null:A.para.lineHeight,r.top=""===A.para.spaceAbove?0:A.para.spaceAbove,r.bottom=""===A.para.spaceBelow?0:A.para.spaceBelow,r.left=""===A.para.marginLeft?0:A.para.marginLeft,r.right=""===A.para.marginRight?0:A.para.marginRight);let o=A.font;if(!o){const e=A[Yo]();let t=A[Ho]();for(;t&&t!==e;){if(t.font){o=t.font;break}t=t[Ho]()}}const I=(A.w||e.width)-s,c=A[vo].fontFinder;if(A.value.exData&&A.value.exData[uo]&&"text/html"===A.value.exData.contentType){const e=kc(A.value.exData[uo],o,r,g,c,I);i=e.width,t=e.height,a=e.isBroken}else{const e=A.value[uI]();if(e){const A=kc(e,o,r,g,c,I);i=A.width,t=A.height,a=A.isBroken}}null===i||A.w||(i+=s),null===t||A.h||(t+=n)}return{w:i,h:t,isBroken:a}}function Sc(A,e,t){let i;if(""!==A.w&&""!==A.h)i=[A.x,A.y,A.w,A.h];else{if(!t)return null;let a=A.w;if(""===a){if(0===A.maxW){const e=A[Jo]();a="position"===e.layout&&""!==e.w?0:A.minW}else a=Math.min(A.maxW,t.width);e.attributes.style.width=wc(a)}let s=A.h;if(""===s){if(0===A.maxH){const e=A[Jo]();s="position"===e.layout&&""!==e.h?0:A.minH}else s=Math.min(A.maxH,t.height);e.attributes.style.height=wc(s)}i=[A.x,A.y,a,s]}return i}function Rc(A){const e=A[Jo]();if(e.layout?.includes("row")){const t=e[mo],i=A.colSpan;let a;a=-1===i?t.columnWidths.slice(t.currentColumn).reduce(((A,e)=>A+e),0):t.columnWidths.slice(t.currentColumn,t.currentColumn+i).reduce(((A,e)=>A+e),0),isNaN(a)||(A.w=a)}e.layout&&"position"!==e.layout&&(A.x=A.y=0),"table"===A.layout&&""===A.w&&Array.isArray(A.columnWidths)&&(A.w=A.columnWidths.reduce(((A,e)=>A+e),0))}function Gc(A){switch(A.layout){case"position":default:return"xfaPosition";case"lr-tb":return"xfaLrTb";case"rl-row":return"xfaRlRow";case"rl-tb":return"xfaRlTb";case"row":return"xfaRow";case"table":return"xfaTable";case"tb":return"xfaTb"}}function Nc(A,...e){const t=Object.create(null);for(const i of e){const e=A[i];if(null!==e)if(Dc.hasOwnProperty(i))Dc[i](A,t);else if(e instanceof hc){const A=e[mI]();A?Object.assign(t,A):R(`(DEBUG) - XFA - style for ${i} not implemented yet`)}}return t}function xc(A,e){const{attributes:t}=e,{style:i}=t,a={name:"div",attributes:{class:["xfaWrapper"],style:Object.create(null)},children:[]};if(t.class.push("xfaWrapped"),A.border){const{widths:t,insets:s}=A.border[mo];let n,g,r=s[0],o=s[3];const I=s[0]+s[2],c=s[1]+s[3];switch(A.border.hand){case"even":r-=t[0]/2,o-=t[3]/2,n=`calc(100% + ${(t[1]+t[3])/2-c}px)`,g=`calc(100% + ${(t[0]+t[2])/2-I}px)`;break;case"left":r-=t[0],o-=t[3],n=`calc(100% + ${t[1]+t[3]-c}px)`,g=`calc(100% + ${t[0]+t[2]-I}px)`;break;case"right":n=c?`calc(100% - ${c}px)`:"100%",g=I?`calc(100% - ${I}px)`:"100%"}const C=["xfaBorder"];Lc(A.border)&&C.push("xfaPrintOnly");const B={name:"div",attributes:{class:C,style:{top:`${r}px`,left:`${o}px`,width:n,height:g}},children:[]};for(const A of["border","borderWidth","borderColor","borderRadius","borderStyle"])void 0!==i[A]&&(B.attributes.style[A]=i[A],delete i[A]);a.children.push(B,e)}else a.children.push(e);for(const A of["background","backgroundClip","top","left","width","height","minWidth","minHeight","maxWidth","maxHeight","transform","transformOrigin","visibility"])void 0!==i[A]&&(a.attributes.style[A]=i[A],delete i[A]);return a.attributes.style.position="absolute"===i.position?"absolute":"relative",delete i.position,i.alignSelf&&(a.attributes.style.alignSelf=i.alignSelf,delete i.alignSelf),a}function Uc(A){const e=xI(A.textIndent,"0px");if(e>=0)return;const t="padding"+("left"==("right"===A.textAlign?"right":"left")?"Left":"Right"),i=xI(A[t],"0px");A[t]=i-e+"px"}function Mc(A,e){switch(A.access){case"nonInteractive":e.push("xfaNonInteractive");break;case"readOnly":e.push("xfaReadOnly");break;case"protected":e.push("xfaDisabled")}}function Lc(A){return A.relevant.length>0&&!A.relevant[0].excluded&&"print"===A.relevant[0].viewname}function Jc(A){const e=A[Yo]()[mo].paraStack;return e.length?e.at(-1):null}function Hc(A,e,t){if(t.attributes.class?.includes("xfaRich")){e&&(""===A.h&&(e.height="auto"),""===A.w&&(e.width="auto"));const i=Jc(A);if(i){const A=t.attributes.style;switch(A.display="flex",A.flexDirection="column",i.vAlign){case"top":A.justifyContent="start";break;case"bottom":A.justifyContent="end";break;case"middle":A.justifyContent="center"}const e=i[mI]();for(const[t,i]of Object.entries(e))t in A||(A[t]=i)}}}function Yc(A,e,t,i){if(!t)return void delete i.fontFamily;const a=FI(A.typeface);i.fontFamily=`"${a}"`;const s=t.find(a);if(s){const{fontFamily:t}=s.regular.cssFontInfo;t!==a&&(i.fontFamily=`"${t}"`);const n=Jc(e);if(n&&""!==n.lineHeight)return;if(i.lineHeight)return;const g=HI(A,s);g&&(i.lineHeight=Math.max(1.2,g.lineHeight))}}function vc(A){const e=x(A,null,{addDefaultProtocol:!0,tryConvertEncoding:!0});return e?e.href:null}function Kc(A,e){return{name:"div",attributes:{class:["lr-tb"===A.layout?"xfaLr":"xfaRl"]},children:e}}function qc(A){if(!A[mo])return null;const e={name:"div",attributes:A[mo].attributes,children:A[mo].children};if(A[mo].failingNode){const t=A[mo].failingNode[wo]();t&&(A.layout.endsWith("-tb")?e.children.push(Kc(A,[t])):e.children.push(t))}return 0===e.children.length?null:e}function Tc(A,e,t){const i=A[mo],a=i.availableSpace,[s,n,g,r]=t;switch(A.layout){case"position":i.width=Math.max(i.width,s+g),i.height=Math.max(i.height,n+r),i.children.push(e);break;case"lr-tb":case"rl-tb":i.line&&1!==i.attempt||(i.line=Kc(A,[]),i.children.push(i.line),i.numberInLine=0),i.numberInLine+=1,i.line.children.push(e),0===i.attempt?(i.currentWidth+=g,i.height=Math.max(i.height,i.prevHeight+r)):(i.currentWidth=g,i.prevHeight=i.height,i.height+=r,i.attempt=0),i.width=Math.max(i.width,i.currentWidth);break;case"rl-row":case"row":{i.children.push(e),i.width+=g,i.height=Math.max(i.height,r);const A=wc(i.height);for(const e of i.children)e.attributes.style.height=A;break}case"table":case"tb":i.width=Math.min(a.width,Math.max(i.width,g)),i.height+=r,i.children.push(e)}}function Pc(A){const e=A[mo].availableSpace,t=A.margin?A.margin.topInset+A.margin.bottomInset:0,i=A.margin?A.margin.leftInset+A.margin.rightInset:0;switch(A.layout){case"lr-tb":case"rl-tb":return 0===A[mo].attempt?{width:e.width-i-A[mo].currentWidth,height:e.height-t-A[mo].prevHeight}:{width:e.width-i,height:e.height-t-A[mo].height};case"rl-row":case"row":return{width:A[mo].columnWidths.slice(A[mo].currentColumn).reduce(((A,e)=>A+e)),height:e.height-i};case"table":case"tb":return{width:e.width-i,height:e.height-t-A[mo].height};default:return e}}function Wc(A,e){if(null===A[Yo]()[mo].firstUnsplittable)return!0;if(0===A.w||0===A.h)return!0;const t=A[Jo](),i=t[mo]?.attempt||0,[,a,s,n]=function(A){let e,t,i=""===A.w?NaN:A.w,a=""===A.h?NaN:A.h,[s,n]=[0,0];switch(A.anchorType||""){case"bottomCenter":[s,n]=[i/2,a];break;case"bottomLeft":[s,n]=[0,a];break;case"bottomRight":[s,n]=[i,a];break;case"middleCenter":[s,n]=[i/2,a/2];break;case"middleLeft":[s,n]=[0,a/2];break;case"middleRight":[s,n]=[i,a/2];break;case"topCenter":[s,n]=[i/2,0];break;case"topRight":[s,n]=[i,0]}switch(A.rotate||0){case 0:[e,t]=[-s,-n];break;case 90:[e,t]=[-n,s],[i,a]=[a,-i];break;case 180:[e,t]=[s,n],[i,a]=[-i,-a];break;case 270:[e,t]=[n,-s],[i,a]=[-a,i]}return[A.x+e+Math.min(0,i),A.y+t+Math.min(0,a),Math.abs(i),Math.abs(a)]}(A);switch(t.layout){case"lr-tb":case"rl-tb":return 0===i?A[Yo]()[mo].noLayoutFailure?""!==A.w?Math.round(s-e.width)<=2:e.width>2:!(""!==A.h&&Math.round(n-e.height)>2)&&(""!==A.w?Math.round(s-e.width)<=2||0===t[mo].numberInLine&&e.height>2:e.width>2):!!A[Yo]()[mo].noLayoutFailure||!(""!==A.h&&Math.round(n-e.height)>2)&&(""===A.w||Math.round(s-e.width)<=2||!t[zo]())&&e.height>2;case"table":case"tb":return!!A[Yo]()[mo].noLayoutFailure||(""===A.h||A[jo]()?(""===A.w||Math.round(s-e.width)<=2||!t[zo]())&&e.height>2:Math.round(n-e.height)<=2);case"position":return!!A[Yo]()[mo].noLayoutFailure||(""===A.h||Math.round(n+a-e.height)<=2||n+a>A[Yo]()[mo].currentContentArea.h);case"rl-row":case"row":return!!A[Yo]()[mo].noLayoutFailure||""===A.h||Math.round(n-e.height)<=2;default:return!0}}const Zc=DI.template.id,Oc="http://www.w3.org/2000/svg",Xc=/^H(\d+)$/,Vc=new Set(["image/gif","image/jpeg","image/jpg","image/pjpeg","image/png","image/apng","image/x-png","image/bmp","image/x-ms-bmp","image/tiff","image/tif","application/octet-stream"]),jc=[[[66,77],"image/bmp"],[[255,216,255],"image/jpeg"],[[73,73,42,0],"image/tiff"],[[77,77,0,42],"image/tiff"],[[71,73,70,56,57,97],"image/gif"],[[137,80,78,71,13,10,26,10],"image/png"]];function zc(A){if(!A||!A.border)return{w:0,h:0};const e=A.border[No]();return e?{w:e.widths[0]+e.widths[2]+e.insets[0]+e.insets[2],h:e.widths[1]+e.widths[3]+e.insets[1]+e.insets[3]}:{w:0,h:0}}function _c(A){return A.margin&&(A.margin.topInset||A.margin.rightInset||A.margin.bottomInset||A.margin.leftInset)}function $c(A,e){if(!A.value){const e=new Bh({});A[co](e),A.value=e}A.value[lI](e)}function*AC(A){for(const e of A[Uo]())e instanceof $B?yield*e[Mo]():yield e}function eC(A){return"error"===A.validate?.nullTest}function tC(A){for(;A;){if(!A.traversal)return void(A[EI]=A[Ho]()[EI]);if(A[EI])return;let e=null;for(const t of A.traversal[Uo]())if("next"===t.operation){e=t;break}if(!e||!e.ref)return void(A[EI]=A[Ho]()[EI]);const t=A[Yo]();A[EI]=++t[EI];const i=t[BI](e.ref,A);if(!i)return;A=i[0]}}function iC(A,e){const t=A.assist;if(t){const A=t[fI]();A&&(e.title=A);const i=t.role.match(Xc);if(i){const A="heading",t=i[1];e.role=A,e["aria-level"]=t}}if("table"===A.layout)e.role="table";else if("row"===A.layout)e.role="row";else{const t=A[Ho]();"row"===t.layout&&(e.role="TH"===t.assist?.role?"columnheader":"cell")}}function aC(A){if(!A.assist)return null;const e=A.assist;return e.speak&&""!==e.speak[uo]?e.speak[uo]:e.toolTip?e.toolTip[uo]:null}function sC(A){return LI.success({name:"div",attributes:{class:["xfaRich"],style:Object.create(null)},children:[{name:"span",attributes:{style:Object.create(null)},value:A}]})}function nC(A){const e=A[Yo]();null===e[mo].firstUnsplittable&&(e[mo].firstUnsplittable=A,e[mo].noLayoutFailure=!0)}function gC(A){const e=A[Yo]();e[mo].firstUnsplittable===A&&(e[mo].noLayoutFailure=!1)}function rC(A){if(A[mo])return!1;if(A[mo]=Object.create(null),"auto"===A.targetType)return!1;const e=A[Yo]();let t=null;if(A.target){if(t=e[BI](A.target,A[Ho]()),!t)return!1;t=t[0]}const{currentPageArea:i,currentContentArea:a}=e[mo];if("pageArea"===A.targetType)return t instanceof NB||(t=null),A.startNew?(A[mo].target=t||i,!0):!(!t||t===i||(A[mo].target=t,0));t instanceof xC||(t=null);const s=t&&t[Ho]();let n,g=s;if(A.startNew)if(t){const A=s.contentArea.children,e=A.indexOf(a),i=A.indexOf(t);-1!==e&&eA,i[mo].noLayoutFailure=!0;const n=e[fI](t);A[Io](n.html,n.bbox),i[mo].noLayoutFailure=a,e[Jo]=s}class IC extends fc{constructor(A){super(Zc,"appearanceFilter"),this.id=A.id||"",this.type=NI(A.type,["optional","required"]),this.use=A.use||"",this.usehref=A.usehref||""}}class cC extends hc{constructor(A){super(Zc,"arc",!0),this.circular=SI({data:A.circular,defaultValue:0,validate:A=>1===A}),this.hand=NI(A.hand,["even","left","right"]),this.id=A.id||"",this.startAngle=RI({data:A.startAngle,defaultValue:0,validate:A=>!0}),this.sweepAngle=RI({data:A.sweepAngle,defaultValue:360,validate:A=>!0}),this.use=A.use||"",this.usehref=A.usehref||"",this.edge=null,this.fill=null}[fI](){const A=this.edge||new PC({}),e=A[mI](),t=Object.create(null);let i;"visible"===this.fill?.presence?Object.assign(t,this.fill[mI]()):t.fill="transparent",t.strokeWidth=wc("visible"===A.presence?A.thickness:0),t.stroke=e.color;const a={xmlns:Oc,style:{width:"100%",height:"100%",overflow:"visible"}};if(360===this.sweepAngle)i={name:"ellipse",attributes:{xmlns:Oc,cx:"50%",cy:"50%",rx:"50%",ry:"50%",style:t}};else{const A=this.startAngle*Math.PI/180,e=this.sweepAngle*Math.PI/180,s=this.sweepAngle>180?1:0,[n,g,r,o]=[50*(1+Math.cos(A)),50*(1-Math.sin(A)),50*(1+Math.cos(A+e)),50*(1-Math.sin(A+e))];i={name:"path",attributes:{xmlns:Oc,d:`M ${n} ${g} A 50 50 0 ${s} 0 ${r} ${o}`,vectorEffect:"non-scaling-stroke",style:t}},Object.assign(a,{viewBox:"0 0 100 100",preserveAspectRatio:"none"})}const s={name:"svg",children:[i],attributes:a};return _c(this[Ho]()[Ho]())?LI.success({name:"div",attributes:{style:{display:"inline",width:"100%",height:"100%"}},children:[s]}):(s.attributes.style.position="absolute",LI.success(s))}}class CC extends hc{constructor(A){super(Zc,"area",!0),this.colSpan=SI({data:A.colSpan,defaultValue:1,validate:A=>A>=1||-1===A}),this.id=A.id||"",this.name=A.name||"",this.relevant=MI(A.relevant),this.use=A.use||"",this.usehref=A.usehref||"",this.x=xI(A.x,"0pt"),this.y=xI(A.y,"0pt"),this.desc=null,this.extras=null,this.area=new Qc,this.draw=new Qc,this.exObject=new Qc,this.exclGroup=new Qc,this.field=new Qc,this.subform=new Qc,this.subformSet=new Qc}*[Mo](){yield*AC(this)}[_o](){return!0}[Zo](){return!0}[Io](A,e){const[t,i,a,s]=e;this[mo].width=Math.max(this[mo].width,t+a),this[mo].height=Math.max(this[mo].height,i+s),this[mo].children.push(A)}[ko](){return this[mo].availableSpace}[fI](A){const e=Nc(this,"position"),t={style:e,id:this[yI],class:["xfaArea"]};Lc(this)&&t.class.push("xfaPrintOnly"),this.name&&(t.xfaName=this.name);const i=[];this[mo]={children:i,width:0,height:0,availableSpace:A};const a=this[Co]({filter:new Set(["area","draw","field","exclGroup","subform","subformSet"]),include:!0});if(!a.success)return a.isBreak()?a:(delete this[mo],LI.FAILURE);e.width=wc(this[mo].width),e.height=wc(this[mo].height);const s={name:"div",attributes:t,children:i},n=[this.x,this.y,this[mo].width,this[mo].height];return delete this[mo],LI.success(s,n)}}class BC extends hc{constructor(A){super(Zc,"assist",!0),this.id=A.id||"",this.role=A.role||"",this.use=A.use||"",this.usehref=A.usehref||"",this.speak=null,this.toolTip=null}[fI](){return this.toolTip?.[uo]||null}}class hC extends hc{constructor(A){super(Zc,"barcode",!0),this.charEncoding=GI({data:A.charEncoding?A.charEncoding.toLowerCase():"",defaultValue:"",validate:A=>["utf-8","big-five","fontspecific","gbk","gb-18030","gb-2312","ksc-5601","none","shift-jis","ucs-2","utf-16"].includes(A)||A.match(/iso-8859-\d{2}/)}),this.checksum=NI(A.checksum,["none","1mod10","1mod10_1mod11","2mod10","auto"]),this.dataColumnCount=SI({data:A.dataColumnCount,defaultValue:-1,validate:A=>A>=0}),this.dataLength=SI({data:A.dataLength,defaultValue:-1,validate:A=>A>=0}),this.dataPrep=NI(A.dataPrep,["none","flateCompress"]),this.dataRowCount=SI({data:A.dataRowCount,defaultValue:-1,validate:A=>A>=0}),this.endChar=A.endChar||"",this.errorCorrectionLevel=SI({data:A.errorCorrectionLevel,defaultValue:-1,validate:A=>A>=0&&A<=8}),this.id=A.id||"",this.moduleHeight=xI(A.moduleHeight,"5mm"),this.moduleWidth=xI(A.moduleWidth,"0.25mm"),this.printCheckDigit=SI({data:A.printCheckDigit,defaultValue:0,validate:A=>1===A}),this.rowColumnRatio=UI(A.rowColumnRatio),this.startChar=A.startChar||"",this.textLocation=NI(A.textLocation,["below","above","aboveEmbedded","belowEmbedded","none"]),this.truncate=SI({data:A.truncate,defaultValue:0,validate:A=>1===A}),this.type=NI(A.type?A.type.toLowerCase():"",["aztec","codabar","code2of5industrial","code2of5interleaved","code2of5matrix","code2of5standard","code3of9","code3of9extended","code11","code49","code93","code128","code128a","code128b","code128c","code128sscc","datamatrix","ean8","ean8add2","ean8add5","ean13","ean13add2","ean13add5","ean13pwcd","fim","logmars","maxicode","msi","pdf417","pdf417macro","plessey","postauscust2","postauscust3","postausreplypaid","postausstandard","postukrm4scc","postusdpbc","postusimb","postusstandard","postus5zip","qrcode","rfid","rss14","rss14expanded","rss14limited","rss14stacked","rss14stackedomni","rss14truncated","telepen","ucc128","ucc128random","ucc128sscc","upca","upcaadd2","upcaadd5","upcapwcd","upce","upceadd2","upceadd5","upcean2","upcean5","upsmaxicode"]),this.upsMode=NI(A.upsMode,["usCarrier","internationalCarrier","secureSymbol","standardSymbol"]),this.use=A.use||"",this.usehref=A.usehref||"",this.wideNarrowRatio=UI(A.wideNarrowRatio),this.encrypt=null,this.extras=null}}class QC extends hc{constructor(A){super(Zc,"bind",!0),this.match=NI(A.match,["once","dataRef","global","none"]),this.ref=A.ref||"",this.picture=null}}class lC extends hc{constructor(A){super(Zc,"bindItems"),this.connection=A.connection||"",this.labelRef=A.labelRef||"",this.ref=A.ref||"",this.valueRef=A.valueRef||""}}class EC extends hc{constructor(A){super(Zc,"bookend"),this.id=A.id||"",this.leader=A.leader||"",this.trailer=A.trailer||"",this.use=A.use||"",this.usehref=A.usehref||""}}class uC extends mc{constructor(A){super(Zc,"boolean"),this.id=A.id||"",this.name=A.name||"",this.use=A.use||"",this.usehref=A.usehref||""}[fI](A){return sC(1===this[uo]?"1":"0")}}class dC extends hc{constructor(A){super(Zc,"border",!0),this.break=NI(A.break,["close","open"]),this.hand=NI(A.hand,["even","left","right"]),this.id=A.id||"",this.presence=NI(A.presence,["visible","hidden","inactive","invisible"]),this.relevant=MI(A.relevant),this.use=A.use||"",this.usehref=A.usehref||"",this.corner=new Qc(4),this.edge=new Qc(4),this.extras=null,this.fill=null,this.margin=null}[No](){if(!this[mo]){const A=this.edge.children.slice();if(A.length<4){const e=A.at(-1)||new PC({});for(let t=A.length;t<4;t++)A.push(e)}const e=A.map((A=>A.thickness)),t=[0,0,0,0];this.margin&&(t[0]=this.margin.topInset,t[1]=this.margin.rightInset,t[2]=this.margin.bottomInset,t[3]=this.margin.leftInset),this[mo]={widths:e,insets:t,edges:A}}return this[mo]}[mI](){const{edges:A}=this[No](),e=A.map((A=>{const e=A[mI]();return e.color||="#000000",e})),t=Object.create(null);if(this.margin&&Object.assign(t,this.margin[mI]()),"visible"===this.fill?.presence&&Object.assign(t,this.fill[mI]()),this.corner.children.some((A=>0!==A.radius))){const A=this.corner.children.map((A=>A[mI]()));if(2===A.length||3===A.length){const e=A.at(-1);for(let t=A.length;t<4;t++)A.push(e)}t.borderRadius=A.map((A=>A.radius)).join(" ")}switch(this.presence){case"invisible":case"hidden":t.borderStyle="";break;case"inactive":t.borderStyle="none";break;default:t.borderStyle=e.map((A=>A.style)).join(" ")}return t.borderWidth=e.map((A=>A.width)).join(" "),t.borderColor=e.map((A=>A.color)).join(" "),t}}class fC extends hc{constructor(A){super(Zc,"break",!0),this.after=NI(A.after,["auto","contentArea","pageArea","pageEven","pageOdd"]),this.afterTarget=A.afterTarget||"",this.before=NI(A.before,["auto","contentArea","pageArea","pageEven","pageOdd"]),this.beforeTarget=A.beforeTarget||"",this.bookendLeader=A.bookendLeader||"",this.bookendTrailer=A.bookendTrailer||"",this.id=A.id||"",this.overflowLeader=A.overflowLeader||"",this.overflowTarget=A.overflowTarget||"",this.overflowTrailer=A.overflowTrailer||"",this.startNew=SI({data:A.startNew,defaultValue:0,validate:A=>1===A}),this.use=A.use||"",this.usehref=A.usehref||"",this.extras=null}}class pC extends hc{constructor(A){super(Zc,"breakAfter",!0),this.id=A.id||"",this.leader=A.leader||"",this.startNew=SI({data:A.startNew,defaultValue:0,validate:A=>1===A}),this.target=A.target||"",this.targetType=NI(A.targetType,["auto","contentArea","pageArea"]),this.trailer=A.trailer||"",this.use=A.use||"",this.usehref=A.usehref||"",this.script=null}}class mC extends hc{constructor(A){super(Zc,"breakBefore",!0),this.id=A.id||"",this.leader=A.leader||"",this.startNew=SI({data:A.startNew,defaultValue:0,validate:A=>1===A}),this.target=A.target||"",this.targetType=NI(A.targetType,["auto","contentArea","pageArea"]),this.trailer=A.trailer||"",this.use=A.use||"",this.usehref=A.usehref||"",this.script=null}[fI](A){return this[mo]={},LI.FAILURE}}class yC extends hc{constructor(A){super(Zc,"button",!0),this.highlight=NI(A.highlight,["inverted","none","outline","push"]),this.id=A.id||"",this.use=A.use||"",this.usehref=A.usehref||"",this.extras=null}[fI](A){const e=this[Ho]()[Ho](),t={name:"button",attributes:{id:this[yI],class:["xfaButton"],style:{}},children:[]};for(const A of e.event.children){if("click"!==A.activity||!A.script)continue;const e=jA(A.script[uo]);if(!e)continue;const i=vc(e.url);i&&t.children.push({name:"a",attributes:{id:"link"+this[yI],href:i,newWindow:e.newWindow,class:["xfaLink"],style:{}},children:[]})}return LI.success(t)}}class wC extends hc{constructor(A){super(Zc,"calculate",!0),this.id=A.id||"",this.override=NI(A.override,["disabled","error","ignore","warning"]),this.use=A.use||"",this.usehref=A.usehref||"",this.extras=null,this.message=null,this.script=null}}class DC extends hc{constructor(A){super(Zc,"caption",!0),this.id=A.id||"",this.placement=NI(A.placement,["left","bottom","inline","right","top"]),this.presence=NI(A.presence,["visible","hidden","inactive","invisible"]),this.reserve=Math.ceil(xI(A.reserve)),this.use=A.use||"",this.usehref=A.usehref||"",this.extras=null,this.font=null,this.margin=null,this.para=null,this.value=null}[lI](A){$c(this,A)}[No](A){if(!this[mo]){let{width:e,height:t}=A;switch(this.placement){case"left":case"right":case"inline":e=this.reserve<=0?e:this.reserve;break;case"top":case"bottom":t=this.reserve<=0?t:this.reserve}this[mo]=Fc(this,{width:e,height:t})}return this[mo]}[fI](A){if(!this.value)return LI.EMPTY;this[oI]();const e=this.value[fI](A).html;if(!e)return this[rI](),LI.EMPTY;const t=this.reserve;if(this.reserve<=0){const{w:e,h:t}=this[No](A);switch(this.placement){case"left":case"right":case"inline":this.reserve=e;break;case"top":case"bottom":this.reserve=t}}const i=[];"string"==typeof e?i.push({name:"#text",value:e}):i.push(e);const a=Nc(this,"font","margin","visibility");switch(this.placement){case"left":case"right":this.reserve>0&&(a.width=wc(this.reserve));break;case"top":case"bottom":this.reserve>0&&(a.height=wc(this.reserve))}return Hc(this,null,e),this[rI](),this.reserve=t,LI.success({name:"div",attributes:{style:a,class:["xfaCaption"]},children:i})}}class bC extends fc{constructor(A){super(Zc,"certificate"),this.id=A.id||"",this.name=A.name||"",this.use=A.use||"",this.usehref=A.usehref||""}}class kC extends hc{constructor(A){super(Zc,"certificates",!0),this.credentialServerPolicy=NI(A.credentialServerPolicy,["optional","required"]),this.id=A.id||"",this.url=A.url||"",this.urlPolicy=A.urlPolicy||"",this.use=A.use||"",this.usehref=A.usehref||"",this.encryption=null,this.issuers=null,this.keyUsage=null,this.oids=null,this.signing=null,this.subjectDNs=null}}class FC extends hc{constructor(A){super(Zc,"checkButton",!0),this.id=A.id||"",this.mark=NI(A.mark,["default","check","circle","cross","diamond","square","star"]),this.shape=NI(A.shape,["square","round"]),this.size=xI(A.size,"10pt"),this.use=A.use||"",this.usehref=A.usehref||"",this.border=null,this.extras=null,this.margin=null}[fI](A){const e=Nc("margin"),t=wc(this.size);let i,a,s;e.width=e.height=t;const n=this[Ho]()[Ho](),g=n.items.children.length&&n.items.children[0][fI]().html||[],r={on:(void 0!==g[0]?g[0]:"on").toString(),off:(void 0!==g[1]?g[1]:"off").toString()},o=(n.value?.[uI]()||"off")===r.on||void 0,I=n[Jo](),c=n[yI];let C;I instanceof eB?(s=I[yI],i="radio",a="xfaRadio",C=I[fo]?.[yI]||I[yI]):(i="checkbox",a="xfaCheckbox",C=n[fo]?.[yI]||n[yI]);const B={name:"input",attributes:{class:[a],style:e,fieldId:c,dataId:C,type:i,checked:o,xfaOn:r.on,xfaOff:r.off,"aria-label":aC(n),"aria-required":!1}};return s&&(B.attributes.name=s),eC(n)&&(B.attributes["aria-required"]=!0,B.attributes.required=!0),LI.success({name:"label",attributes:{class:["xfaLabel"]},children:[B]})}}class SC extends hc{constructor(A){super(Zc,"choiceList",!0),this.commitOn=NI(A.commitOn,["select","exit"]),this.id=A.id||"",this.open=NI(A.open,["userControl","always","multiSelect","onEntry"]),this.textEntry=SI({data:A.textEntry,defaultValue:0,validate:A=>1===A}),this.use=A.use||"",this.usehref=A.usehref||"",this.border=null,this.extras=null,this.margin=null}[fI](A){const e=Nc(this,"border","margin"),t=this[Ho]()[Ho](),i={fontSize:`calc(${t.font?.size||10}px * var(--scale-factor))`},a=[];if(t.items.children.length>0){const A=t.items;let e=0,s=0;2===A.children.length&&(e=A.children[0].save,s=1-e);const n=A.children[e][fI]().html,g=A.children[s][fI]().html;let r=!1;const o=t.value?.[uI]()||"";for(let A=0,e=n.length;AMath.min(Math.max(0,parseInt(A.trim(),10)),255))).map((A=>isNaN(A)?0:A));return s.length<3||([t,i,a]=s),{r:t,g:i,b:a}}(A.value):"",this.extras=null}[Ko](){return!1}[mI](){return this.value?V.makeHexColor(this.value.r,this.value.g,this.value.b):null}}class GC extends hc{constructor(A){super(Zc,"comb"),this.id=A.id||"",this.numberOfCells=SI({data:A.numberOfCells,defaultValue:0,validate:A=>A>=0}),this.use=A.use||"",this.usehref=A.usehref||""}}class NC extends hc{constructor(A){super(Zc,"connect",!0),this.connection=A.connection||"",this.id=A.id||"",this.ref=A.ref||"",this.usage=NI(A.usage,["exportAndImport","exportOnly","importOnly"]),this.use=A.use||"",this.usehref=A.usehref||"",this.picture=null}}class xC extends hc{constructor(A){super(Zc,"contentArea",!0),this.h=xI(A.h),this.id=A.id||"",this.name=A.name||"",this.relevant=MI(A.relevant),this.use=A.use||"",this.usehref=A.usehref||"",this.w=xI(A.w),this.x=xI(A.x,"0pt"),this.y=xI(A.y,"0pt"),this.desc=null,this.extras=null}[fI](A){const e={left:wc(this.x),top:wc(this.y),width:wc(this.w),height:wc(this.h)},t=["xfaContentarea"];return Lc(this)&&t.push("xfaPrintOnly"),LI.success({name:"div",children:[],attributes:{style:e,class:t,id:this[yI]}})}}class UC extends hc{constructor(A){super(Zc,"corner",!0),this.id=A.id||"",this.inverted=SI({data:A.inverted,defaultValue:0,validate:A=>1===A}),this.join=NI(A.join,["square","round"]),this.presence=NI(A.presence,["visible","hidden","inactive","invisible"]),this.radius=xI(A.radius),this.stroke=NI(A.stroke,["solid","dashDot","dashDotDot","dashed","dotted","embossed","etched","lowered","raised"]),this.thickness=xI(A.thickness,"0.5pt"),this.use=A.use||"",this.usehref=A.usehref||"",this.color=null,this.extras=null}[mI](){const A=Nc(this,"visibility");return A.radius=wc("square"===this.join?0:this.radius),A}}class MC extends uc{constructor(A){super(Zc,"date"),this.id=A.id||"",this.name=A.name||"",this.use=A.use||"",this.usehref=A.usehref||""}[yo](){const A=this[uo].trim();this[uo]=A?new Date(A):null}[fI](A){return sC(this[uo]?this[uo].toString():"")}}class LC extends uc{constructor(A){super(Zc,"dateTime"),this.id=A.id||"",this.name=A.name||"",this.use=A.use||"",this.usehref=A.usehref||""}[yo](){const A=this[uo].trim();this[uo]=A?new Date(A):null}[fI](A){return sC(this[uo]?this[uo].toString():"")}}class JC extends hc{constructor(A){super(Zc,"dateTimeEdit",!0),this.hScrollPolicy=NI(A.hScrollPolicy,["auto","off","on"]),this.id=A.id||"",this.picker=NI(A.picker,["host","none"]),this.use=A.use||"",this.usehref=A.usehref||"",this.border=null,this.comb=null,this.extras=null,this.margin=null}[fI](A){const e=Nc(this,"border","font","margin"),t=this[Ho]()[Ho](),i={name:"input",attributes:{type:"text",fieldId:t[yI],dataId:t[fo]?.[yI]||t[yI],class:["xfaTextfield"],style:e,"aria-label":aC(t),"aria-required":!1}};return eC(t)&&(i.attributes["aria-required"]=!0,i.attributes.required=!0),LI.success({name:"label",attributes:{class:["xfaLabel"]},children:[i]})}}class HC extends uc{constructor(A){super(Zc,"decimal"),this.fracDigits=SI({data:A.fracDigits,defaultValue:2,validate:A=>!0}),this.id=A.id||"",this.leadDigits=SI({data:A.leadDigits,defaultValue:-1,validate:A=>!0}),this.name=A.name||"",this.use=A.use||"",this.usehref=A.usehref||""}[yo](){const A=parseFloat(this[uo].trim());this[uo]=isNaN(A)?null:A}[fI](A){return sC(null!==this[uo]?this[uo].toString():"")}}class YC extends hc{constructor(A){super(Zc,"defaultUi",!0),this.id=A.id||"",this.use=A.use||"",this.usehref=A.usehref||"",this.extras=null}}class vC extends hc{constructor(A){super(Zc,"desc",!0),this.id=A.id||"",this.use=A.use||"",this.usehref=A.usehref||"",this.boolean=new Qc,this.date=new Qc,this.dateTime=new Qc,this.decimal=new Qc,this.exData=new Qc,this.float=new Qc,this.image=new Qc,this.integer=new Qc,this.text=new Qc,this.time=new Qc}}class KC extends dc{constructor(A){super(Zc,"digestMethod",["","SHA1","SHA256","SHA512","RIPEMD160"]),this.id=A.id||"",this.use=A.use||"",this.usehref=A.usehref||""}}class qC extends hc{constructor(A){super(Zc,"digestMethods",!0),this.id=A.id||"",this.type=NI(A.type,["optional","required"]),this.use=A.use||"",this.usehref=A.usehref||"",this.digestMethod=new Qc}}class TC extends hc{constructor(A){super(Zc,"draw",!0),this.anchorType=NI(A.anchorType,["topLeft","bottomCenter","bottomLeft","bottomRight","middleCenter","middleLeft","middleRight","topCenter","topRight"]),this.colSpan=SI({data:A.colSpan,defaultValue:1,validate:A=>A>=1||-1===A}),this.h=A.h?xI(A.h):"",this.hAlign=NI(A.hAlign,["left","center","justify","justifyAll","radix","right"]),this.id=A.id||"",this.locale=A.locale||"",this.maxH=xI(A.maxH,"0pt"),this.maxW=xI(A.maxW,"0pt"),this.minH=xI(A.minH,"0pt"),this.minW=xI(A.minW,"0pt"),this.name=A.name||"",this.presence=NI(A.presence,["visible","hidden","inactive","invisible"]),this.relevant=MI(A.relevant),this.rotate=SI({data:A.rotate,defaultValue:0,validate:A=>A%90==0}),this.use=A.use||"",this.usehref=A.usehref||"",this.w=A.w?xI(A.w):"",this.x=xI(A.x,"0pt"),this.y=xI(A.y,"0pt"),this.assist=null,this.border=null,this.caption=null,this.desc=null,this.extras=null,this.font=null,this.keep=null,this.margin=null,this.para=null,this.traversal=null,this.ui=null,this.value=null,this.setProperty=new Qc}[lI](A){$c(this,A)}[fI](A){if(tC(this),"hidden"===this.presence||"inactive"===this.presence)return LI.EMPTY;Rc(this),this[oI]();const e=this.w,t=this.h,{w:i,h:a,isBroken:s}=Fc(this,A);if(i&&""===this.w){if(s&&this[Jo]()[zo]())return this[rI](),LI.FAILURE;this.w=i}if(a&&""===this.h&&(this.h=a),nC(this),!Wc(this,A))return this.w=e,this.h=t,this[rI](),LI.FAILURE;gC(this);const n=Nc(this,"font","hAlign","dimensions","position","presence","rotate","anchorType","border","margin");bc(this,n),n.margin&&(n.padding=n.margin,delete n.margin);const g=["xfaDraw"];this.font&&g.push("xfaFont"),Lc(this)&&g.push("xfaPrintOnly");const r={style:n,id:this[yI],class:g};this.name&&(r.xfaName=this.name);const o={name:"div",attributes:r,children:[]};iC(this,r);const I=Sc(this,o,A),c=this.value?this.value[fI](A).html:null;return null===c?(this.w=e,this.h=t,this[rI](),LI.success(xc(this,o),I)):(o.children.push(c),Hc(this,n,c),this.w=e,this.h=t,this[rI](),LI.success(xc(this,o),I))}}class PC extends hc{constructor(A){super(Zc,"edge",!0),this.cap=NI(A.cap,["square","butt","round"]),this.id=A.id||"",this.presence=NI(A.presence,["visible","hidden","inactive","invisible"]),this.stroke=NI(A.stroke,["solid","dashDot","dashDotDot","dashed","dotted","embossed","etched","lowered","raised"]),this.thickness=xI(A.thickness,"0.5pt"),this.use=A.use||"",this.usehref=A.usehref||"",this.color=null,this.extras=null}[mI](){const A=Nc(this,"visibility");if(Object.assign(A,{linecap:this.cap,width:wc(this.thickness),color:this.color?this.color[mI]():"#000000",style:""}),"visible"!==this.presence)A.style="none";else switch(this.stroke){case"solid":A.style="solid";break;case"dashDot":case"dashDotDot":case"dashed":A.style="dashed";break;case"dotted":A.style="dotted";break;case"embossed":A.style="ridge";break;case"etched":A.style="groove";break;case"lowered":A.style="inset";break;case"raised":A.style="outset"}return A}}class WC extends dc{constructor(A){super(Zc,"encoding",["adbe.x509.rsa_sha1","adbe.pkcs7.detached","adbe.pkcs7.sha1"]),this.id=A.id||"",this.use=A.use||"",this.usehref=A.usehref||""}}class ZC extends hc{constructor(A){super(Zc,"encodings",!0),this.id=A.id||"",this.type=NI(A.type,["optional","required"]),this.use=A.use||"",this.usehref=A.usehref||"",this.encoding=new Qc}}class OC extends hc{constructor(A){super(Zc,"encrypt",!0),this.id=A.id||"",this.use=A.use||"",this.usehref=A.usehref||"",this.certificate=null}}class XC extends hc{constructor(A){super(Zc,"encryptData",!0),this.id=A.id||"",this.operation=NI(A.operation,["encrypt","decrypt"]),this.target=A.target||"",this.use=A.use||"",this.usehref=A.usehref||"",this.filter=null,this.manifest=null}}class VC extends hc{constructor(A){super(Zc,"encryption",!0),this.id=A.id||"",this.type=NI(A.type,["optional","required"]),this.use=A.use||"",this.usehref=A.usehref||"",this.certificate=new Qc}}class jC extends dc{constructor(A){super(Zc,"encryptionMethod",["","AES256-CBC","TRIPLEDES-CBC","AES128-CBC","AES192-CBC"]),this.id=A.id||"",this.use=A.use||"",this.usehref=A.usehref||""}}class zC extends hc{constructor(A){super(Zc,"encryptionMethods",!0),this.id=A.id||"",this.type=NI(A.type,["optional","required"]),this.use=A.use||"",this.usehref=A.usehref||"",this.encryptionMethod=new Qc}}class _C extends hc{constructor(A){super(Zc,"event",!0),this.activity=NI(A.activity,["click","change","docClose","docReady","enter","exit","full","indexChange","initialize","mouseDown","mouseEnter","mouseExit","mouseUp","postExecute","postOpen","postPrint","postSave","postSign","postSubmit","preExecute","preOpen","prePrint","preSave","preSign","preSubmit","ready","validationState"]),this.id=A.id||"",this.listen=NI(A.listen,["refOnly","refAndDescendents"]),this.name=A.name||"",this.ref=A.ref||"",this.use=A.use||"",this.usehref=A.usehref||"",this.extras=null,this.encryptData=null,this.execute=null,this.script=null,this.signData=null,this.submit=null}}class $C extends uc{constructor(A){super(Zc,"exData"),this.contentType=A.contentType||"",this.href=A.href||"",this.id=A.id||"",this.maxLength=SI({data:A.maxLength,defaultValue:-1,validate:A=>A>=-1}),this.name=A.name||"",this.rid=A.rid||"",this.transferEncoding=NI(A.transferEncoding,["none","base64","package"]),this.use=A.use||"",this.usehref=A.usehref||""}[Wo](){return"text/html"===this.contentType}[aI](A){return("text/html"===this.contentType&&A[eI]===DI.xhtml.id||"text/xml"===this.contentType)&&(this[uo]=A,!0)}[fI](A){return"text/html"===this.contentType&&this[uo]?this[uo][fI](A):LI.EMPTY}}class AB extends hc{constructor(A){super(Zc,"exObject",!0),this.archive=A.archive||"",this.classId=A.classId||"",this.codeBase=A.codeBase||"",this.codeType=A.codeType||"",this.id=A.id||"",this.name=A.name||"",this.use=A.use||"",this.usehref=A.usehref||"",this.extras=null,this.boolean=new Qc,this.date=new Qc,this.dateTime=new Qc,this.decimal=new Qc,this.exData=new Qc,this.exObject=new Qc,this.float=new Qc,this.image=new Qc,this.integer=new Qc,this.text=new Qc,this.time=new Qc}}class eB extends hc{constructor(A){super(Zc,"exclGroup",!0),this.access=NI(A.access,["open","nonInteractive","protected","readOnly"]),this.accessKey=A.accessKey||"",this.anchorType=NI(A.anchorType,["topLeft","bottomCenter","bottomLeft","bottomRight","middleCenter","middleLeft","middleRight","topCenter","topRight"]),this.colSpan=SI({data:A.colSpan,defaultValue:1,validate:A=>A>=1||-1===A}),this.h=A.h?xI(A.h):"",this.hAlign=NI(A.hAlign,["left","center","justify","justifyAll","radix","right"]),this.id=A.id||"",this.layout=NI(A.layout,["position","lr-tb","rl-row","rl-tb","row","table","tb"]),this.maxH=xI(A.maxH,"0pt"),this.maxW=xI(A.maxW,"0pt"),this.minH=xI(A.minH,"0pt"),this.minW=xI(A.minW,"0pt"),this.name=A.name||"",this.presence=NI(A.presence,["visible","hidden","inactive","invisible"]),this.relevant=MI(A.relevant),this.use=A.use||"",this.usehref=A.usehref||"",this.w=A.w?xI(A.w):"",this.x=xI(A.x,"0pt"),this.y=xI(A.y,"0pt"),this.assist=null,this.bind=null,this.border=null,this.calculate=null,this.caption=null,this.desc=null,this.extras=null,this.margin=null,this.para=null,this.traversal=null,this.validate=null,this.connect=new Qc,this.event=new Qc,this.field=new Qc,this.setProperty=new Qc}[Zo](){return!0}[Ko](){return!0}[lI](A){for(const e of this.field.children){if(!e.value){const A=new Bh({});e[co](A),e.value=A}e.value[lI](A)}}[zo](){return this.layout.endsWith("-tb")&&0===this[mo].attempt&&this[mo].numberInLine>0||this[Ho]()[zo]()}[jo](){const A=this[Jo]();return!!A[jo]()&&(void 0!==this[mo]._isSplittable?this[mo]._isSplittable:"position"===this.layout||this.layout.includes("row")?(this[mo]._isSplittable=!1,!1):!(A.layout?.endsWith("-tb")&&0!==A[mo].numberInLine||(this[mo]._isSplittable=!0,0)))}[wo](){return qc(this)}[Io](A,e){Tc(this,A,e)}[ko](){return Pc(this)}[fI](A){if(tC(this),"hidden"===this.presence||"inactive"===this.presence||0===this.h||0===this.w)return LI.EMPTY;Rc(this);const e=[],t={id:this[yI],class:[]};Mc(this,t.class),this[mo]||(this[mo]=Object.create(null)),Object.assign(this[mo],{children:e,attributes:t,attempt:0,line:null,numberInLine:0,availableSpace:{width:Math.min(this.w||1/0,A.width),height:Math.min(this.h||1/0,A.height)},width:0,height:0,prevHeight:0,currentWidth:0});const i=this[jo]();if(i||nC(this),!Wc(this,A))return LI.FAILURE;const a=new Set(["field"]);if(this.layout.includes("row")){const A=this[Jo]().columnWidths;Array.isArray(A)&&A.length>0&&(this[mo].columnWidths=A,this[mo].currentColumn=0)}const s=Nc(this,"anchorType","dimensions","position","presence","border","margin","hAlign"),n=["xfaExclgroup"],g=Gc(this);g&&n.push(g),Lc(this)&&n.push("xfaPrintOnly"),t.style=s,t.class=n,this.name&&(t.xfaName=this.name),this[oI]();const r="lr-tb"===this.layout||"rl-tb"===this.layout,o=r?2:1;for(;this[mo].attemptA>=1||-1===A}),this.h=A.h?xI(A.h):"",this.hAlign=NI(A.hAlign,["left","center","justify","justifyAll","radix","right"]),this.id=A.id||"",this.locale=A.locale||"",this.maxH=xI(A.maxH,"0pt"),this.maxW=xI(A.maxW,"0pt"),this.minH=xI(A.minH,"0pt"),this.minW=xI(A.minW,"0pt"),this.name=A.name||"",this.presence=NI(A.presence,["visible","hidden","inactive","invisible"]),this.relevant=MI(A.relevant),this.rotate=SI({data:A.rotate,defaultValue:0,validate:A=>A%90==0}),this.use=A.use||"",this.usehref=A.usehref||"",this.w=A.w?xI(A.w):"",this.x=xI(A.x,"0pt"),this.y=xI(A.y,"0pt"),this.assist=null,this.bind=null,this.border=null,this.calculate=null,this.caption=null,this.desc=null,this.extras=null,this.font=null,this.format=null,this.items=new Qc(2),this.keep=null,this.margin=null,this.para=null,this.traversal=null,this.ui=null,this.validate=null,this.value=null,this.bindItems=new Qc,this.connect=new Qc,this.event=new Qc,this.setProperty=new Qc}[Zo](){return!0}[lI](A){$c(this,A)}[fI](A){if(tC(this),!this.ui){let A;switch(this.ui=new ch({}),this.ui[vo]=this[vo],this[co](this.ui),this.items.children.length){case 0:A=new sh({}),this.ui.textEdit=A;break;case 1:A=new FC({}),this.ui.checkButton=A;break;case 2:A=new SC({}),this.ui.choiceList=A}this.ui[co](A)}if(!this.ui||"hidden"===this.presence||"inactive"===this.presence||0===this.h||0===this.w)return LI.EMPTY;this.caption&&delete this.caption[mo],this[oI]();const e=this.caption?this.caption[fI](A).html:null,t=this.w,i=this.h;let a=0,s=0;this.margin&&(a=this.margin.leftInset+this.margin.rightInset,s=this.margin.topInset+this.margin.bottomInset);let n=null;if(""===this.w||""===this.h){let e=null,t=null,i=0,g=0;if(this.ui.checkButton)i=g=this.ui.checkButton.size;else{const{w:e,h:t}=Fc(this,A);null!==e?(i=e,g=t):g=function(A,e=!1){let t=null;if(A){const e=FI(A.typeface),i=A[vo].fontFinder.find(e);t=HI(A,i)}if(!t)return{lineHeight:12,lineGap:2,lineNoGap:10};const i=A.size||10,a=t.lineHeight?Math.max(e?0:1.2,t.lineHeight):1.2,s=void 0===t.lineGap?.2:t.lineGap;return{lineHeight:a*i,lineGap:s*i,lineNoGap:Math.max(1,a-s)*i}}(this.font,!0).lineNoGap}if(n=zc(this.ui[No]()),i+=n.w,g+=n.h,this.caption){const{w:a,h:s,isBroken:n}=this.caption[No](A);if(n&&this[Jo]()[zo]())return this[rI](),LI.FAILURE;switch(e=a,t=s,this.caption.placement){case"left":case"right":case"inline":e+=i;break;case"top":case"bottom":t+=g}}else e=i,t=g;e&&""===this.w&&(e+=a,this.w=Math.min(this.maxW<=0?1/0:this.maxW,this.minW+1A>=1&&A<=5}),this.appearanceFilter=null,this.certificates=null,this.digestMethods=null,this.encodings=null,this.encryptionMethods=null,this.handler=null,this.lockDocument=null,this.mdp=null,this.reasons=null,this.timeStamp=null}}class gB extends uc{constructor(A){super(Zc,"float"),this.id=A.id||"",this.name=A.name||"",this.use=A.use||"",this.usehref=A.usehref||""}[yo](){const A=parseFloat(this[uo].trim());this[uo]=isNaN(A)?null:A}[fI](A){return sC(null!==this[uo]?this[uo].toString():"")}}class rB extends hc{constructor(A){super(Zc,"font",!0),this.baselineShift=xI(A.baselineShift),this.fontHorizontalScale=RI({data:A.fontHorizontalScale,defaultValue:100,validate:A=>A>=0}),this.fontVerticalScale=RI({data:A.fontVerticalScale,defaultValue:100,validate:A=>A>=0}),this.id=A.id||"",this.kerningMode=NI(A.kerningMode,["none","pair"]),this.letterSpacing=xI(A.letterSpacing,"0"),this.lineThrough=SI({data:A.lineThrough,defaultValue:0,validate:A=>1===A||2===A}),this.lineThroughPeriod=NI(A.lineThroughPeriod,["all","word"]),this.overline=SI({data:A.overline,defaultValue:0,validate:A=>1===A||2===A}),this.overlinePeriod=NI(A.overlinePeriod,["all","word"]),this.posture=NI(A.posture,["normal","italic"]),this.size=xI(A.size,"10pt"),this.typeface=A.typeface||"Courier",this.underline=SI({data:A.underline,defaultValue:0,validate:A=>1===A||2===A}),this.underlinePeriod=NI(A.underlinePeriod,["all","word"]),this.use=A.use||"",this.usehref=A.usehref||"",this.weight=NI(A.weight,["normal","bold"]),this.extras=null,this.fill=null}[Bo](A){super[Bo](A),this[vo].usedTypefaces.add(this.typeface)}[mI](){const A=Nc(this,"fill"),e=A.color;return e&&("#000000"===e?delete A.color:e.startsWith("#")||(A.background=e,A.backgroundClip="text",A.color="transparent")),this.baselineShift&&(A.verticalAlign=wc(this.baselineShift)),A.fontKerning="none"===this.kerningMode?"none":"normal",A.letterSpacing=wc(this.letterSpacing),0!==this.lineThrough&&(A.textDecoration="line-through",2===this.lineThrough&&(A.textDecorationStyle="double")),0!==this.overline&&(A.textDecoration="overline",2===this.overline&&(A.textDecorationStyle="double")),A.fontStyle=this.posture,A.fontSize=wc(.99*this.size),Yc(this,this,this[vo].fontFinder,A),0!==this.underline&&(A.textDecoration="underline",2===this.underline&&(A.textDecorationStyle="double")),A.fontWeight=this.weight,A}}class oB extends hc{constructor(A){super(Zc,"format",!0),this.id=A.id||"",this.use=A.use||"",this.usehref=A.usehref||"",this.extras=null,this.picture=null}}class IB extends fc{constructor(A){super(Zc,"handler"),this.id=A.id||"",this.type=NI(A.type,["optional","required"]),this.use=A.use||"",this.usehref=A.usehref||""}}class cB extends hc{constructor(A){super(Zc,"hyphenation"),this.excludeAllCaps=SI({data:A.excludeAllCaps,defaultValue:0,validate:A=>1===A}),this.excludeInitialCap=SI({data:A.excludeInitialCap,defaultValue:0,validate:A=>1===A}),this.hyphenate=SI({data:A.hyphenate,defaultValue:0,validate:A=>1===A}),this.id=A.id||"",this.pushCharacterCount=SI({data:A.pushCharacterCount,defaultValue:3,validate:A=>A>=0}),this.remainCharacterCount=SI({data:A.remainCharacterCount,defaultValue:3,validate:A=>A>=0}),this.use=A.use||"",this.usehref=A.usehref||"",this.wordCharacterCount=SI({data:A.wordCharacterCount,defaultValue:7,validate:A=>A>=0})}}class CB extends fc{constructor(A){super(Zc,"image"),this.aspect=NI(A.aspect,["fit","actual","height","none","width"]),this.contentType=A.contentType||"",this.href=A.href||"",this.id=A.id||"",this.name=A.name||"",this.transferEncoding=NI(A.transferEncoding,["base64","none","package"]),this.use=A.use||"",this.usehref=A.usehref||""}[fI](){if(this.contentType&&!Vc.has(this.contentType.toLowerCase()))return LI.EMPTY;let A=this[vo].images&&this[vo].images.get(this.href);if(!A&&(this.href||!this[uo]))return LI.EMPTY;if(A||"base64"!==this.transferEncoding||(A=P(atob(this[uo]))),!A)return LI.EMPTY;if(!this.contentType){for(const[e,t]of jc)if(A.length>e.length&&e.every(((e,t)=>e===A[t]))){this.contentType=t;break}if(!this.contentType)return LI.EMPTY}const e=new Blob([A],{type:this.contentType});let t;switch(this.aspect){case"fit":case"actual":break;case"height":t={height:"100%",objectFit:"fill"};break;case"none":t={width:"100%",height:"100%",objectFit:"fill"};break;case"width":t={width:"100%",objectFit:"fill"}}const i=this[Ho]();return LI.success({name:"img",attributes:{class:["xfaImage"],style:t,src:URL.createObjectURL(e),alt:i?aC(i[Ho]()):null}})}}class BB extends hc{constructor(A){super(Zc,"imageEdit",!0),this.data=NI(A.data,["link","embed"]),this.id=A.id||"",this.use=A.use||"",this.usehref=A.usehref||"",this.border=null,this.extras=null,this.margin=null}[fI](A){return"embed"===this.data?LI.success({name:"div",children:[],attributes:{}}):LI.EMPTY}}class hB extends uc{constructor(A){super(Zc,"integer"),this.id=A.id||"",this.name=A.name||"",this.use=A.use||"",this.usehref=A.usehref||""}[yo](){const A=parseInt(this[uo].trim(),10);this[uo]=isNaN(A)?null:A}[fI](A){return sC(null!==this[uo]?this[uo].toString():"")}}class QB extends hc{constructor(A){super(Zc,"issuers",!0),this.id=A.id||"",this.type=NI(A.type,["optional","required"]),this.use=A.use||"",this.usehref=A.usehref||"",this.certificate=new Qc}}class lB extends hc{constructor(A){super(Zc,"items",!0),this.id=A.id||"",this.name=A.name||"",this.presence=NI(A.presence,["visible","hidden","inactive","invisible"]),this.ref=A.ref||"",this.save=SI({data:A.save,defaultValue:0,validate:A=>1===A}),this.use=A.use||"",this.usehref=A.usehref||"",this.boolean=new Qc,this.date=new Qc,this.dateTime=new Qc,this.decimal=new Qc,this.exData=new Qc,this.float=new Qc,this.image=new Qc,this.integer=new Qc,this.text=new Qc,this.time=new Qc}[fI](){const A=[];for(const e of this[Uo]())A.push(e[uI]());return LI.success(A)}}class EB extends hc{constructor(A){super(Zc,"keep",!0),this.id=A.id||"";const e=["none","contentArea","pageArea"];this.intact=NI(A.intact,e),this.next=NI(A.next,e),this.previous=NI(A.previous,e),this.use=A.use||"",this.usehref=A.usehref||"",this.extras=null}}class uB extends hc{constructor(A){super(Zc,"keyUsage");const e=["","yes","no"];this.crlSign=NI(A.crlSign,e),this.dataEncipherment=NI(A.dataEncipherment,e),this.decipherOnly=NI(A.decipherOnly,e),this.digitalSignature=NI(A.digitalSignature,e),this.encipherOnly=NI(A.encipherOnly,e),this.id=A.id||"",this.keyAgreement=NI(A.keyAgreement,e),this.keyCertSign=NI(A.keyCertSign,e),this.keyEncipherment=NI(A.keyEncipherment,e),this.nonRepudiation=NI(A.nonRepudiation,e),this.type=NI(A.type,["optional","required"]),this.use=A.use||"",this.usehref=A.usehref||""}}class dB extends hc{constructor(A){super(Zc,"line",!0),this.hand=NI(A.hand,["even","left","right"]),this.id=A.id||"",this.slope=NI(A.slope,["\\","/"]),this.use=A.use||"",this.usehref=A.usehref||"",this.edge=null}[fI](){const A=this[Ho]()[Ho](),e=this.edge||new PC({}),t=e[mI](),i=Object.create(null),a="visible"===e.presence?e.thickness:0;let s,n,g,r;i.strokeWidth=wc(a),i.stroke=t.color;let o="100%",I="100%";A.w<=a?([s,n,g,r]=["50%",0,"50%","100%"],o=i.strokeWidth):A.h<=a?([s,n,g,r]=[0,"50%","100%","50%"],I=i.strokeWidth):"\\"===this.slope?[s,n,g,r]=[0,0,"100%","100%"]:[s,n,g,r]=[0,"100%","100%",0];const c={name:"svg",children:[{name:"line",attributes:{xmlns:Oc,x1:s,y1:n,x2:g,y2:r,style:i}}],attributes:{xmlns:Oc,width:o,height:I,style:{overflow:"visible"}}};return _c(A)?LI.success({name:"div",attributes:{style:{display:"inline",width:"100%",height:"100%"}},children:[c]}):(c.attributes.style.position="absolute",LI.success(c))}}class fB extends hc{constructor(A){super(Zc,"linear",!0),this.id=A.id||"",this.type=NI(A.type,["toRight","toBottom","toLeft","toTop"]),this.use=A.use||"",this.usehref=A.usehref||"",this.color=null,this.extras=null}[mI](A){return A=A?A[mI]():"#FFFFFF",`linear-gradient(${this.type.replace(/([RBLT])/," $1").toLowerCase()}, ${A}, ${this.color?this.color[mI]():"#000000"})`}}class pB extends uc{constructor(A){super(Zc,"lockDocument"),this.id=A.id||"",this.type=NI(A.type,["optional","required"]),this.use=A.use||"",this.usehref=A.usehref||""}[yo](){this[uo]=NI(this[uo],["auto","0","1"])}}class mB extends hc{constructor(A){super(Zc,"manifest",!0),this.action=NI(A.action,["include","all","exclude"]),this.id=A.id||"",this.name=A.name||"",this.use=A.use||"",this.usehref=A.usehref||"",this.extras=null,this.ref=new Qc}}class yB extends hc{constructor(A){super(Zc,"margin",!0),this.bottomInset=xI(A.bottomInset,"0"),this.id=A.id||"",this.leftInset=xI(A.leftInset,"0"),this.rightInset=xI(A.rightInset,"0"),this.topInset=xI(A.topInset,"0"),this.use=A.use||"",this.usehref=A.usehref||"",this.extras=null}[mI](){return{margin:wc(this.topInset)+" "+wc(this.rightInset)+" "+wc(this.bottomInset)+" "+wc(this.leftInset)}}}class wB extends hc{constructor(A){super(Zc,"mdp"),this.id=A.id||"",this.permissions=SI({data:A.permissions,defaultValue:2,validate:A=>1===A||3===A}),this.signatureType=NI(A.signatureType,["filler","author"]),this.use=A.use||"",this.usehref=A.usehref||""}}class DB extends hc{constructor(A){super(Zc,"medium"),this.id=A.id||"",this.imagingBBox=function(A){const e=-1;if(!A)return{x:e,y:e,width:e,height:e};const t=A.trim().split(/\s*,\s*/).map((A=>xI(A,"-1")));if(t.length<4||t[2]<0||t[3]<0)return{x:e,y:e,width:e,height:e};const[i,a,s,n]=t;return{x:i,y:a,width:s,height:n}}(A.imagingBBox),this.long=xI(A.long),this.orientation=NI(A.orientation,["portrait","landscape"]),this.short=xI(A.short),this.stock=A.stock||"",this.trayIn=NI(A.trayIn,["auto","delegate","pageFront"]),this.trayOut=NI(A.trayOut,["auto","delegate"]),this.use=A.use||"",this.usehref=A.usehref||""}}class bB extends hc{constructor(A){super(Zc,"message",!0),this.id=A.id||"",this.use=A.use||"",this.usehref=A.usehref||"",this.text=new Qc}}class kB extends hc{constructor(A){super(Zc,"numericEdit",!0),this.hScrollPolicy=NI(A.hScrollPolicy,["auto","off","on"]),this.id=A.id||"",this.use=A.use||"",this.usehref=A.usehref||"",this.border=null,this.comb=null,this.extras=null,this.margin=null}[fI](A){const e=Nc(this,"border","font","margin"),t=this[Ho]()[Ho](),i={name:"input",attributes:{type:"text",fieldId:t[yI],dataId:t[fo]?.[yI]||t[yI],class:["xfaTextfield"],style:e,"aria-label":aC(t),"aria-required":!1}};return eC(t)&&(i.attributes["aria-required"]=!0,i.attributes.required=!0),LI.success({name:"label",attributes:{class:["xfaLabel"]},children:[i]})}}class FB extends hc{constructor(A){super(Zc,"occur",!0),this.id=A.id||"",this.initial=""!==A.initial?SI({data:A.initial,defaultValue:"",validate:A=>!0}):"",this.max=""!==A.max?SI({data:A.max,defaultValue:1,validate:A=>!0}):"",this.min=""!==A.min?SI({data:A.min,defaultValue:1,validate:A=>!0}):"",this.use=A.use||"",this.usehref=A.usehref||"",this.extras=null}[Bo](){const A=this[Ho](),e=this.min;""===this.min&&(this.min=A instanceof NB||A instanceof xB?0:1),""===this.max&&(this.max=""===e?A instanceof NB||A instanceof xB?-1:1:this.min),-1!==this.max&&this.max!0}),this.name=A.name||"",this.numbered=SI({data:A.numbered,defaultValue:1,validate:A=>!0}),this.oddOrEven=NI(A.oddOrEven,["any","even","odd"]),this.pagePosition=NI(A.pagePosition,["any","first","last","only","rest"]),this.relevant=MI(A.relevant),this.use=A.use||"",this.usehref=A.usehref||"",this.desc=null,this.extras=null,this.medium=null,this.occur=null,this.area=new Qc,this.contentArea=new Qc,this.draw=new Qc,this.exclGroup=new Qc,this.field=new Qc,this.subform=new Qc}[$o](){return this[mo]?!this.occur||-1===this.occur.max||this[mo].numberOfUseA.oddOrEven===e&&A.pagePosition===t));return i||(i=this.pageArea.children.find((A=>"any"===A.oddOrEven&&A.pagePosition===t)),i||(i=this.pageArea.children.find((A=>"any"===A.oddOrEven&&"any"===A.pagePosition)),i||this.pageArea.children[0]))}}class UB extends hc{constructor(A){super(Zc,"para",!0),this.hAlign=NI(A.hAlign,["left","center","justify","justifyAll","radix","right"]),this.id=A.id||"",this.lineHeight=A.lineHeight?xI(A.lineHeight,"0pt"):"",this.marginLeft=A.marginLeft?xI(A.marginLeft,"0pt"):"",this.marginRight=A.marginRight?xI(A.marginRight,"0pt"):"",this.orphans=SI({data:A.orphans,defaultValue:0,validate:A=>A>=0}),this.preserve=A.preserve||"",this.radixOffset=A.radixOffset?xI(A.radixOffset,"0pt"):"",this.spaceAbove=A.spaceAbove?xI(A.spaceAbove,"0pt"):"",this.spaceBelow=A.spaceBelow?xI(A.spaceBelow,"0pt"):"",this.tabDefault=A.tabDefault?xI(this.tabDefault):"",this.tabStops=(A.tabStops||"").trim().split(/\s+/).map(((A,e)=>e%2==1?xI(A):A)),this.textIndent=A.textIndent?xI(A.textIndent,"0pt"):"",this.use=A.use||"",this.usehref=A.usehref||"",this.vAlign=NI(A.vAlign,["top","bottom","middle"]),this.widows=SI({data:A.widows,defaultValue:0,validate:A=>A>=0}),this.hyphenation=null}[mI](){const A=Nc(this,"hAlign");return""!==this.marginLeft&&(A.paddingLeft=wc(this.marginLeft)),""!==this.marginRight&&(A.paddingight=wc(this.marginRight)),""!==this.spaceAbove&&(A.paddingTop=wc(this.spaceAbove)),""!==this.spaceBelow&&(A.paddingBottom=wc(this.spaceBelow)),""!==this.textIndent&&(A.textIndent=wc(this.textIndent),Uc(A)),this.lineHeight>0&&(A.lineHeight=wc(this.lineHeight)),""!==this.tabDefault&&(A.tabSize=wc(this.tabDefault)),this.tabStops.length,this.hyphenatation&&Object.assign(A,this.hyphenatation[mI]()),A}}class MB extends hc{constructor(A){super(Zc,"passwordEdit",!0),this.hScrollPolicy=NI(A.hScrollPolicy,["auto","off","on"]),this.id=A.id||"",this.passwordChar=A.passwordChar||"*",this.use=A.use||"",this.usehref=A.usehref||"",this.border=null,this.extras=null,this.margin=null}}class LB extends hc{constructor(A){super(Zc,"pattern",!0),this.id=A.id||"",this.type=NI(A.type,["crossHatch","crossDiagonal","diagonalLeft","diagonalRight","horizontal","vertical"]),this.use=A.use||"",this.usehref=A.usehref||"",this.color=null,this.extras=null}[mI](A){A=A?A[mI]():"#FFFFFF";const e=this.color?this.color[mI]():"#000000",t="repeating-linear-gradient",i=`${A},${A} 5px,${e} 5px,${e} 10px`;switch(this.type){case"crossHatch":return`${t}(to top,${i}) ${t}(to right,${i})`;case"crossDiagonal":return`${t}(45deg,${i}) ${t}(-45deg,${i})`;case"diagonalLeft":return`${t}(45deg,${i})`;case"diagonalRight":return`${t}(-45deg,${i})`;case"horizontal":return`${t}(to top,${i})`;case"vertical":return`${t}(to right,${i})`}return""}}class JB extends fc{constructor(A){super(Zc,"picture"),this.id=A.id||"",this.use=A.use||"",this.usehref=A.usehref||""}}class HB extends hc{constructor(A){super(Zc,"proto",!0),this.appearanceFilter=new Qc,this.arc=new Qc,this.area=new Qc,this.assist=new Qc,this.barcode=new Qc,this.bindItems=new Qc,this.bookend=new Qc,this.boolean=new Qc,this.border=new Qc,this.break=new Qc,this.breakAfter=new Qc,this.breakBefore=new Qc,this.button=new Qc,this.calculate=new Qc,this.caption=new Qc,this.certificate=new Qc,this.certificates=new Qc,this.checkButton=new Qc,this.choiceList=new Qc,this.color=new Qc,this.comb=new Qc,this.connect=new Qc,this.contentArea=new Qc,this.corner=new Qc,this.date=new Qc,this.dateTime=new Qc,this.dateTimeEdit=new Qc,this.decimal=new Qc,this.defaultUi=new Qc,this.desc=new Qc,this.digestMethod=new Qc,this.digestMethods=new Qc,this.draw=new Qc,this.edge=new Qc,this.encoding=new Qc,this.encodings=new Qc,this.encrypt=new Qc,this.encryptData=new Qc,this.encryption=new Qc,this.encryptionMethod=new Qc,this.encryptionMethods=new Qc,this.event=new Qc,this.exData=new Qc,this.exObject=new Qc,this.exclGroup=new Qc,this.execute=new Qc,this.extras=new Qc,this.field=new Qc,this.fill=new Qc,this.filter=new Qc,this.float=new Qc,this.font=new Qc,this.format=new Qc,this.handler=new Qc,this.hyphenation=new Qc,this.image=new Qc,this.imageEdit=new Qc,this.integer=new Qc,this.issuers=new Qc,this.items=new Qc,this.keep=new Qc,this.keyUsage=new Qc,this.line=new Qc,this.linear=new Qc,this.lockDocument=new Qc,this.manifest=new Qc,this.margin=new Qc,this.mdp=new Qc,this.medium=new Qc,this.message=new Qc,this.numericEdit=new Qc,this.occur=new Qc,this.oid=new Qc,this.oids=new Qc,this.overflow=new Qc,this.pageArea=new Qc,this.pageSet=new Qc,this.para=new Qc,this.passwordEdit=new Qc,this.pattern=new Qc,this.picture=new Qc,this.radial=new Qc,this.reason=new Qc,this.reasons=new Qc,this.rectangle=new Qc,this.ref=new Qc,this.script=new Qc,this.setProperty=new Qc,this.signData=new Qc,this.signature=new Qc,this.signing=new Qc,this.solid=new Qc,this.speak=new Qc,this.stipple=new Qc,this.subform=new Qc,this.subformSet=new Qc,this.subjectDN=new Qc,this.subjectDNs=new Qc,this.submit=new Qc,this.text=new Qc,this.textEdit=new Qc,this.time=new Qc,this.timeStamp=new Qc,this.toolTip=new Qc,this.traversal=new Qc,this.traverse=new Qc,this.ui=new Qc,this.validate=new Qc,this.value=new Qc,this.variables=new Qc}}class YB extends hc{constructor(A){super(Zc,"radial",!0),this.id=A.id||"",this.type=NI(A.type,["toEdge","toCenter"]),this.use=A.use||"",this.usehref=A.usehref||"",this.color=null,this.extras=null}[mI](A){A=A?A[mI]():"#FFFFFF";const e=this.color?this.color[mI]():"#000000";return`radial-gradient(circle at center, ${"toEdge"===this.type?`${A},${e}`:`${e},${A}`})`}}class vB extends fc{constructor(A){super(Zc,"reason"),this.id=A.id||"",this.name=A.name||"",this.use=A.use||"",this.usehref=A.usehref||""}}class KB extends hc{constructor(A){super(Zc,"reasons",!0),this.id=A.id||"",this.type=NI(A.type,["optional","required"]),this.use=A.use||"",this.usehref=A.usehref||"",this.reason=new Qc}}class qB extends hc{constructor(A){super(Zc,"rectangle",!0),this.hand=NI(A.hand,["even","left","right"]),this.id=A.id||"",this.use=A.use||"",this.usehref=A.usehref||"",this.corner=new Qc(4),this.edge=new Qc(4),this.fill=null}[fI](){const A=this.edge.children.length?this.edge.children[0]:new PC({}),e=A[mI](),t=Object.create(null);"visible"===this.fill?.presence?Object.assign(t,this.fill[mI]()):t.fill="transparent",t.strokeWidth=wc("visible"===A.presence?A.thickness:0),t.stroke=e.color;const i=(this.corner.children.length?this.corner.children[0]:new UC({}))[mI](),a={name:"svg",children:[{name:"rect",attributes:{xmlns:Oc,width:"100%",height:"100%",x:0,y:0,rx:i.radius,ry:i.radius,style:t}}],attributes:{xmlns:Oc,style:{overflow:"visible"},width:"100%",height:"100%"}};return _c(this[Ho]()[Ho]())?LI.success({name:"div",attributes:{style:{display:"inline",width:"100%",height:"100%"}},children:[a]}):(a.attributes.style.position="absolute",LI.success(a))}}class TB extends fc{constructor(A){super(Zc,"ref"),this.id=A.id||"",this.use=A.use||"",this.usehref=A.usehref||""}}class PB extends fc{constructor(A){super(Zc,"script"),this.binding=A.binding||"",this.contentType=A.contentType||"",this.id=A.id||"",this.name=A.name||"",this.runAt=NI(A.runAt,["client","both","server"]),this.use=A.use||"",this.usehref=A.usehref||""}}class WB extends hc{constructor(A){super(Zc,"setProperty"),this.connection=A.connection||"",this.ref=A.ref||"",this.target=A.target||""}}class ZB extends hc{constructor(A){super(Zc,"signData",!0),this.id=A.id||"",this.operation=NI(A.operation,["sign","clear","verify"]),this.ref=A.ref||"",this.target=A.target||"",this.use=A.use||"",this.usehref=A.usehref||"",this.filter=null,this.manifest=null}}class OB extends hc{constructor(A){super(Zc,"signature",!0),this.id=A.id||"",this.type=NI(A.type,["PDF1.3","PDF1.6"]),this.use=A.use||"",this.usehref=A.usehref||"",this.border=null,this.extras=null,this.filter=null,this.manifest=null,this.margin=null}}class XB extends hc{constructor(A){super(Zc,"signing",!0),this.id=A.id||"",this.type=NI(A.type,["optional","required"]),this.use=A.use||"",this.usehref=A.usehref||"",this.certificate=new Qc}}class VB extends hc{constructor(A){super(Zc,"solid",!0),this.id=A.id||"",this.use=A.use||"",this.usehref=A.usehref||"",this.extras=null}[mI](A){return A?A[mI]():"#FFFFFF"}}class jB extends fc{constructor(A){super(Zc,"speak"),this.disable=SI({data:A.disable,defaultValue:0,validate:A=>1===A}),this.id=A.id||"",this.priority=NI(A.priority,["custom","caption","name","toolTip"]),this.rid=A.rid||"",this.use=A.use||"",this.usehref=A.usehref||""}}class zB extends hc{constructor(A){super(Zc,"stipple",!0),this.id=A.id||"",this.rate=SI({data:A.rate,defaultValue:50,validate:A=>A>=0&&A<=100}),this.use=A.use||"",this.usehref=A.usehref||"",this.color=null,this.extras=null}[mI](A){const e=this.rate/100;return V.makeHexColor(Math.round(A.value.r*(1-e)+this.value.r*e),Math.round(A.value.g*(1-e)+this.value.g*e),Math.round(A.value.b*(1-e)+this.value.b*e))}}class _B extends hc{constructor(A){super(Zc,"subform",!0),this.access=NI(A.access,["open","nonInteractive","protected","readOnly"]),this.allowMacro=SI({data:A.allowMacro,defaultValue:0,validate:A=>1===A}),this.anchorType=NI(A.anchorType,["topLeft","bottomCenter","bottomLeft","bottomRight","middleCenter","middleLeft","middleRight","topCenter","topRight"]),this.colSpan=SI({data:A.colSpan,defaultValue:1,validate:A=>A>=1||-1===A}),this.columnWidths=(A.columnWidths||"").trim().split(/\s+/).map((A=>"-1"===A?-1:xI(A))),this.h=A.h?xI(A.h):"",this.hAlign=NI(A.hAlign,["left","center","justify","justifyAll","radix","right"]),this.id=A.id||"",this.layout=NI(A.layout,["position","lr-tb","rl-row","rl-tb","row","table","tb"]),this.locale=A.locale||"",this.maxH=xI(A.maxH,"0pt"),this.maxW=xI(A.maxW,"0pt"),this.mergeMode=NI(A.mergeMode,["consumeData","matchTemplate"]),this.minH=xI(A.minH,"0pt"),this.minW=xI(A.minW,"0pt"),this.name=A.name||"",this.presence=NI(A.presence,["visible","hidden","inactive","invisible"]),this.relevant=MI(A.relevant),this.restoreState=NI(A.restoreState,["manual","auto"]),this.scope=NI(A.scope,["name","none"]),this.use=A.use||"",this.usehref=A.usehref||"",this.w=A.w?xI(A.w):"",this.x=xI(A.x,"0pt"),this.y=xI(A.y,"0pt"),this.assist=null,this.bind=null,this.bookend=null,this.border=null,this.break=null,this.calculate=null,this.desc=null,this.extras=null,this.keep=null,this.margin=null,this.occur=null,this.overflow=null,this.pageSet=null,this.para=null,this.traversal=null,this.validate=null,this.variables=null,this.area=new Qc,this.breakAfter=new Qc,this.breakBefore=new Qc,this.connect=new Qc,this.draw=new Qc,this.event=new Qc,this.exObject=new Qc,this.exclGroup=new Qc,this.field=new Qc,this.proto=new Qc,this.setProperty=new Qc,this.subform=new Qc,this.subformSet=new Qc}[Jo](){const A=this[Ho]();return A instanceof $B?A[Jo]():A}[Zo](){return!0}[zo](){return this.layout.endsWith("-tb")&&0===this[mo].attempt&&this[mo].numberInLine>0||this[Ho]()[zo]()}*[Mo](){yield*AC(this)}[wo](){return qc(this)}[Io](A,e){Tc(this,A,e)}[ko](){return Pc(this)}[jo](){const A=this[Jo]();return!!A[jo]()&&(void 0!==this[mo]._isSplittable?this[mo]._isSplittable:"position"===this.layout||this.layout.includes("row")||this.keep&&"none"!==this.keep.intact?(this[mo]._isSplittable=!1,!1):!(A.layout?.endsWith("-tb")&&0!==A[mo].numberInLine||(this[mo]._isSplittable=!0,0)))}[fI](A){if(tC(this),this.break){if("auto"!==this.break.after||""!==this.break.afterTarget){const A=new pC({targetType:this.break.after,target:this.break.afterTarget,startNew:this.break.startNew.toString()});A[vo]=this[vo],this[co](A),this.breakAfter.push(A)}if("auto"!==this.break.before||""!==this.break.beforeTarget){const A=new mC({targetType:this.break.before,target:this.break.beforeTarget,startNew:this.break.startNew.toString()});A[vo]=this[vo],this[co](A),this.breakBefore.push(A)}if(""!==this.break.overflowTarget){const A=new GB({target:this.break.overflowTarget,leader:this.break.overflowLeader,trailer:this.break.overflowTrailer});A[vo]=this[vo],this[co](A),this.overflow.push(A)}this[II](this.break),this.break=null}if("hidden"===this.presence||"inactive"===this.presence)return LI.EMPTY;if((this.breakBefore.children.length>1||this.breakAfter.children.length>1)&&R("XFA - Several breakBefore or breakAfter in subforms: please file a bug."),this.breakBefore.children.length>=1){const A=this.breakBefore.children[0];if(rC(A))return LI.breakNode(A)}if(this[mo]?.afterBreakAfter)return LI.EMPTY;Rc(this);const e=[],t={id:this[yI],class:[]};Mc(this,t.class),this[mo]||(this[mo]=Object.create(null)),Object.assign(this[mo],{children:e,line:null,attributes:t,attempt:0,numberInLine:0,availableSpace:{width:Math.min(this.w||1/0,A.width),height:Math.min(this.h||1/0,A.height)},width:0,height:0,prevHeight:0,currentWidth:0});const i=this[Yo](),a=i[mo].noLayoutFailure,s=this[jo]();if(s||nC(this),!Wc(this,A))return LI.FAILURE;const n=new Set(["area","draw","exclGroup","field","subform","subformSet"]);if(this.layout.includes("row")){const A=this[Jo]().columnWidths;Array.isArray(A)&&A.length>0&&(this[mo].columnWidths=A,this[mo].currentColumn=0)}const g=Nc(this,"anchorType","dimensions","position","presence","border","margin","hAlign"),r=["xfaSubform"],o=Gc(this);if(o&&r.push(o),t.style=g,t.class=r,this.name&&(t.xfaName=this.name),this.overflow){const e=this.overflow[No]();e.addLeader&&(e.addLeader=!1,oC(this,e.leader,A))}this[oI]();const I="lr-tb"===this.layout||"rl-tb"===this.layout,c=I?2:1;for(;this[mo].attempt=1){const A=this.breakAfter.children[0];if(rC(A))return this[mo].afterBreakAfter=u,LI.breakNode(A)}return delete this[mo],u}}class $B extends hc{constructor(A){super(Zc,"subformSet",!0),this.id=A.id||"",this.name=A.name||"",this.relation=NI(A.relation,["ordered","choice","unordered"]),this.relevant=MI(A.relevant),this.use=A.use||"",this.usehref=A.usehref||"",this.bookend=null,this.break=null,this.desc=null,this.extras=null,this.occur=null,this.overflow=null,this.breakAfter=new Qc,this.breakBefore=new Qc,this.subform=new Qc,this.subformSet=new Qc}*[Mo](){yield*AC(this)}[Jo](){let A=this[Ho]();for(;!(A instanceof _B);)A=A[Ho]();return A}[Zo](){return!0}}class Ah extends uc{constructor(A){super(Zc,"subjectDN"),this.delimiter=A.delimiter||",",this.id=A.id||"",this.name=A.name||"",this.use=A.use||"",this.usehref=A.usehref||""}[yo](){this[uo]=new Map(this[uo].split(this.delimiter).map((A=>((A=A.split("=",2))[0]=A[0].trim(),A))))}}class eh extends hc{constructor(A){super(Zc,"subjectDNs",!0),this.id=A.id||"",this.type=NI(A.type,["optional","required"]),this.use=A.use||"",this.usehref=A.usehref||"",this.subjectDN=new Qc}}class th extends hc{constructor(A){super(Zc,"submit",!0),this.embedPDF=SI({data:A.embedPDF,defaultValue:0,validate:A=>1===A}),this.format=NI(A.format,["xdp","formdata","pdf","urlencoded","xfd","xml"]),this.id=A.id||"",this.target=A.target||"",this.textEncoding=GI({data:A.textEncoding?A.textEncoding.toLowerCase():"",defaultValue:"",validate:A=>["utf-8","big-five","fontspecific","gbk","gb-18030","gb-2312","ksc-5601","none","shift-jis","ucs-2","utf-16"].includes(A)||A.match(/iso-8859-\d{2}/)}),this.use=A.use||"",this.usehref=A.usehref||"",this.xdpContent=A.xdpContent||"",this.encrypt=null,this.encryptData=new Qc,this.signData=new Qc}}class ih extends hc{constructor(A){super(Zc,"template",!0),this.baseProfile=NI(A.baseProfile,["full","interactiveForms"]),this.extras=null,this.subform=new Qc}[yo](){0===this.subform.children.length&&R("XFA - No subforms in template node."),this.subform.children.length>=2&&R("XFA - Several subforms in template node: please file a bug."),this[EI]=5e3}[jo](){return!0}[BI](A,e){return A.startsWith("#")?[this[qo].get(A.slice(1))]:OI(this,e,A,!0,!0)}*[dI](){if(!this.subform.children.length)return LI.success({name:"div",children:[]});this[mo]={overflowNode:null,firstUnsplittable:null,currentContentArea:null,currentPageArea:null,noLayoutFailure:!1,pageNumber:1,pagePosition:"first",oddOrEven:"odd",blankOrNotBlank:"nonBlank",paraStack:[]};const A=this.subform.children[0];A.pageSet[ho]();const e=A.pageSet.pageArea.children,t={name:"div",children:[]};let i=null,a=null,s=null;if(A.breakBefore.children.length>=1?(a=A.breakBefore.children[0],s=a.target):A.subform.children.length>=1&&A.subform.children[0].breakBefore.children.length>=1?(a=A.subform.children[0].breakBefore.children[0],s=a.target):A.break?.beforeTarget?(a=A.break,s=a.beforeTarget):A.subform.children.length>=1&&A.subform.children[0].break?.beforeTarget&&(a=A.subform.children[0].break,s=a.beforeTarget),a){const A=this[BI](s,a[Ho]());A instanceof NB&&(i=A,a[mo]={})}i||(i=e[0]),i[mo]={numberOfUse:1};const n=i[Ho]();let g;n[mo]={numberOfUse:1,pageIndex:n.pageArea.children.indexOf(i),pageSetIndex:0};let r=null,o=null,I=!0,c=0,C=0;for(;;){if(I)c=0;else if(t.children.pop(),3==++c)return R("XFA - Something goes wrong: please file a bug."),t;g=null,this[mo].currentPageArea=i;const e=i[fI]().html;t.children.push(e),r&&(this[mo].noLayoutFailure=!0,e.children.push(r[fI](i[mo].space).html),r=null),o&&(this[mo].noLayoutFailure=!0,e.children.push(o[fI](i[mo].space).html),o=null);const a=i.contentArea.children,s=e.children.filter((A=>A.attributes.class.includes("xfaContentarea")));I=!1,this[mo].firstUnsplittable=null,this[mo].noLayoutFailure=!1;const n=e=>{const t=A[wo]();t&&(I||=t.children?.length>0,s[e].children.push(t))};for(let e=C,i=a.length;e0,s[e].children.push(B.html)):!I&&t.children.length>1&&t.children.pop(),t;if(B.isBreak()){const A=B.breakNode;if(n(e),"auto"===A.targetType)continue;A.leader&&(r=this[BI](A.leader,A[Ho]()),r=r?r[0]:null),A.trailer&&(o=this[BI](A.trailer,A[Ho]()),o=o?o[0]:null),"pageArea"===A.targetType?(g=A[mo].target,e=1/0):A[mo].target?(g=A[mo].target,C=A[mo].index+1,e=1/0):e=A[mo].index}else if(this[mo].overflowNode){const A=this[mo].overflowNode;this[mo].overflowNode=null;const t=A[No](),i=t.target;t.addLeader=null!==t.leader,t.addTrailer=null!==t.trailer,n(e);const s=e;if(e=1/0,i instanceof NB)g=i;else if(i instanceof xC){const A=a.indexOf(i);-1!==A?A>s?e=A-1:C=A:(g=i[Ho](),C=g.contentArea.children.indexOf(i))}}else n(e)}this[mo].pageNumber+=1,g&&(g[$o]()?g[mo].numberOfUse+=1:g=null),i=g||i[Lo](),yield null}}}class ah extends uc{constructor(A){super(Zc,"text"),this.id=A.id||"",this.maxChars=SI({data:A.maxChars,defaultValue:0,validate:A=>A>=0}),this.name=A.name||"",this.rid=A.rid||"",this.use=A.use||"",this.usehref=A.usehref||""}[oo](){return!0}[aI](A){return A[eI]===DI.xhtml.id?(this[uo]=A,!0):(R(`XFA - Invalid content in Text: ${A[tI]}.`),!1)}[nI](A){this[uo]instanceof hc||super[nI](A)}[yo](){"string"==typeof this[uo]&&(this[uo]=this[uo].replaceAll("\r\n","\n"))}[No](){return"string"==typeof this[uo]?this[uo].split(/[\u2029\u2028\n]/).reduce(((A,e)=>(e&&A.push(e),A)),[]).join("\n"):this[uo][uI]()}[fI](A){if("string"==typeof this[uo]){const A=sC(this[uo]).html;return this[uo].includes("\u2029")?(A.name="div",A.children=[],this[uo].split("\u2029").map((A=>A.split(/[\u2028\n]/).reduce(((A,e)=>(A.push({name:"span",value:e},{name:"br"}),A)),[]))).forEach((e=>{A.children.push({name:"p",children:e})}))):/[\u2028\n]/.test(this[uo])&&(A.name="div",A.children=[],this[uo].split(/[\u2028\n]/).forEach((e=>{A.children.push({name:"span",value:e},{name:"br"})}))),LI.success(A)}return this[uo][fI](A)}}class sh extends hc{constructor(A){super(Zc,"textEdit",!0),this.allowRichText=SI({data:A.allowRichText,defaultValue:0,validate:A=>1===A}),this.hScrollPolicy=NI(A.hScrollPolicy,["auto","off","on"]),this.id=A.id||"",this.multiLine=SI({data:A.multiLine,defaultValue:"",validate:A=>0===A||1===A}),this.use=A.use||"",this.usehref=A.usehref||"",this.vScrollPolicy=NI(A.vScrollPolicy,["auto","off","on"]),this.border=null,this.comb=null,this.extras=null,this.margin=null}[fI](A){const e=Nc(this,"border","font","margin");let t;const i=this[Ho]()[Ho]();return""===this.multiLine&&(this.multiLine=i instanceof TC?1:0),t=1===this.multiLine?{name:"textarea",attributes:{dataId:i[fo]?.[yI]||i[yI],fieldId:i[yI],class:["xfaTextfield"],style:e,"aria-label":aC(i),"aria-required":!1}}:{name:"input",attributes:{type:"text",dataId:i[fo]?.[yI]||i[yI],fieldId:i[yI],class:["xfaTextfield"],style:e,"aria-label":aC(i),"aria-required":!1}},eC(i)&&(t.attributes["aria-required"]=!0,t.attributes.required=!0),LI.success({name:"label",attributes:{class:["xfaLabel"]},children:[t]})}}class nh extends fc{constructor(A){super(Zc,"time"),this.id=A.id||"",this.name=A.name||"",this.use=A.use||"",this.usehref=A.usehref||""}[yo](){const A=this[uo].trim();this[uo]=A?new Date(A):null}[fI](A){return sC(this[uo]?this[uo].toString():"")}}class gh extends hc{constructor(A){super(Zc,"timeStamp"),this.id=A.id||"",this.server=A.server||"",this.type=NI(A.type,["optional","required"]),this.use=A.use||"",this.usehref=A.usehref||""}}class rh extends fc{constructor(A){super(Zc,"toolTip"),this.id=A.id||"",this.rid=A.rid||"",this.use=A.use||"",this.usehref=A.usehref||""}}class oh extends hc{constructor(A){super(Zc,"traversal",!0),this.id=A.id||"",this.use=A.use||"",this.usehref=A.usehref||"",this.extras=null,this.traverse=new Qc}}class Ih extends hc{constructor(A){super(Zc,"traverse",!0),this.id=A.id||"",this.operation=NI(A.operation,["next","back","down","first","left","right","up"]),this.ref=A.ref||"",this.use=A.use||"",this.usehref=A.usehref||"",this.extras=null,this.script=null}get name(){return this.operation}[_o](){return!1}}class ch extends hc{constructor(A){super(Zc,"ui",!0),this.id=A.id||"",this.use=A.use||"",this.usehref=A.usehref||"",this.extras=null,this.picture=null,this.barcode=null,this.button=null,this.checkButton=null,this.choiceList=null,this.dateTimeEdit=null,this.defaultUi=null,this.imageEdit=null,this.numericEdit=null,this.passwordEdit=null,this.signature=null,this.textEdit=null}[No](){if(void 0===this[mo]){for(const A of Object.getOwnPropertyNames(this)){if("extras"===A||"picture"===A)continue;const e=this[A];if(e instanceof hc)return this[mo]=e,e}this[mo]=null}return this[mo]}[fI](A){const e=this[No]();return e?e[fI](A):LI.EMPTY}}class Ch extends hc{constructor(A){super(Zc,"validate",!0),this.formatTest=NI(A.formatTest,["warning","disabled","error"]),this.id=A.id||"",this.nullTest=NI(A.nullTest,["disabled","error","warning"]),this.scriptTest=NI(A.scriptTest,["error","disabled","warning"]),this.use=A.use||"",this.usehref=A.usehref||"",this.extras=null,this.message=null,this.picture=null,this.script=null}}class Bh extends hc{constructor(A){super(Zc,"value",!0),this.id=A.id||"",this.override=SI({data:A.override,defaultValue:0,validate:A=>1===A}),this.relevant=MI(A.relevant),this.use=A.use||"",this.usehref=A.usehref||"",this.arc=null,this.boolean=null,this.date=null,this.dateTime=null,this.decimal=null,this.exData=null,this.float=null,this.image=null,this.integer=null,this.line=null,this.rectangle=null,this.text=null,this.time=null}[lI](A){const e=this[Ho]();if(e instanceof aB&&e.ui?.imageEdit)return this.image||(this.image=new CB({}),this[co](this.image)),void(this.image[uo]=A[uo]);const t=A[tI];if(null===this[t]){for(const A of Object.getOwnPropertyNames(this)){const e=this[A];e instanceof hc&&(this[A]=null,this[II](e))}this[A[tI]]=A,this[co](A)}else this[t][uo]=A[uo]}[uI](){if(this.exData)return"string"==typeof this.exData[uo]?this.exData[uo].trim():this.exData[uo][uI]().trim();for(const A of Object.getOwnPropertyNames(this)){if("image"===A)continue;const e=this[A];if(e instanceof hc)return(e[uo]||"").toString().trim()}return null}[fI](A){for(const e of Object.getOwnPropertyNames(this)){const t=this[e];if(t instanceof hc)return t[fI](A)}return LI.EMPTY}}class hh extends hc{constructor(A){super(Zc,"variables",!0),this.id=A.id||"",this.use=A.use||"",this.usehref=A.usehref||"",this.boolean=new Qc,this.date=new Qc,this.dateTime=new Qc,this.decimal=new Qc,this.exData=new Qc,this.float=new Qc,this.image=new Qc,this.integer=new Qc,this.manifest=new Qc,this.script=new Qc,this.text=new Qc,this.time=new Qc}[_o](){return!0}}class Qh{static[wI](A,e){if(Qh.hasOwnProperty(A)){const t=Qh[A](e);return t[QI](e),t}}static appearanceFilter(A){return new IC(A)}static arc(A){return new cC(A)}static area(A){return new CC(A)}static assist(A){return new BC(A)}static barcode(A){return new hC(A)}static bind(A){return new QC(A)}static bindItems(A){return new lC(A)}static bookend(A){return new EC(A)}static boolean(A){return new uC(A)}static border(A){return new dC(A)}static break(A){return new fC(A)}static breakAfter(A){return new pC(A)}static breakBefore(A){return new mC(A)}static button(A){return new yC(A)}static calculate(A){return new wC(A)}static caption(A){return new DC(A)}static certificate(A){return new bC(A)}static certificates(A){return new kC(A)}static checkButton(A){return new FC(A)}static choiceList(A){return new SC(A)}static color(A){return new RC(A)}static comb(A){return new GC(A)}static connect(A){return new NC(A)}static contentArea(A){return new xC(A)}static corner(A){return new UC(A)}static date(A){return new MC(A)}static dateTime(A){return new LC(A)}static dateTimeEdit(A){return new JC(A)}static decimal(A){return new HC(A)}static defaultUi(A){return new YC(A)}static desc(A){return new vC(A)}static digestMethod(A){return new KC(A)}static digestMethods(A){return new qC(A)}static draw(A){return new TC(A)}static edge(A){return new PC(A)}static encoding(A){return new WC(A)}static encodings(A){return new ZC(A)}static encrypt(A){return new OC(A)}static encryptData(A){return new XC(A)}static encryption(A){return new VC(A)}static encryptionMethod(A){return new jC(A)}static encryptionMethods(A){return new zC(A)}static event(A){return new _C(A)}static exData(A){return new $C(A)}static exObject(A){return new AB(A)}static exclGroup(A){return new eB(A)}static execute(A){return new tB(A)}static extras(A){return new iB(A)}static field(A){return new aB(A)}static fill(A){return new sB(A)}static filter(A){return new nB(A)}static float(A){return new gB(A)}static font(A){return new rB(A)}static format(A){return new oB(A)}static handler(A){return new IB(A)}static hyphenation(A){return new cB(A)}static image(A){return new CB(A)}static imageEdit(A){return new BB(A)}static integer(A){return new hB(A)}static issuers(A){return new QB(A)}static items(A){return new lB(A)}static keep(A){return new EB(A)}static keyUsage(A){return new uB(A)}static line(A){return new dB(A)}static linear(A){return new fB(A)}static lockDocument(A){return new pB(A)}static manifest(A){return new mB(A)}static margin(A){return new yB(A)}static mdp(A){return new wB(A)}static medium(A){return new DB(A)}static message(A){return new bB(A)}static numericEdit(A){return new kB(A)}static occur(A){return new FB(A)}static oid(A){return new SB(A)}static oids(A){return new RB(A)}static overflow(A){return new GB(A)}static pageArea(A){return new NB(A)}static pageSet(A){return new xB(A)}static para(A){return new UB(A)}static passwordEdit(A){return new MB(A)}static pattern(A){return new LB(A)}static picture(A){return new JB(A)}static proto(A){return new HB(A)}static radial(A){return new YB(A)}static reason(A){return new vB(A)}static reasons(A){return new KB(A)}static rectangle(A){return new qB(A)}static ref(A){return new TB(A)}static script(A){return new PB(A)}static setProperty(A){return new WB(A)}static signData(A){return new ZB(A)}static signature(A){return new OB(A)}static signing(A){return new XB(A)}static solid(A){return new VB(A)}static speak(A){return new jB(A)}static stipple(A){return new zB(A)}static subform(A){return new _B(A)}static subformSet(A){return new $B(A)}static subjectDN(A){return new Ah(A)}static subjectDNs(A){return new eh(A)}static submit(A){return new th(A)}static template(A){return new ih(A)}static text(A){return new ah(A)}static textEdit(A){return new sh(A)}static time(A){return new nh(A)}static timeStamp(A){return new gh(A)}static toolTip(A){return new rh(A)}static traversal(A){return new oh(A)}static traverse(A){return new Ih(A)}static ui(A){return new ch(A)}static validate(A){return new Ch(A)}static value(A){return new Bh(A)}static variables(A){return new hh(A)}}const lh=DI.datasets.id;function Eh(A){const e=new ah({});return e[uo]=A,e}class uh{constructor(A){this.root=A,this.datasets=A.datasets,this.data=A.datasets?.data||new Ec(DI.datasets.id,"data"),this.emptyMerge=0===this.data[Uo]().length,this.root.form=this.form=A.template[lo]()}_isConsumeData(){return!this.emptyMerge&&this._mergeMode}_isMatchTemplate(){return!this._isConsumeData()}bind(){return this._bindElement(this.form,this.data),this.form}getData(){return this.data}_bindValue(A,e,t){if(A[fo]=e,A[Ko]())if(e[Oo]()){const t=e[Go]();A[lI](Eh(t))}else if(A instanceof aB&&"multiSelect"===A.ui?.choiceList?.open){const t=e[Uo]().map((A=>A[uo].trim())).join("\n");A[lI](Eh(t))}else this._isConsumeData()&&R("XFA - Nodes haven't the same type.");else!e[Oo]()||this._isMatchTemplate()?this._bindElement(A,e):R("XFA - Nodes haven't the same type.")}_findDataByNameToConsume(A,e,t,i){if(!A)return null;let a,s;for(let i=0;i<3;i++){for(a=t[xo](A,!1,!0);s=a.next().value,s;)if(e===s[Oo]())return s;if(t[eI]===DI.datasets.id&&"data"===t[tI])break;t=t[Ho]()}return i?(a=this.data[xo](A,!0,!1),s=a.next().value,s||(a=this.data[Do](A,!0),s=a.next().value,s?.[Oo]()?s:null)):null}_setProperties(A,e){if(A.hasOwnProperty("setProperty"))for(const{ref:t,target:i,connection:a}of A.setProperty.children){if(a)continue;if(!t)continue;const s=OI(this.root,e,t,!1,!1);if(!s){R(`XFA - Invalid reference: ${t}.`);continue}const[n]=s;if(!n[Xo](this.data)){R("XFA - Invalid node: must be a data node.");continue}const g=OI(this.root,A,i,!1,!1);if(!g){R(`XFA - Invalid target: ${i}.`);continue}const[r]=g;if(!r[Xo](A)){R("XFA - Invalid target: must be a property or subproperty.");continue}const o=r[Ho]();if(r instanceof WB||o instanceof WB){R("XFA - Invalid target: cannot be a setProperty or one of its properties.");continue}if(r instanceof lC||o instanceof lC){R("XFA - Invalid target: cannot be a bindItems or one of its properties.");continue}const I=n[uI](),c=r[tI];if(r instanceof lc){const A=Object.create(null);A[c]=I;const e=Reflect.construct(Object.getPrototypeOf(o).constructor,[A]);o[c]=e[c]}else r.hasOwnProperty(uo)?(r[fo]=n,r[uo]=I,r[yo]()):R("XFA - Invalid node to use in setProperty")}}_bindItems(A,e){if(!A.hasOwnProperty("items")||!A.hasOwnProperty("bindItems")||A.bindItems.isEmpty())return;for(const e of A.items.children)A[II](e);A.items.clear();const t=new lB({}),i=new lB({});A[co](t),A.items.push(t),A[co](i),A.items.push(i);for(const{ref:a,labelRef:s,valueRef:n,connection:g}of A.bindItems.children){if(g)continue;if(!a)continue;const A=OI(this.root,e,a,!1,!1);if(A)for(const e of A){if(!e[Xo](this.datasets)){R(`XFA - Invalid ref (${a}): must be a datasets child.`);continue}const A=OI(this.root,e,s,!0,!1);if(!A){R(`XFA - Invalid label: ${s}.`);continue}const[g]=A;if(!g[Xo](this.datasets)){R("XFA - Invalid label: must be a datasets child.");continue}const r=OI(this.root,e,n,!0,!1);if(!r){R(`XFA - Invalid value: ${n}.`);continue}const[o]=r;if(!o[Xo](this.datasets)){R("XFA - Invalid value: must be a datasets child.");continue}const I=Eh(g[uI]()),c=Eh(o[uI]());t[co](I),t.text.push(I),i[co](c),i.text.push(c)}else R(`XFA - Invalid reference: ${a}.`)}}_bindOccurrences(A,e,t){let i;if(e.length>1&&(i=A[lo](),i[II](i.occur),i.occur=null),this._bindValue(A,e[0],t),this._setProperties(A,e[0]),this._bindItems(A,e[0]),1===e.length)return;const a=A[Ho](),s=A[tI],n=a[To](A);for(let A=1,g=e.length;Ae.name===A.name)).length:t[i].children.length;const s=t[To](A)+1,n=e.initial-a;if(n){const e=A[lo]();e[II](e.occur),e.occur=null,t[i].push(e),t[Po](s,e);for(let A=1;A0)this._bindOccurrences(i,[A[0]],null);else if(this.emptyMerge){const A=e[eI]===lh?-1:e[eI],t=i[fo]=new Ec(A,i.name||"root");e[co](t),this._bindElement(i,t)}continue}if(!i[Zo]())continue;let A=!1,a=null,s=null,n=null;if(i.bind){switch(i.bind.match){case"none":this._setAndBind(i,e);continue;case"global":A=!0;break;case"dataRef":if(!i.bind.ref){R(`XFA - ref is empty in node ${i[tI]}.`),this._setAndBind(i,e);continue}s=i.bind.ref}i.bind.picture&&(a=i.bind.picture[uo])}const[g,r]=this._getOccurInfo(i);if(s){if(n=OI(this.root,e,s,!0,!1),null===n){if(n=XI(this.data,e,s),!n)continue;this._isConsumeData()&&(n[Eo]=!0),this._setAndBind(i,n);continue}this._isConsumeData()&&(n=n.filter((A=>!A[Eo]))),n.length>r?n=n.slice(0,r):0===n.length&&(n=null),n&&this._isConsumeData()&&n.forEach((A=>{A[Eo]=!0}))}else{if(!i.name){this._setAndBind(i,e);continue}if(this._isConsumeData()){const t=[];for(;t.length0?t:null}else{if(n=e[xo](i.name,!1,this.emptyMerge).next().value,!n){if(0===g){t.push(i);continue}const A=e[eI]===lh?-1:e[eI];n=i[fo]=new Ec(A,i.name),this.emptyMerge&&(n[Eo]=!0),e[co](n),this._setAndBind(i,n);continue}this.emptyMerge&&(n[Eo]=!0),n=[n]}}n?this._bindOccurrences(i,n,a):g>0?this._setAndBind(i,e):t.push(i)}t.forEach((A=>A[Ho]()[II](A)))}}class dh{constructor(A,e){this.data=e,this.dataset=A.datasets||null}serialize(A){const e=[[-1,this.data[Uo]()]];for(;e.length>0;){const t=e.at(-1),[i,a]=t;if(i+1===a.length){e.pop();continue}const s=a[++t[0]],n=A.get(s[yI]);if(n)s[lI](n);else{const e=s[bo]();for(const t of e.values()){const e=A.get(t[yI]);if(e){t[lI](e);break}}}const g=s[Uo]();g.length>0&&e.push([-1,g])}const t=[''];if(this.dataset)for(const A of this.dataset[Uo]())"data"!==A[tI]&&A[pI](t);return this.data[pI](t),t.push(""),t.join("")}}const fh=DI.config.id;class ph extends hc{constructor(A){super(fh,"acrobat",!0),this.acrobat7=null,this.autoSave=null,this.common=null,this.validate=null,this.validateApprovalSignatures=null,this.submitUrl=new Qc}}class mh extends hc{constructor(A){super(fh,"acrobat7",!0),this.dynamicRender=null}}class yh extends dc{constructor(A){super(fh,"ADBE_JSConsole",["delegate","Enable","Disable"])}}class wh extends dc{constructor(A){super(fh,"ADBE_JSDebugger",["delegate","Enable","Disable"])}}class Dh extends mc{constructor(A){super(fh,"addSilentPrint")}}class bh extends mc{constructor(A){super(fh,"addViewerPreferences")}}class kh extends yc{constructor(A){super(fh,"adjustData")}}class Fh extends pc{constructor(A){super(fh,"adobeExtensionLevel",0,(A=>A>=1&&A<=8))}}class Sh extends hc{constructor(A){super(fh,"agent",!0),this.name=A.name?A.name.trim():"",this.common=new Qc}}class Rh extends uc{constructor(A){super(fh,"alwaysEmbed")}}class Gh extends fc{constructor(A){super(fh,"amd")}}class Nh extends hc{constructor(A){super(fh,"area"),this.level=SI({data:A.level,defaultValue:0,validate:A=>A>=1&&A<=3}),this.name=NI(A.name,["","barcode","coreinit","deviceDriver","font","general","layout","merge","script","signature","sourceSet","templateCache"])}}class xh extends dc{constructor(A){super(fh,"attributes",["preserve","delegate","ignore"])}}class Uh extends dc{constructor(A){super(fh,"autoSave",["disabled","enabled"])}}class Mh extends fc{constructor(A){super(fh,"base")}}class Lh extends hc{constructor(A){super(fh,"batchOutput"),this.format=NI(A.format,["none","concat","zip","zipCompress"])}}class Jh extends uc{constructor(A){super(fh,"behaviorOverride")}[yo](){this[uo]=new Map(this[uo].trim().split(/\s+/).filter((A=>A.includes(":"))).map((A=>A.split(":",2))))}}class Hh extends hc{constructor(A){super(fh,"cache",!0),this.templateCache=null}}class Yh extends mc{constructor(A){super(fh,"change")}}class vh extends hc{constructor(A){super(fh,"common",!0),this.data=null,this.locale=null,this.localeSet=null,this.messaging=null,this.suppressBanner=null,this.template=null,this.validationMessaging=null,this.versionControl=null,this.log=new Qc}}class Kh extends hc{constructor(A){super(fh,"compress"),this.scope=NI(A.scope,["imageOnly","document"])}}class qh extends mc{constructor(A){super(fh,"compressLogicalStructure")}}class Th extends yc{constructor(A){super(fh,"compressObjectStream")}}class Ph extends hc{constructor(A){super(fh,"compression",!0),this.compressLogicalStructure=null,this.compressObjectStream=null,this.level=null,this.type=null}}class Wh extends hc{constructor(A){super(fh,"config",!0),this.acrobat=null,this.present=null,this.trace=null,this.agent=new Qc}}class Zh extends dc{constructor(A){super(fh,"conformance",["A","B"])}}class Oh extends mc{constructor(A){super(fh,"contentCopy")}}class Xh extends pc{constructor(A){super(fh,"copies",1,(A=>A>=1))}}class Vh extends fc{constructor(A){super(fh,"creator")}}class jh extends pc{constructor(A){super(fh,"currentPage",0,(A=>A>=0))}}class zh extends hc{constructor(A){super(fh,"data",!0),this.adjustData=null,this.attributes=null,this.incrementalLoad=null,this.outputXSL=null,this.range=null,this.record=null,this.startNode=null,this.uri=null,this.window=null,this.xsl=null,this.excludeNS=new Qc,this.transform=new Qc}}class _h extends hc{constructor(A){super(fh,"debug",!0),this.uri=null}}class $h extends uc{constructor(A){super(fh,"defaultTypeface"),this.writingScript=NI(A.writingScript,["*","Arabic","Cyrillic","EastEuropeanRoman","Greek","Hebrew","Japanese","Korean","Roman","SimplifiedChinese","Thai","TraditionalChinese","Vietnamese"])}}class AQ extends dc{constructor(A){super(fh,"destination",["pdf","pcl","ps","webClient","zpl"])}}class eQ extends mc{constructor(A){super(fh,"documentAssembly")}}class tQ extends hc{constructor(A){super(fh,"driver",!0),this.name=A.name?A.name.trim():"",this.fontInfo=null,this.xdc=null}}class iQ extends dc{constructor(A){super(fh,"duplexOption",["simplex","duplexFlipLongEdge","duplexFlipShortEdge"])}}class aQ extends dc{constructor(A){super(fh,"dynamicRender",["forbidden","required"])}}class sQ extends mc{constructor(A){super(fh,"embed")}}class nQ extends mc{constructor(A){super(fh,"encrypt")}}class gQ extends hc{constructor(A){super(fh,"encryption",!0),this.encrypt=null,this.encryptionLevel=null,this.permissions=null}}class rQ extends dc{constructor(A){super(fh,"encryptionLevel",["40bit","128bit"])}}class oQ extends fc{constructor(A){super(fh,"enforce")}}class IQ extends hc{constructor(A){super(fh,"equate"),this.force=SI({data:A.force,defaultValue:1,validate:A=>0===A}),this.from=A.from||"",this.to=A.to||""}}class cQ extends hc{constructor(A){super(fh,"equateRange"),this.from=A.from||"",this.to=A.to||"",this._unicodeRange=A.unicodeRange||""}get unicodeRange(){const A=[],e=/U\+([0-9a-fA-F]+)/,t=this._unicodeRange;for(let i of t.split(",").map((A=>A.trim())).filter((A=>!!A)))i=i.split("-",2).map((A=>{const t=A.match(e);return t?parseInt(t[1],16):0})),1===i.length&&i.push(i[0]),A.push(i);return U(this,"unicodeRange",A)}}class CQ extends uc{constructor(A){super(fh,"exclude")}[yo](){this[uo]=this[uo].trim().split(/\s+/).filter((A=>A&&["calculate","close","enter","exit","initialize","ready","validate"].includes(A)))}}class BQ extends fc{constructor(A){super(fh,"excludeNS")}}class hQ extends dc{constructor(A){super(fh,"flipLabel",["usePrinterSetting","on","off"])}}class QQ extends hc{constructor(A){super(fh,"fontInfo",!0),this.embed=null,this.map=null,this.subsetBelow=null,this.alwaysEmbed=new Qc,this.defaultTypeface=new Qc,this.neverEmbed=new Qc}}class lQ extends mc{constructor(A){super(fh,"formFieldFilling")}}class EQ extends fc{constructor(A){super(fh,"groupParent")}}class uQ extends dc{constructor(A){super(fh,"ifEmpty",["dataValue","dataGroup","ignore","remove"])}}class dQ extends fc{constructor(A){super(fh,"includeXDPContent")}}class fQ extends dc{constructor(A){super(fh,"incrementalLoad",["none","forwardOnly"])}}class pQ extends mc{constructor(A){super(fh,"incrementalMerge")}}class mQ extends mc{constructor(A){super(fh,"interactive")}}class yQ extends dc{constructor(A){super(fh,"jog",["usePrinterSetting","none","pageSet"])}}class wQ extends hc{constructor(A){super(fh,"labelPrinter",!0),this.name=NI(A.name,["zpl","dpl","ipl","tcpl"]),this.batchOutput=null,this.flipLabel=null,this.fontInfo=null,this.xdc=null}}class DQ extends dc{constructor(A){super(fh,"layout",["paginate","panel"])}}class bQ extends pc{constructor(A){super(fh,"level",0,(A=>A>0))}}class kQ extends mc{constructor(A){super(fh,"linearized")}}class FQ extends fc{constructor(A){super(fh,"locale")}}class SQ extends fc{constructor(A){super(fh,"localeSet")}}class RQ extends hc{constructor(A){super(fh,"log",!0),this.mode=null,this.threshold=null,this.to=null,this.uri=null}}class GQ extends hc{constructor(A){super(fh,"map",!0),this.equate=new Qc,this.equateRange=new Qc}}class NQ extends hc{constructor(A){super(fh,"mediumInfo",!0),this.map=null}}class xQ extends hc{constructor(A){super(fh,"message",!0),this.msgId=null,this.severity=null}}class UQ extends hc{constructor(A){super(fh,"messaging",!0),this.message=new Qc}}class MQ extends dc{constructor(A){super(fh,"mode",["append","overwrite"])}}class LQ extends mc{constructor(A){super(fh,"modifyAnnots")}}class JQ extends pc{constructor(A){super(fh,"msgId",1,(A=>A>=1))}}class HQ extends fc{constructor(A){super(fh,"nameAttr")}}class YQ extends uc{constructor(A){super(fh,"neverEmbed")}}class vQ extends pc{constructor(A){super(fh,"numberOfCopies",null,(A=>A>=2&&A<=5))}}class KQ extends hc{constructor(A){super(fh,"openAction",!0),this.destination=null}}class qQ extends hc{constructor(A){super(fh,"output",!0),this.to=null,this.type=null,this.uri=null}}class TQ extends fc{constructor(A){super(fh,"outputBin")}}class PQ extends hc{constructor(A){super(fh,"outputXSL",!0),this.uri=null}}class WQ extends dc{constructor(A){super(fh,"overprint",["none","both","draw","field"])}}class ZQ extends fc{constructor(A){super(fh,"packets")}[yo](){"*"!==this[uo]&&(this[uo]=this[uo].trim().split(/\s+/).filter((A=>["config","datasets","template","xfdf","xslt"].includes(A))))}}class OQ extends hc{constructor(A){super(fh,"pageOffset"),this.x=SI({data:A.x,defaultValue:"useXDCSetting",validate:A=>!0}),this.y=SI({data:A.y,defaultValue:"useXDCSetting",validate:A=>!0})}}class XQ extends fc{constructor(A){super(fh,"pageRange")}[yo](){const A=this[uo].trim().split(/\s+/).map((A=>parseInt(A,10))),e=[];for(let t=0,i=A.length;t!1))}}class _Q extends hc{constructor(A){super(fh,"pcl",!0),this.name=A.name||"",this.batchOutput=null,this.fontInfo=null,this.jog=null,this.mediumInfo=null,this.outputBin=null,this.pageOffset=null,this.staple=null,this.xdc=null}}class $Q extends hc{constructor(A){super(fh,"pdf",!0),this.name=A.name||"",this.adobeExtensionLevel=null,this.batchOutput=null,this.compression=null,this.creator=null,this.encryption=null,this.fontInfo=null,this.interactive=null,this.linearized=null,this.openAction=null,this.pdfa=null,this.producer=null,this.renderPolicy=null,this.scriptModel=null,this.silentPrint=null,this.submitFormat=null,this.tagged=null,this.version=null,this.viewerPreferences=null,this.xdc=null}}class Al extends hc{constructor(A){super(fh,"pdfa",!0),this.amd=null,this.conformance=null,this.includeXDPContent=null,this.part=null}}class el extends hc{constructor(A){super(fh,"permissions",!0),this.accessibleContent=null,this.change=null,this.contentCopy=null,this.documentAssembly=null,this.formFieldFilling=null,this.modifyAnnots=null,this.plaintextMetadata=null,this.print=null,this.printHighQuality=null}}class tl extends mc{constructor(A){super(fh,"pickTrayByPDFSize")}}class il extends fc{constructor(A){super(fh,"picture")}}class al extends mc{constructor(A){super(fh,"plaintextMetadata")}}class sl extends dc{constructor(A){super(fh,"presence",["preserve","dissolve","dissolveStructure","ignore","remove"])}}class nl extends hc{constructor(A){super(fh,"present",!0),this.behaviorOverride=null,this.cache=null,this.common=null,this.copies=null,this.destination=null,this.incrementalMerge=null,this.layout=null,this.output=null,this.overprint=null,this.pagination=null,this.paginationOverride=null,this.script=null,this.validate=null,this.xdp=null,this.driver=new Qc,this.labelPrinter=new Qc,this.pcl=new Qc,this.pdf=new Qc,this.ps=new Qc,this.submitUrl=new Qc,this.webClient=new Qc,this.zpl=new Qc}}class gl extends mc{constructor(A){super(fh,"print")}}class rl extends mc{constructor(A){super(fh,"printHighQuality")}}class ol extends dc{constructor(A){super(fh,"printScaling",["appdefault","noScaling"])}}class Il extends fc{constructor(A){super(fh,"printerName")}}class cl extends fc{constructor(A){super(fh,"producer")}}class Cl extends hc{constructor(A){super(fh,"ps",!0),this.name=A.name||"",this.batchOutput=null,this.fontInfo=null,this.jog=null,this.mediumInfo=null,this.outputBin=null,this.staple=null,this.xdc=null}}class Bl extends uc{constructor(A){super(fh,"range")}[yo](){this[uo]=this[uo].trim().split(/\s*,\s*/,2).map((A=>A.split("-").map((A=>parseInt(A.trim(),10))))).filter((A=>A.every((A=>!isNaN(A))))).map((A=>(1===A.length&&A.push(A[0]),A)))}}class hl extends uc{constructor(A){super(fh,"record")}[yo](){this[uo]=this[uo].trim();const A=parseInt(this[uo],10);!isNaN(A)&&A>=0&&(this[uo]=A)}}class Ql extends uc{constructor(A){super(fh,"relevant")}[yo](){this[uo]=this[uo].trim().split(/\s+/)}}class ll extends uc{constructor(A){super(fh,"rename")}[yo](){this[uo]=this[uo].trim(),(this[uo].toLowerCase().startsWith("xml")||new RegExp("[\\p{L}_][\\p{L}\\d._\\p{M}-]*","u").test(this[uo]))&&R("XFA - Rename: invalid XFA name")}}class El extends dc{constructor(A){super(fh,"renderPolicy",["server","client"])}}class ul extends dc{constructor(A){super(fh,"runScripts",["both","client","none","server"])}}class dl extends hc{constructor(A){super(fh,"script",!0),this.currentPage=null,this.exclude=null,this.runScripts=null}}class fl extends dc{constructor(A){super(fh,"scriptModel",["XFA","none"])}}class pl extends dc{constructor(A){super(fh,"severity",["ignore","error","information","trace","warning"])}}class ml extends hc{constructor(A){super(fh,"silentPrint",!0),this.addSilentPrint=null,this.printerName=null}}class yl extends hc{constructor(A){super(fh,"staple"),this.mode=NI(A.mode,["usePrinterSetting","on","off"])}}class wl extends fc{constructor(A){super(fh,"startNode")}}class Dl extends pc{constructor(A){super(fh,"startPage",0,(A=>!0))}}class bl extends dc{constructor(A){super(fh,"submitFormat",["html","delegate","fdf","xml","pdf"])}}class kl extends fc{constructor(A){super(fh,"submitUrl")}}class Fl extends pc{constructor(A){super(fh,"subsetBelow",100,(A=>A>=0&&A<=100))}}class Sl extends mc{constructor(A){super(fh,"suppressBanner")}}class Rl extends mc{constructor(A){super(fh,"tagged")}}class Gl extends hc{constructor(A){super(fh,"template",!0),this.base=null,this.relevant=null,this.startPage=null,this.uri=null,this.xsl=null}}class Nl extends dc{constructor(A){super(fh,"threshold",["trace","error","information","warning"])}}class xl extends dc{constructor(A){super(fh,"to",["null","memory","stderr","stdout","system","uri"])}}class Ul extends hc{constructor(A){super(fh,"templateCache"),this.maxEntries=SI({data:A.maxEntries,defaultValue:5,validate:A=>A>=0})}}class Ml extends hc{constructor(A){super(fh,"trace",!0),this.area=new Qc}}class Ll extends hc{constructor(A){super(fh,"transform",!0),this.groupParent=null,this.ifEmpty=null,this.nameAttr=null,this.picture=null,this.presence=null,this.rename=null,this.whitespace=null}}class Jl extends dc{constructor(A){super(fh,"type",["none","ascii85","asciiHex","ccittfax","flate","lzw","runLength","native","xdp","mergedXDP"])}}class Hl extends fc{constructor(A){super(fh,"uri")}}class Yl extends dc{constructor(A){super(fh,"validate",["preSubmit","prePrint","preExecute","preSave"])}}class vl extends uc{constructor(A){super(fh,"validateApprovalSignatures")}[yo](){this[uo]=this[uo].trim().split(/\s+/).filter((A=>["docReady","postSign"].includes(A)))}}class Kl extends dc{constructor(A){super(fh,"validationMessaging",["allMessagesIndividually","allMessagesTogether","firstMessageOnly","noMessages"])}}class ql extends dc{constructor(A){super(fh,"version",["1.7","1.6","1.5","1.4","1.3","1.2"])}}class Tl extends hc{constructor(A){super(fh,"VersionControl"),this.outputBelow=NI(A.outputBelow,["warn","error","update"]),this.sourceAbove=NI(A.sourceAbove,["warn","error"]),this.sourceBelow=NI(A.sourceBelow,["update","maintain"])}}class Pl extends hc{constructor(A){super(fh,"viewerPreferences",!0),this.ADBE_JSConsole=null,this.ADBE_JSDebugger=null,this.addViewerPreferences=null,this.duplexOption=null,this.enforce=null,this.numberOfCopies=null,this.pageRange=null,this.pickTrayByPDFSize=null,this.printScaling=null}}class Wl extends hc{constructor(A){super(fh,"webClient",!0),this.name=A.name?A.name.trim():"",this.fontInfo=null,this.xdc=null}}class Zl extends dc{constructor(A){super(fh,"whitespace",["preserve","ltrim","normalize","rtrim","trim"])}}class Ol extends uc{constructor(A){super(fh,"window")}[yo](){const A=this[uo].trim().split(/\s*,\s*/,2).map((A=>parseInt(A,10)));A.some((A=>isNaN(A)))?this[uo]=[0,0]:(1===A.length&&A.push(A[0]),this[uo]=A)}}class Xl extends hc{constructor(A){super(fh,"xdc",!0),this.uri=new Qc,this.xsl=new Qc}}class Vl extends hc{constructor(A){super(fh,"xdp",!0),this.packets=null}}class jl extends hc{constructor(A){super(fh,"xsl",!0),this.debug=null,this.uri=null}}class zl extends hc{constructor(A){super(fh,"zpl",!0),this.name=A.name?A.name.trim():"",this.batchOutput=null,this.flipLabel=null,this.fontInfo=null,this.xdc=null}}class _l{static[wI](A,e){if(_l.hasOwnProperty(A))return _l[A](e)}static acrobat(A){return new ph(A)}static acrobat7(A){return new mh(A)}static ADBE_JSConsole(A){return new yh(A)}static ADBE_JSDebugger(A){return new wh(A)}static addSilentPrint(A){return new Dh(A)}static addViewerPreferences(A){return new bh(A)}static adjustData(A){return new kh(A)}static adobeExtensionLevel(A){return new Fh(A)}static agent(A){return new Sh(A)}static alwaysEmbed(A){return new Rh(A)}static amd(A){return new Gh(A)}static area(A){return new Nh(A)}static attributes(A){return new xh(A)}static autoSave(A){return new Uh(A)}static base(A){return new Mh(A)}static batchOutput(A){return new Lh(A)}static behaviorOverride(A){return new Jh(A)}static cache(A){return new Hh(A)}static change(A){return new Yh(A)}static common(A){return new vh(A)}static compress(A){return new Kh(A)}static compressLogicalStructure(A){return new qh(A)}static compressObjectStream(A){return new Th(A)}static compression(A){return new Ph(A)}static config(A){return new Wh(A)}static conformance(A){return new Zh(A)}static contentCopy(A){return new Oh(A)}static copies(A){return new Xh(A)}static creator(A){return new Vh(A)}static currentPage(A){return new jh(A)}static data(A){return new zh(A)}static debug(A){return new _h(A)}static defaultTypeface(A){return new $h(A)}static destination(A){return new AQ(A)}static documentAssembly(A){return new eQ(A)}static driver(A){return new tQ(A)}static duplexOption(A){return new iQ(A)}static dynamicRender(A){return new aQ(A)}static embed(A){return new sQ(A)}static encrypt(A){return new nQ(A)}static encryption(A){return new gQ(A)}static encryptionLevel(A){return new rQ(A)}static enforce(A){return new oQ(A)}static equate(A){return new IQ(A)}static equateRange(A){return new cQ(A)}static exclude(A){return new CQ(A)}static excludeNS(A){return new BQ(A)}static flipLabel(A){return new hQ(A)}static fontInfo(A){return new QQ(A)}static formFieldFilling(A){return new lQ(A)}static groupParent(A){return new EQ(A)}static ifEmpty(A){return new uQ(A)}static includeXDPContent(A){return new dQ(A)}static incrementalLoad(A){return new fQ(A)}static incrementalMerge(A){return new pQ(A)}static interactive(A){return new mQ(A)}static jog(A){return new yQ(A)}static labelPrinter(A){return new wQ(A)}static layout(A){return new DQ(A)}static level(A){return new bQ(A)}static linearized(A){return new kQ(A)}static locale(A){return new FQ(A)}static localeSet(A){return new SQ(A)}static log(A){return new RQ(A)}static map(A){return new GQ(A)}static mediumInfo(A){return new NQ(A)}static message(A){return new xQ(A)}static messaging(A){return new UQ(A)}static mode(A){return new MQ(A)}static modifyAnnots(A){return new LQ(A)}static msgId(A){return new JQ(A)}static nameAttr(A){return new HQ(A)}static neverEmbed(A){return new YQ(A)}static numberOfCopies(A){return new vQ(A)}static openAction(A){return new KQ(A)}static output(A){return new qQ(A)}static outputBin(A){return new TQ(A)}static outputXSL(A){return new PQ(A)}static overprint(A){return new WQ(A)}static packets(A){return new ZQ(A)}static pageOffset(A){return new OQ(A)}static pageRange(A){return new XQ(A)}static pagination(A){return new VQ(A)}static paginationOverride(A){return new jQ(A)}static part(A){return new zQ(A)}static pcl(A){return new _Q(A)}static pdf(A){return new $Q(A)}static pdfa(A){return new Al(A)}static permissions(A){return new el(A)}static pickTrayByPDFSize(A){return new tl(A)}static picture(A){return new il(A)}static plaintextMetadata(A){return new al(A)}static presence(A){return new sl(A)}static present(A){return new nl(A)}static print(A){return new gl(A)}static printHighQuality(A){return new rl(A)}static printScaling(A){return new ol(A)}static printerName(A){return new Il(A)}static producer(A){return new cl(A)}static ps(A){return new Cl(A)}static range(A){return new Bl(A)}static record(A){return new hl(A)}static relevant(A){return new Ql(A)}static rename(A){return new ll(A)}static renderPolicy(A){return new El(A)}static runScripts(A){return new ul(A)}static script(A){return new dl(A)}static scriptModel(A){return new fl(A)}static severity(A){return new pl(A)}static silentPrint(A){return new ml(A)}static staple(A){return new yl(A)}static startNode(A){return new wl(A)}static startPage(A){return new Dl(A)}static submitFormat(A){return new bl(A)}static submitUrl(A){return new kl(A)}static subsetBelow(A){return new Fl(A)}static suppressBanner(A){return new Sl(A)}static tagged(A){return new Rl(A)}static template(A){return new Gl(A)}static templateCache(A){return new Ul(A)}static threshold(A){return new Nl(A)}static to(A){return new xl(A)}static trace(A){return new Ml(A)}static transform(A){return new Ll(A)}static type(A){return new Jl(A)}static uri(A){return new Hl(A)}static validate(A){return new Yl(A)}static validateApprovalSignatures(A){return new vl(A)}static validationMessaging(A){return new Kl(A)}static version(A){return new ql(A)}static versionControl(A){return new Tl(A)}static viewerPreferences(A){return new Pl(A)}static webClient(A){return new Wl(A)}static whitespace(A){return new Zl(A)}static window(A){return new Ol(A)}static xdc(A){return new Xl(A)}static xdp(A){return new Vl(A)}static xsl(A){return new jl(A)}static zpl(A){return new zl(A)}}const $l=DI.connectionSet.id;class AE extends hc{constructor(A){super($l,"connectionSet",!0),this.wsdlConnection=new Qc,this.xmlConnection=new Qc,this.xsdConnection=new Qc}}class eE extends hc{constructor(A){super($l,"effectiveInputPolicy"),this.id=A.id||"",this.name=A.name||"",this.use=A.use||"",this.usehref=A.usehref||""}}class tE extends hc{constructor(A){super($l,"effectiveOutputPolicy"),this.id=A.id||"",this.name=A.name||"",this.use=A.use||"",this.usehref=A.usehref||""}}class iE extends fc{constructor(A){super($l,"operation"),this.id=A.id||"",this.input=A.input||"",this.name=A.name||"",this.output=A.output||"",this.use=A.use||"",this.usehref=A.usehref||""}}class aE extends fc{constructor(A){super($l,"rootElement"),this.id=A.id||"",this.name=A.name||"",this.use=A.use||"",this.usehref=A.usehref||""}}class sE extends fc{constructor(A){super($l,"soapAction"),this.id=A.id||"",this.name=A.name||"",this.use=A.use||"",this.usehref=A.usehref||""}}class nE extends fc{constructor(A){super($l,"soapAddress"),this.id=A.id||"",this.name=A.name||"",this.use=A.use||"",this.usehref=A.usehref||""}}class gE extends fc{constructor(A){super($l,"uri"),this.id=A.id||"",this.name=A.name||"",this.use=A.use||"",this.usehref=A.usehref||""}}class rE extends fc{constructor(A){super($l,"wsdlAddress"),this.id=A.id||"",this.name=A.name||"",this.use=A.use||"",this.usehref=A.usehref||""}}class oE extends hc{constructor(A){super($l,"wsdlConnection",!0),this.dataDescription=A.dataDescription||"",this.name=A.name||"",this.effectiveInputPolicy=null,this.effectiveOutputPolicy=null,this.operation=null,this.soapAction=null,this.soapAddress=null,this.wsdlAddress=null}}class IE extends hc{constructor(A){super($l,"xmlConnection",!0),this.dataDescription=A.dataDescription||"",this.name=A.name||"",this.uri=null}}class cE extends hc{constructor(A){super($l,"xsdConnection",!0),this.dataDescription=A.dataDescription||"",this.name=A.name||"",this.rootElement=null,this.uri=null}}class CE{static[wI](A,e){if(CE.hasOwnProperty(A))return CE[A](e)}static connectionSet(A){return new AE(A)}static effectiveInputPolicy(A){return new eE(A)}static effectiveOutputPolicy(A){return new tE(A)}static operation(A){return new iE(A)}static rootElement(A){return new aE(A)}static soapAction(A){return new sE(A)}static soapAddress(A){return new nE(A)}static uri(A){return new gE(A)}static wsdlAddress(A){return new rE(A)}static wsdlConnection(A){return new oE(A)}static xmlConnection(A){return new IE(A)}static xsdConnection(A){return new cE(A)}}const BE=DI.datasets.id;class hE extends Ec{constructor(A){super(BE,"data",A)}[Vo](){return!0}}class QE extends hc{constructor(A){super(BE,"datasets",!0),this.data=null,this.Signature=null}[aI](A){const e=A[tI];("data"===e&&A[eI]===BE||"Signature"===e&&A[eI]===DI.signature.id)&&(this[e]=A),this[co](A)}}class lE{static[wI](A,e){if(lE.hasOwnProperty(A))return lE[A](e)}static datasets(A){return new QE(A)}static data(A){return new hE(A)}}const EE=DI.localeSet.id;class uE extends hc{constructor(A){super(EE,"calendarSymbols",!0),this.name="gregorian",this.dayNames=new Qc(2),this.eraNames=null,this.meridiemNames=null,this.monthNames=new Qc(2)}}class dE extends fc{constructor(A){super(EE,"currencySymbol"),this.name=NI(A.name,["symbol","isoname","decimal"])}}class fE extends hc{constructor(A){super(EE,"currencySymbols",!0),this.currencySymbol=new Qc(3)}}class pE extends fc{constructor(A){super(EE,"datePattern"),this.name=NI(A.name,["full","long","med","short"])}}class mE extends hc{constructor(A){super(EE,"datePatterns",!0),this.datePattern=new Qc(4)}}class yE extends uc{constructor(A){super(EE,"dateTimeSymbols")}}class wE extends fc{constructor(A){super(EE,"day")}}class DE extends hc{constructor(A){super(EE,"dayNames",!0),this.abbr=SI({data:A.abbr,defaultValue:0,validate:A=>1===A}),this.day=new Qc(7)}}class bE extends fc{constructor(A){super(EE,"era")}}class kE extends hc{constructor(A){super(EE,"eraNames",!0),this.era=new Qc(2)}}class FE extends hc{constructor(A){super(EE,"locale",!0),this.desc=A.desc||"",this.name="isoname",this.calendarSymbols=null,this.currencySymbols=null,this.datePatterns=null,this.dateTimeSymbols=null,this.numberPatterns=null,this.numberSymbols=null,this.timePatterns=null,this.typeFaces=null}}class SE extends hc{constructor(A){super(EE,"localeSet",!0),this.locale=new Qc}}class RE extends fc{constructor(A){super(EE,"meridiem")}}class GE extends hc{constructor(A){super(EE,"meridiemNames",!0),this.meridiem=new Qc(2)}}class NE extends fc{constructor(A){super(EE,"month")}}class xE extends hc{constructor(A){super(EE,"monthNames",!0),this.abbr=SI({data:A.abbr,defaultValue:0,validate:A=>1===A}),this.month=new Qc(12)}}class UE extends fc{constructor(A){super(EE,"numberPattern"),this.name=NI(A.name,["full","long","med","short"])}}class ME extends hc{constructor(A){super(EE,"numberPatterns",!0),this.numberPattern=new Qc(4)}}class LE extends fc{constructor(A){super(EE,"numberSymbol"),this.name=NI(A.name,["decimal","grouping","percent","minus","zero"])}}class JE extends hc{constructor(A){super(EE,"numberSymbols",!0),this.numberSymbol=new Qc(5)}}class HE extends fc{constructor(A){super(EE,"timePattern"),this.name=NI(A.name,["full","long","med","short"])}}class YE extends hc{constructor(A){super(EE,"timePatterns",!0),this.timePattern=new Qc(4)}}class vE extends hc{constructor(A){super(EE,"typeFace",!0),this.name=""|A.name}}class KE extends hc{constructor(A){super(EE,"typeFaces",!0),this.typeFace=new Qc}}class qE{static[wI](A,e){if(qE.hasOwnProperty(A))return qE[A](e)}static calendarSymbols(A){return new uE(A)}static currencySymbol(A){return new dE(A)}static currencySymbols(A){return new fE(A)}static datePattern(A){return new pE(A)}static datePatterns(A){return new mE(A)}static dateTimeSymbols(A){return new yE(A)}static day(A){return new wE(A)}static dayNames(A){return new DE(A)}static era(A){return new bE(A)}static eraNames(A){return new kE(A)}static locale(A){return new FE(A)}static localeSet(A){return new SE(A)}static meridiem(A){return new RE(A)}static meridiemNames(A){return new GE(A)}static month(A){return new NE(A)}static monthNames(A){return new xE(A)}static numberPattern(A){return new UE(A)}static numberPatterns(A){return new ME(A)}static numberSymbol(A){return new LE(A)}static numberSymbols(A){return new JE(A)}static timePattern(A){return new HE(A)}static timePatterns(A){return new YE(A)}static typeFace(A){return new vE(A)}static typeFaces(A){return new KE(A)}}const TE=DI.signature.id;class PE extends hc{constructor(A){super(TE,"signature",!0)}}class WE{static[wI](A,e){if(WE.hasOwnProperty(A))return WE[A](e)}static signature(A){return new PE(A)}}const ZE=DI.stylesheet.id;class OE extends hc{constructor(A){super(ZE,"stylesheet",!0)}}class XE{static[wI](A,e){if(XE.hasOwnProperty(A))return XE[A](e)}static stylesheet(A){return new OE(A)}}const VE=DI.xdp.id;class jE extends hc{constructor(A){super(VE,"xdp",!0),this.uuid=A.uuid||"",this.timeStamp=A.timeStamp||"",this.config=null,this.connectionSet=null,this.datasets=null,this.localeSet=null,this.stylesheet=new Qc,this.template=null}[sI](A){const e=DI[A[tI]];return e&&A[eI]===e.id}}class zE{static[wI](A,e){if(zE.hasOwnProperty(A))return zE[A](e)}static xdp(A){return new jE(A)}}const _E=DI.xhtml.id,$E=Symbol(),Au=new Set(["color","font","font-family","font-size","font-stretch","font-style","font-weight","margin","margin-bottom","margin-left","margin-right","margin-top","letter-spacing","line-height","orphans","page-break-after","page-break-before","page-break-inside","tab-interval","tab-stop","text-align","text-decoration","text-indent","vertical-align","widows","kerning-mode","xfa-font-horizontal-scale","xfa-font-vertical-scale","xfa-spacerun","xfa-tab-stops"]),eu=new Map([["page-break-after","breakAfter"],["page-break-before","breakBefore"],["page-break-inside","breakInside"],["kerning-mode",A=>"none"===A?"none":"normal"],["xfa-font-horizontal-scale",A=>`scaleX(${Math.max(0,Math.min(parseInt(A)/100)).toFixed(2)})`],["xfa-font-vertical-scale",A=>`scaleY(${Math.max(0,Math.min(parseInt(A)/100)).toFixed(2)})`],["xfa-spacerun",""],["xfa-tab-stops",""],["font-size",(A,e)=>wc(.99*(A=e.fontSize=xI(A)))],["letter-spacing",A=>wc(xI(A))],["line-height",A=>wc(xI(A))],["margin",A=>wc(xI(A))],["margin-bottom",A=>wc(xI(A))],["margin-left",A=>wc(xI(A))],["margin-right",A=>wc(xI(A))],["margin-top",A=>wc(xI(A))],["text-indent",A=>wc(xI(A))],["font-family",A=>A],["vertical-align",A=>wc(xI(A))]]),tu=/\s+/g,iu=/[\r\n]+/g,au=/\r\n?/g;function su(A,e,t){const i=Object.create(null);if(!A)return i;const a=Object.create(null);for(const[e,t]of A.split(";").map((A=>A.split(":",2)))){const A=eu.get(e);if(""===A)continue;let s=t;A&&(s="string"==typeof A?A:A(t,a)),e.endsWith("scale")?i.transform=i.transform?`${i[e]} ${s}`:s:i[e.replaceAll(/-([a-zA-Z])/g,((A,e)=>e.toUpperCase()))]=s}if(i.fontFamily&&Yc({typeface:i.fontFamily,weight:i.fontWeight||"normal",posture:i.fontStyle||"normal",size:a.fontSize||0},e,e[vo].fontFinder,i),t&&i.verticalAlign&&"0px"!==i.verticalAlign&&i.fontSize){const A=.583,e=.333,t=xI(i.fontSize);i.fontSize=wc(t*A),i.verticalAlign=wc(Math.sign(xI(i.verticalAlign))*t*e)}return t&&i.fontSize&&(i.fontSize=`calc(${i.fontSize} * var(--scale-factor))`),Uc(i),i}const nu=new Set(["body","html"]);class gu extends Ec{constructor(A,e){super(_E,e),this[$E]=!1,this.style=A.style||""}[Bo](A){var e;super[Bo](A),this.style=(e=this).style?e.style.trim().split(/\s*;\s*/).filter((A=>!!A)).map((A=>A.split(/\s*:\s*/,2))).filter((([A,t])=>("font-family"===A&&e[vo].usedTypefaces.add(t),Au.has(A)))).map((A=>A.join(":"))).join(";"):""}[oo](){return!nu.has(this[tI])}[nI](A,e=!1){e?this[$E]=!0:(A=A.replaceAll(iu,""),this.style.includes("xfa-spacerun:yes")||(A=A.replaceAll(tu," "))),A&&(this[uo]+=A)}[gI](A,e=!0){const t=Object.create(null),i={top:NaN,bottom:NaN,left:NaN,right:NaN};let a=null;for(const[A,e]of this.style.split(";").map((A=>A.split(":",2))))switch(A){case"font-family":t.typeface=FI(e);break;case"font-size":t.size=xI(e);break;case"font-weight":t.weight=e;break;case"font-style":t.posture=e;break;case"letter-spacing":t.letterSpacing=xI(e);break;case"margin":const A=e.split(/ \t/).map((A=>xI(A)));switch(A.length){case 1:i.top=i.bottom=i.left=i.right=A[0];break;case 2:i.top=i.bottom=A[0],i.left=i.right=A[1];break;case 3:i.top=A[0],i.bottom=A[2],i.left=i.right=A[1];break;case 4:i.top=A[0],i.left=A[1],i.bottom=A[2],i.right=A[3]}break;case"margin-top":i.top=xI(e);break;case"margin-bottom":i.bottom=xI(e);break;case"margin-left":i.left=xI(e);break;case"margin-right":i.right=xI(e);break;case"line-height":a=xI(e)}if(A.pushData(t,i,a),this[uo])A.addString(this[uo]);else for(const e of this[Uo]())"#text"!==e[tI]?e[gI](A):A.addString(e[uo]);e&&A.popFont()}[fI](A){const e=[];if(this[mo]={children:e},this[Co]({}),0===e.length&&!this[uo])return LI.EMPTY;let t;return t=this[$E]?this[uo]?this[uo].replaceAll(au,"\n"):void 0:this[uo]||void 0,LI.success({name:this[tI],attributes:{href:this.href,style:su(this.style,this,this[$E])},children:e,value:t})}}class ru extends gu{constructor(A){super(A,"a"),this.href=vc(A.href)||""}}class ou extends gu{constructor(A){super(A,"b")}[gI](A){A.pushFont({weight:"bold"}),super[gI](A),A.popFont()}}class Iu extends gu{constructor(A){super(A,"body")}[fI](A){const e=super[fI](A),{html:t}=e;return t?(t.name="div",t.attributes.class=["xfaRich"],e):LI.EMPTY}}class cu extends gu{constructor(A){super(A,"br")}[uI](){return"\n"}[gI](A){A.addString("\n")}[fI](A){return LI.success({name:"br"})}}class Cu extends gu{constructor(A){super(A,"html")}[fI](A){const e=[];if(this[mo]={children:e},this[Co]({}),0===e.length)return LI.success({name:"div",attributes:{class:["xfaRich"],style:{}},value:this[uo]||""});if(1===e.length){const A=e[0];if(A.attributes?.class.includes("xfaRich"))return LI.success(A)}return LI.success({name:"div",attributes:{class:["xfaRich"],style:{}},children:e})}}class Bu extends gu{constructor(A){super(A,"i")}[gI](A){A.pushFont({posture:"italic"}),super[gI](A),A.popFont()}}class hu extends gu{constructor(A){super(A,"li")}}class Qu extends gu{constructor(A){super(A,"ol")}}class lu extends gu{constructor(A){super(A,"p")}[gI](A){super[gI](A,!1),A.addString("\n"),A.addPara(),A.popFont()}[uI](){return this[Ho]()[Uo]().at(-1)===this?super[uI]():super[uI]()+"\n"}}class Eu extends gu{constructor(A){super(A,"span")}}class uu extends gu{constructor(A){super(A,"sub")}}class du extends gu{constructor(A){super(A,"sup")}}class fu extends gu{constructor(A){super(A,"ul")}}class pu{static[wI](A,e){if(pu.hasOwnProperty(A))return pu[A](e)}static a(A){return new ru(A)}static b(A){return new ou(A)}static body(A){return new Iu(A)}static br(A){return new cu(A)}static html(A){return new Cu(A)}static i(A){return new Bu(A)}static li(A){return new hu(A)}static ol(A){return new Qu(A)}static p(A){return new lu(A)}static span(A){return new Eu(A)}static sub(A){return new uu(A)}static sup(A){return new du(A)}static ul(A){return new fu(A)}}const mu={config:_l,connection:CE,datasets:lE,localeSet:qE,signature:WE,stylesheet:XE,template:Qh,xdp:zE,xhtml:pu};class yu{constructor(A){this.namespaceId=A}[wI](A,e){return new Ec(this.namespaceId,A,e)}}class wu extends hc{constructor(A){super(-1,"root",Object.create(null)),this.element=null,this[qo]=A}[aI](A){return this.element=A,!0}[yo](){super[yo](),this.element.template instanceof ih&&(this[qo].set(cI,this.element),this.element.template[CI](this[qo]),this.element.template[qo]=this[qo])}}class Du extends hc{constructor(){super(-1,"",Object.create(null))}[aI](A){return!1}}class bu{constructor(A=null){this._namespaceStack=[],this._nsAgnosticLevel=0,this._namespacePrefixes=new Map,this._namespaces=new Map,this._nextNsId=Math.max(...Object.values(DI).map((({id:A})=>A))),this._currentNamespace=A||new yu(++this._nextNsId)}buildRoot(A){return new wu(A)}build({nsPrefix:A,name:e,attributes:t,namespace:i,prefixes:a}){const s=null!==i;if(s&&(this._namespaceStack.push(this._currentNamespace),this._currentNamespace=this._searchNamespace(i)),a&&this._addNamespacePrefix(a),t.hasOwnProperty(iI)){const A=mu.datasets,e=t[iI];let i=null;for(const[t,a]of Object.entries(e))if(this._getNamespaceToUse(t)===A){i={xfa:a};break}i?t[iI]=i:delete t[iI]}const n=this._getNamespaceToUse(A)?.[wI](e,t)||new Du;return n[Vo]()&&this._nsAgnosticLevel++,(s||a||n[Vo]())&&(n[Qo]={hasNamespace:s,prefixes:a,nsAgnostic:n[Vo]()}),n}isNsAgnostic(){return this._nsAgnosticLevel>0}_searchNamespace(A){let e=this._namespaces.get(A);if(e)return e;for(const[t,{check:i}]of Object.entries(DI))if(i(A)){if(e=mu[t],e)return this._namespaces.set(A,e),e;break}return e=new yu(++this._nextNsId),this._namespaces.set(A,e),e}_addNamespacePrefix(A){for(const{prefix:e,value:t}of A){const A=this._searchNamespace(t);let i=this._namespacePrefixes.get(e);i||(i=[],this._namespacePrefixes.set(e,i)),i.push(A)}}_getNamespaceToUse(A){if(!A)return this._currentNamespace;const e=this._namespacePrefixes.get(A);return e?.length>0?e.at(-1):(R(`Unknown namespace prefix: ${A}.`),null)}clean(A){const{hasNamespace:e,prefixes:t,nsAgnostic:i}=A;e&&(this._currentNamespace=this._namespaceStack.pop()),t&&t.forEach((({prefix:A})=>{this._namespacePrefixes.get(A).pop()})),i&&this._nsAgnosticLevel--}}class ku extends Dr{constructor(A=null,e=!1){super(),this._builder=new bu(A),this._stack=[],this._globalData={usedTypefaces:new Set},this._ids=new Map,this._current=this._builder.buildRoot(this._ids),this._errorCode=0,this._whiteRegex=/^\s+$/,this._nbsps=/\xa0+/g,this._richText=e}parse(A){if(this.parseXml(A),0===this._errorCode)return this._current[yo](),this._current.element}onText(A){A=A.replace(this._nbsps,(A=>A.slice(1)+" ")),this._richText||this._current[oo]()?this._current[nI](A,this._richText):this._whiteRegex.test(A)||this._current[nI](A.trim())}onCdata(A){this._current[nI](A)}_mkAttributes(A,e){let t=null,i=null;const a=Object.create({});for(const{name:s,value:n}of A)if("xmlns"===s)t?R(`XFA - multiple namespace definition in <${e}>`):t=n;else if(s.startsWith("xmlns:")){const A=s.substring("xmlns:".length);i||(i=[]),i.push({prefix:A,value:n})}else{const A=s.indexOf(":");if(-1===A)a[s]=n;else{let e=a[iI];e||(e=a[iI]=Object.create(null));const[t,i]=[s.slice(0,A),s.slice(A+1)];(e[t]||=Object.create(null))[i]=n}}return[t,i,a]}_getNameAndPrefix(A,e){const t=A.indexOf(":");return-1===t?[A,null]:[A.substring(t+1),e?"":A.substring(0,t)]}onBeginElement(A,e,t){const[i,a,s]=this._mkAttributes(e,A),[n,g]=this._getNameAndPrefix(A,this._builder.isNsAgnostic()),r=this._builder.build({nsPrefix:g,name:n,attributes:s,namespace:i,prefixes:a});if(r[vo]=this._globalData,t)return r[yo](),this._current[aI](r)&&r[hI](this._ids),void r[Bo](this._builder);this._stack.push(this._current),this._current=r}onEndElement(A){const e=this._current;if(e[Wo]()&&"string"==typeof e[uo]){const A=new ku;A._globalData=this._globalData;const t=A.parse(e[uo]);e[uo]=null,e[aI](t)}e[yo](),this._current=this._stack.pop(),this._current[aI](e)&&e[hI](this._ids),e[Bo](this._builder)}onError(A){this._errorCode=A}}class Fu{constructor(A){try{this.root=(new ku).parse(Fu._createDocument(A));const e=new uh(this.root);this.form=e.bind(),this.dataHandler=new dh(this.root,e.getData()),this.form[vo].template=this.form}catch(A){R(`XFA - an error occurred during parsing and binding: ${A}`)}}isValid(){return this.root&&this.form}_createPagesHelper(){const A=this.form[dI]();return new Promise(((e,t)=>{const i=()=>{try{const t=A.next();t.done?e(t.value):setTimeout(i,0)}catch(A){t(A)}};setTimeout(i,0)}))}async _createPages(){try{this.pages=await this._createPagesHelper(),this.dims=this.pages.children.map((A=>{const{width:e,height:t}=A.attributes.style;return[0,0,parseInt(e),parseInt(t)]}))}catch(A){R(`XFA - an error occurred during layout: ${A}`)}}getBoundingBox(A){return this.dims[A]}async getNumPages(){return this.pages||await this._createPages(),this.dims.length}setImages(A){this.form[vo].images=A}setFonts(A){this.form[vo].fontFinder=new JI(A);const e=[];for(let A of this.form[vo].usedTypefaces)A=FI(A),this.form[vo].fontFinder.find(A)||e.push(A);return e.length>0?e:null}appendFonts(A,e){this.form[vo].fontFinder.add(A,e)}async getPages(){this.pages||await this._createPages();const A=this.pages;return this.pages=null,A}serializeData(A){return this.dataHandler.serialize(A)}static _createDocument(A){return A["/xdp:xdp"]?Object.values(A).join(""):A["xdp:xdp"]}static getRichTextAsHtml(A){if(!A||"string"!=typeof A)return null;try{let e=new ku(pu,!0).parse(A);if(!["body","xhtml"].includes(e[tI])){const A=pu.body({});A[co](e),e=A}const t=e[fI]();if(!t.success)return null;const{html:i}=t,{attributes:a}=i;return a&&(a.class&&(a.class=a.class.filter((A=>!A.startsWith("xfa")))),a.dir="auto"),{html:i,str:e[uI]()}}catch(A){R(`XFA - an error occurred during parsing of rich text: ${A}`)}return null}}class Su{static createGlobals(A){return Promise.all([A.ensureCatalog("acroForm"),A.ensureDoc("xfaDatasets"),A.ensureCatalog("structTreeRoot"),A.ensureCatalog("baseUrl"),A.ensureCatalog("attachments")]).then((([e,t,i,a,s])=>({pdfManager:A,acroForm:e instanceof CA?e:CA.empty,xfaDatasets:t,structTreeRoot:i,baseUrl:a,attachments:s})),(A=>(R(`createGlobals: "${A}".`),null)))}static async create(A,e,t,i,a,s,n){const g=a?await this._getPageIndex(A,e,t.pdfManager):null;return t.pdfManager.ensure(this,"_create",[A,e,t,i,a,s,g,n])}static _create(A,e,t,i,a=!1,s=null,n=null,g=null){const r=A.fetchIfRef(e);if(!(r instanceof CA))return;const{acroForm:o,pdfManager:I}=t,c=e instanceof BA?e.toString():`annot_${i.createObjId()}`;let C=r.get("Subtype");C=C instanceof oA?C.name:null;const B={xref:A,ref:e,dict:r,subtype:C,id:c,annotationGlobals:t,collectFields:a,orphanFields:s,needAppearances:!a&&!0===o.get("NeedAppearances"),pageIndex:n,evaluatorOptions:I.evaluatorOptions,pageRef:g};switch(C){case"Link":return new Tu(B);case"Text":return new qu(B);case"Widget":let A=FA({dict:r,key:"FT"});switch(A=A instanceof oA?A.name:null,A){case"Tx":return new Hu(B);case"Btn":return new Yu(B);case"Ch":return new vu(B);case"Sig":return new Ku(B)}return R(`Unimplemented widget field type "${A}", falling back to base field type.`),new Ju(B);case"Popup":return new Pu(B);case"FreeText":return new Wu(B);case"Line":return new Zu(B);case"Square":return new Ou(B);case"Circle":return new Xu(B);case"PolyLine":return new Vu(B);case"Polygon":return new ju(B);case"Caret":return new zu(B);case"Ink":return new _u(B);case"Highlight":return new $u(B);case"Underline":return new Ad(B);case"Squiggly":return new ed(B);case"StrikeOut":return new td(B);case"Stamp":return new id(B);case"FileAttachment":return new ad(B);default:return a||R(C?`Unimplemented annotation type "${C}", falling back to base annotation.`:"Annotation is missing the required /Subtype."),new Uu(B)}}static async _getPageIndex(A,e,t){try{const i=await A.fetchIfRefAsync(e);if(!(i instanceof CA))return-1;const a=i.getRaw("P");if(a instanceof BA)try{return await t.ensureCatalog("getPageIndex",[a])}catch(A){S(`_getPageIndex -- not a valid page reference: "${A}".`)}if(i.has("Kids"))return-1;const s=await t.ensureDoc("numPages");for(let A=0;AA/255))}function Nu(A,e){const t=A.getArray("QuadPoints");if(!LA(t,null)||0===t.length||t.length%8>0)return null;const i=new Float32Array(t.length);for(let A=0,a=t.length;Ae[2]||he[3]))return null;i.set([C,Q,B,Q,C,h,B,h],A)}return i}function xu(A,e,t){const[i,a,s,n]=V.getAxialAlignedBoundingBox(e,t);if(i===s||a===n)return[1,0,0,1,A[0],A[1]];const g=(A[2]-A[0])/(s-i),r=(A[3]-A[1])/(n-a);return[g,0,0,r,A[0]-i*g,A[1]-a*r]}class Uu{constructor(A){const{dict:e,xref:t,annotationGlobals:i,ref:a,orphanFields:s}=A,n=s?.get(a);n&&e.set("Parent",n),this.setTitle(e.get("T")),this.setContents(e.get("Contents")),this.setModificationDate(e.get("M")),this.setFlags(e.get("F")),this.setRectangle(e.getArray("Rect")),this.setColor(e.getArray("C")),this.setBorderStyle(e),this.setAppearance(e),this.setOptionalContent(e);const g=e.get("MK");this.setBorderAndBackgroundColors(g),this.setRotation(g,e),this.ref=A.ref instanceof BA?A.ref:null,this._streams=[],this.appearance&&this._streams.push(this.appearance);const r=!!(128&this.flags),o=!!(512&this.flags);if(this.data={annotationFlags:this.flags,borderStyle:this.borderStyle,color:this.color,backgroundColor:this.backgroundColor,borderColor:this.borderColor,rotation:this.rotation,contentsObj:this._contents,hasAppearance:!!this.appearance,id:A.id,modificationDate:this.modificationDate,rect:this.rectangle,subtype:A.subtype,hasOwnCanvas:!1,noRotate:!!(16&this.flags),noHTML:r&&o,isEditable:!1,structParent:-1},i.structTreeRoot){let t=e.get("StructParent");this.data.structParent=t=Number.isInteger(t)&&t>=0?t:-1,i.structTreeRoot.addAnnotationIdToPage(A.pageRef,t)}if(A.collectFields){const i=e.get("Kids");if(Array.isArray(i)){const A=[];for(const e of i)e instanceof BA&&A.push(e.toString());0!==A.length&&(this.data.kidIds=A)}this.data.actions=PA(t,e,B),this.data.fieldName=this._constructFieldName(e),this.data.pageIndex=A.pageIndex}const I=e.get("IT");I instanceof oA&&(this.data.it=I.name),this._isOffscreenCanvasSupported=A.evaluatorOptions.isOffscreenCanvasSupported,this._fallbackFontDict=null,this._needAppearances=!1}_hasFlag(A,e){return!!(A&e)}_buildFlags(A,e){let{flags:t}=this;if(void 0===A){if(void 0===e)return;return e?-5&t:-3&t|4}return A?(t|=4,e?-33&t|2:-3&t|I):(t&=-35,e?-5&t:4|t)}_isViewable(A){return!this._hasFlag(A,1)&&!this._hasFlag(A,I)}_isPrintable(A){return this._hasFlag(A,4)&&!this._hasFlag(A,2)&&!this._hasFlag(A,1)}mustBeViewed(A,e){const t=A?.get(this.data.id)?.noView;return void 0!==t?!t:this.viewable&&!this._hasFlag(this.flags,2)}mustBePrinted(A){const e=A?.get(this.data.id)?.noPrint;return void 0!==e?!e:this.printable}mustBeViewedWhenEditing(A,e=null){return A?!this.data.isEditable:!e?.has(this.data.id)}get viewable(){return null!==this.data.quadPoints&&(0===this.flags||this._isViewable(this.flags))}get printable(){return null!==this.data.quadPoints&&0!==this.flags&&this._isPrintable(this.flags)}_parseStringHelper(A){const e="string"==typeof A?z(A):"";return{str:e,dir:e&&"rtl"===xg(e).dir?"rtl":"ltr"}}setDefaultAppearance(A){const{dict:e,annotationGlobals:t}=A,i=FA({dict:e,key:"DA"})||t.acroForm.get("DA");this._defaultAppearance="string"==typeof i?i:"",this.data.defaultAppearanceData=hr(this._defaultAppearance)}setTitle(A){this._title=this._parseStringHelper(A)}setContents(A){this._contents=this._parseStringHelper(A)}setModificationDate(A){this.modificationDate="string"==typeof A?A:null}setFlags(A){this.flags=Number.isInteger(A)&&A>0?A:0,1&this.flags&&"Annotation"!==this.constructor.name&&(this.flags^=1)}hasFlag(A){return this._hasFlag(this.flags,A)}setRectangle(A){this.rectangle=YA(A,[0,0,0,0])}setColor(A){this.color=Ru(A)}setLineEndings(A){if(this.lineEndings=["None","None"],Array.isArray(A)&&2===A.length)for(let e=0;e<2;e++){const t=A[e];if(t instanceof oA)switch(t.name){case"None":continue;case"Square":case"Circle":case"Diamond":case"OpenArrow":case"ClosedArrow":case"Butt":case"ROpenArrow":case"RClosedArrow":case"Slash":this.lineEndings[e]=t.name;continue}R(`Ignoring invalid lineEnding: ${t}`)}}setRotation(A,e){this.rotation=0;let t=A instanceof CA?A.get("R")||0:e.get("Rotate")||0;Number.isInteger(t)&&0!==t&&(t%=360,t<0&&(t+=360),t%90==0&&(this.rotation=t))}setBorderAndBackgroundColors(A){A instanceof CA?(this.borderColor=Ru(A.getArray("BC"),null),this.backgroundColor=Ru(A.getArray("BG"),null)):this.borderColor=this.backgroundColor=null}setBorderStyle(A){if(this.borderStyle=new Mu,A instanceof CA)if(A.has("BS")){const e=A.get("BS");if(e instanceof CA){const A=e.get("Type");A&&!lA(A,"Border")||(this.borderStyle.setWidth(e.get("W"),this.rectangle),this.borderStyle.setStyle(e.get("S")),this.borderStyle.setDashArray(e.getArray("D")))}}else if(A.has("Border")){const e=A.getArray("Border");Array.isArray(e)&&e.length>=3&&(this.borderStyle.setHorizontalCornerRadius(e[0]),this.borderStyle.setVerticalCornerRadius(e[1]),this.borderStyle.setWidth(e[2],this.rectangle),4===e.length&&this.borderStyle.setDashArray(e[3],!0))}else this.borderStyle.setWidth(0)}setAppearance(A){this.appearance=null;const e=A.get("AP");if(!(e instanceof CA))return;const t=e.get("N");if(t instanceof fA)return void(this.appearance=t);if(!(t instanceof CA))return;const i=A.get("AS");if(!(i instanceof oA&&t.has(i.name)))return;const a=t.get(i.name);a instanceof fA&&(this.appearance=a)}setOptionalContent(A){this.oc=null;const e=A.get("OC");e instanceof oA?R("setOptionalContent: Support for /Name-entry is not implemented."):e instanceof CA&&(this.oc=e)}loadResources(A,e){return e.dict.getAsync("Resources").then((e=>{if(e)return new ro(e,A,e.xref).load().then((function(){return e}))}))}async getOperatorList(A,e,t,a){const{hasOwnCanvas:s,id:n,rect:g}=this.data;let r=this.appearance;const o=!!(s&&2&t);if(o&&(g[0]===g[2]||g[1]===g[3]))return this.data.hasOwnCanvas=!1,{opList:new _g,separateForm:!1,separateCanvas:!1};if(!r){if(!o)return{opList:new _g,separateForm:!1,separateCanvas:!1};r=new se(""),r.dict=new CA}const I=r.dict,c=await this.loadResources(["ExtGState","ColorSpace","Pattern","Shading","XObject","Font"],r),C=HA(I.getArray("BBox"),[0,0,1,1]),B=JA(I.getArray("Matrix"),i),h=xu(g,C,B),Q=new _g;let l;return this.oc&&(l=await A.parseMarkedContentProps(this.oc,null)),void 0!==l&&Q.addOp(y,["OC",l]),Q.addOp(80,[n,g,h,B,o]),await A.getOperatorList({stream:r,task:e,resources:c,operatorList:Q,fallbackFontDict:this._fallbackFontDict}),Q.addOp(81,[]),void 0!==l&&Q.addOp(w,[]),this.reset(),{opList:Q,separateForm:!1,separateCanvas:o}}async save(A,e,t){return null}get hasTextContent(){return!1}async extractTextContent(A,e,t){if(!this.appearance)return;const i=await this.loadResources(["ExtGState","Font","Properties","XObject"],this.appearance),a=[],s=[];let n=null;const g={desiredSize:Math.Infinity,ready:!0,enqueue(A,e){for(const e of A.items)void 0!==e.str&&(n||=e.transform.slice(-2),s.push(e.str),e.hasEOL&&(a.push(s.join("").trimEnd()),s.length=0))}};if(await A.getTextContent({stream:this.appearance,task:e,resources:i,includeMarkedContent:!0,keepWhiteSpace:!0,sink:g,viewBox:t}),this.reset(),s.length&&a.push(s.join("").trimEnd()),a.length>1||a[0]){const A=this.appearance.dict,e=HA(A.getArray("BBox"),null),t=JA(A.getArray("Matrix"),null);this.data.textPosition=this._transformPoint(n,e,t),this.data.textContent=a}}_transformPoint(A,e,t){const{rect:i}=this.data;e||=[0,0,1,1],t||=[1,0,0,1,0,0];const a=xu(i,e,t);return a[4]-=i[0],a[5]-=i[1],A=V.applyTransform(A,a),V.applyTransform(A,t)}getFieldObject(){return this.data.kidIds?{id:this.data.id,actions:this.data.actions,name:this.data.fieldName,strokeColor:this.data.borderColor,fillColor:this.data.backgroundColor,type:"",kidIds:this.data.kidIds,page:this.data.pageIndex,rotation:this.rotation}:null}reset(){for(const A of this._streams)A.reset()}_constructFieldName(A){if(!A.has("T")&&!A.has("Parent"))return R("Unknown field name, falling back to empty field name."),"";if(!A.has("Parent"))return z(A.get("T"));const e=[];A.has("T")&&e.unshift(z(A.get("T")));let t=A;const i=new hA;for(A.objId&&i.put(A.objId);t.has("Parent")&&(t=t.get("Parent"),t instanceof CA&&(!t.objId||!i.has(t.objId)));)t.objId&&i.put(t.objId),t.has("T")&&e.unshift(z(t.get("T")));return e.join(".")}}class Mu{constructor(){this.width=1,this.rawWidth=1,this.style=1,this.dashArray=[3],this.horizontalCornerRadius=0,this.verticalCornerRadius=0}setWidth(A,e=[0,0,0,0]){if(A instanceof oA)this.width=0;else if("number"==typeof A){if(A>0){this.rawWidth=A;const t=(e[2]-e[0])/2,i=(e[3]-e[1])/2;t>0&&i>0&&(A>t||A>i)&&(R(`AnnotationBorderStyle.setWidth - ignoring width: ${A}`),A=1)}this.width=A}}setStyle(A){if(A instanceof oA)switch(A.name){case"S":this.style=1;break;case"D":this.style=2;break;case"B":this.style=3;break;case"I":this.style=4;break;case"U":this.style=5}}setDashArray(A,e=!1){if(Array.isArray(A)){let t=!0,i=!0;for(const e of A){if(!(+e>=0)){t=!1;break}e>0&&(i=!1)}0===A.length||t&&!i?(this.dashArray=A,e&&this.setStyle(oA.get("D"))):this.width=0}else A&&(this.width=0)}setHorizontalCornerRadius(A){Number.isInteger(A)&&(this.horizontalCornerRadius=A)}setVerticalCornerRadius(A){Number.isInteger(A)&&(this.verticalCornerRadius=A)}}class Lu extends Uu{constructor(A){super(A);const{dict:e}=A;if(e.has("IRT")){const A=e.getRaw("IRT");this.data.inReplyTo=A instanceof BA?A.toString():null;const t=e.get("RT");this.data.replyType=t instanceof oA?t.name:"R"}let t=null;if(this.data.replyType===o){const A=e.get("IRT");this.setTitle(A.get("T")),this.data.titleObj=this._title,this.setContents(A.get("Contents")),this.data.contentsObj=this._contents,A.has("CreationDate")?(this.setCreationDate(A.get("CreationDate")),this.data.creationDate=this.creationDate):this.data.creationDate=null,A.has("M")?(this.setModificationDate(A.get("M")),this.data.modificationDate=this.modificationDate):this.data.modificationDate=null,t=A.getRaw("Popup"),A.has("C")?(this.setColor(A.getArray("C")),this.data.color=this.color):this.data.color=null}else this.data.titleObj=this._title,this.setCreationDate(e.get("CreationDate")),this.data.creationDate=this.creationDate,t=e.getRaw("Popup"),e.has("C")||(this.data.color=null);this.data.popupRef=t instanceof BA?t.toString():null,e.has("RC")&&(this.data.richText=Fu.getRichTextAsHtml(e.get("RC")))}setCreationDate(A){this.creationDate="string"==typeof A?A:null}_setDefaultAppearance({xref:A,extra:e,strokeColor:t,fillColor:i,blendMode:a,strokeAlpha:s,fillAlpha:n,pointsCallback:g}){let r=Number.MAX_VALUE,o=Number.MAX_VALUE,I=Number.MIN_VALUE,c=Number.MIN_VALUE;const C=["q"];e&&C.push(e),t&&C.push(`${t[0]} ${t[1]} ${t[2]} RG`),i&&C.push(`${i[0]} ${i[1]} ${i[2]} rg`);let B=this.data.quadPoints;B||(B=Float32Array.from([this.rectangle[0],this.rectangle[3],this.rectangle[2],this.rectangle[3],this.rectangle[0],this.rectangle[1],this.rectangle[2],this.rectangle[1]]));for(let A=0,e=B.length;A"string"==typeof A)).map((A=>z(A))):A instanceof oA?z(A.name):"string"==typeof A?z(A):null}hasFieldFlag(A){return!!(this.data.fieldFlags&A)}_isViewable(A){return!0}mustBeViewed(A,e){return e?this.viewable:super.mustBeViewed(A,e)&&!this._hasFlag(this.flags,I)}getRotationMatrix(A){let e=A?.get(this.data.id)?.rotation;return void 0===e&&(e=this.rotation),0===e?i:te(e,this.data.rect[2]-this.data.rect[0],this.data.rect[3]-this.data.rect[1])}getBorderAndBackgroundAppearances(A){let e=A?.get(this.data.id)?.rotation;if(void 0===e&&(e=this.rotation),!this.backgroundColor&&!this.borderColor)return"";const t=this.data.rect[2]-this.data.rect[0],i=this.data.rect[3]-this.data.rect[1],a=0===e||180===e?`0 0 ${t} ${i} re`:`0 0 ${i} ${t} re`;let s="";return this.backgroundColor&&(s=`${lr(this.backgroundColor,!0)} ${a} f `),this.borderColor&&(s+=`${this.borderStyle.width||1} w ${lr(this.borderColor,!1)} ${a} S `),s}async getOperatorList(A,e,t,i){if(16&t&&!(this instanceof Ku)&&!this.data.noHTML&&!this.data.hasOwnCanvas)return{opList:new _g,separateForm:!0,separateCanvas:!1};if(!this._hasText)return super.getOperatorList(A,e,t,i);const a=await this._getAppearance(A,e,t,i);if(this.appearance&&null===a)return super.getOperatorList(A,e,t,i);const s=new _g;if(!this._defaultAppearance||null===a)return{opList:s,separateForm:!1,separateCanvas:!1};const n=!!(this.data.hasOwnCanvas&&2&t),g=[0,0,this.data.rect[2]-this.data.rect[0],this.data.rect[3]-this.data.rect[1]],r=xu(this.data.rect,g,[1,0,0,1,0,0]);let o;this.oc&&(o=await A.parseMarkedContentProps(this.oc,null)),void 0!==o&&s.addOp(y,["OC",o]),s.addOp(80,[this.data.id,this.data.rect,r,this.getRotationMatrix(i),n]);const I=new se(a);return await A.getOperatorList({stream:I,task:e,resources:this._fieldResources.mergedResources,operatorList:s}),s.addOp(81,[]),void 0!==o&&s.addOp(w,[]),{opList:s,separateForm:!1,separateCanvas:n}}_getMKDict(A){const e=new CA(null);return A&&e.set("R",A),this.borderColor&&e.set("BC",Gu(this.borderColor)),this.backgroundColor&&e.set("BG",Gu(this.backgroundColor)),e.size>0?e:null}amendSavedDict(A,e){}async save(A,e,t){const a=t?.get(this.data.id),s=this._buildFlags(a?.noView,a?.noPrint);let n=a?.value,g=a?.rotation;if(n===this.data.fieldValue||void 0===n){if(!this._hasValueFromXFA&&void 0===g&&void 0===s)return null;n||=this.data.fieldValue}if(void 0===g&&!this._hasValueFromXFA&&Array.isArray(n)&&Array.isArray(this.data.fieldValue)&&AA(n,this.data.fieldValue)&&void 0===s)return null;void 0===g&&(g=this.rotation);let r=null;if(!this._needAppearances&&(r=await this._getAppearance(A,e,8,t),null===r&&void 0===s))return null;let o=!1;r?.needAppearances&&(o=!0,r=null);const{xref:I}=A,c=I.fetchIfRef(this.ref);if(!(c instanceof CA))return null;const C=new CA(I);for(const A of c.getKeys())"AP"!==A&&C.set(A,c.getRaw(A));if(void 0!==s&&(C.set("F",s),null===r&&!o)){const A=c.getRaw("AP");A&&C.set("AP",A)}const B={path:this.data.fieldName,value:n};C.set("V",Array.isArray(n)?n.map($A):$A(n)),this.amendSavedDict(t,C);const h=this._getMKDict(g);h&&C.set("MK",h);const Q=[],l=[{ref:this.ref,data:"",xfa:B,needAppearances:o}];if(null!==r){const A=I.getNewTemporaryRef(),e=new CA(I);C.set("AP",e),e.set("N",A);const a=this._getSaveFieldResources(I),s=new se(r),n=s.dict=new CA(I);n.set("Subtype",oA.get("Form")),n.set("Resources",a),n.set("BBox",[0,0,this.data.rect[2]-this.data.rect[0],this.data.rect[3]-this.data.rect[1]]);const g=this.getRotationMatrix(t);g!==i&&n.set("Matrix",g),await Tr(A,s,Q,I),l.push({ref:A,data:Q.join(""),xfa:null,needAppearances:!1}),Q.length=0}return C.set("M",`D:${eA()}`),await Tr(this.ref,C,Q,I),l[0].data=Q.join(""),l}async _getAppearance(A,e,t,i){if(this.hasFieldFlag(c))return null;const a=i?.get(this.data.id);let s,g;if(a&&(s=a.formattedValue||a.value,g=a.rotation),void 0===g&&void 0===s&&!this._needAppearances&&(!this._hasValueFromXFA||this.appearance))return null;const r=this.getBorderAndBackgroundAppearances(i);if(void 0===s&&(s=this.data.fieldValue,!s))return`/Tx BMC q ${r}Q EMC`;if(Array.isArray(s)&&1===s.length&&(s=s[0]),N("string"==typeof s,"Expected `value` to be a string."),s=s.trimEnd(),this.data.combo){const A=this.data.options.find((({exportValue:A})=>s===A));s=A?.displayValue||s}if(""===s)return`/Tx BMC q ${r}Q EMC`;void 0===g&&(g=this.rotation);let o,I=-1;this.data.multiLine?(o=s.split(/\r\n?|\n/).map((A=>A.normalize("NFC"))),I=o.length):o=[s.replace(/\r\n?|\n/,"").normalize("NFC")];let C=this.data.rect[3]-this.data.rect[1],B=this.data.rect[2]-this.data.rect[0];90!==g&&270!==g||([B,C]=[C,B]),this._defaultAppearance||(this.data.defaultAppearanceData=hr(this._defaultAppearance="/Helvetica 0 Tf 0 g"));let h,Q,l,E=await Ju._getFontData(A,e,this.data.defaultAppearanceData,this._fieldResources.mergedResources);const u=[];let d=!1;for(const A of o){const e=E.encodeString(A);e.length>1&&(d=!0),u.push(e.join(""))}if(d&&8&t)return{needAppearances:!0};if(d&&this._isOffscreenCanvasSupported){const t=this.data.comb?"monospace":"sans-serif",i=new Er(A.xref,t),a=i.createFontResources(o.join("")),n=a.getRaw("Font");if(this._fieldResources.mergedResources.has("Font")){const A=this._fieldResources.mergedResources.get("Font");for(const e of n.getKeys())A.set(e,n.getRaw(e))}else this._fieldResources.mergedResources.set("Font",n);const g=i.fontName.name;E=await Ju._getFontData(A,e,{fontName:g,fontSize:0},a);for(let A=0,e=u.length;A2?`/Tx BMC q ${r}BT `+h+` 1 0 0 1 ${zA(2)} ${zA(y)} Tm (${qA(u[0])}) Tj ET Q EMC`:`/Tx BMC q ${r}BT `+h+` 1 0 0 1 0 0 Tm ${this._renderText(u[0],E,Q,B,m,{shift:0},2,y)} ET Q EMC`}static async _getFontData(A,e,t,i){const a=new _g,s={font:null,clone(){return this}},{fontName:n,fontSize:g}=t;return await A.handleSetFont(i,[n&&oA.get(n),g],null,a,e,s,null),s.font}_getTextWidth(A,e){return e.charsToGlyphs(A).reduce(((A,e)=>A+e.width),0)/1e3}_computeFontSize(A,e,t,i,a){let{fontSize:n}=this.data.defaultAppearanceData,g=(n||12)*s,r=Math.round(A/g);if(!n){const o=A=>Math.floor(100*A)/100;if(-1===a){const a=this._getTextWidth(t,i);n=o(Math.min(A/s,e/a)),r=1}else{const I=t.split(/\r\n?|\n/),c=[];for(const A of I){const e=i.encodeString(A).join(""),t=i.charsToGlyphs(e),a=i.getCharPositions(e);c.push({line:e,glyphs:t,positions:a})}const C=t=>{let a=0;for(const s of c)if(a+=this._splitLine(null,i,t,e,s).length*t,a>A)return!0;return!1};for(r=Math.max(r,a);g=A/r,n=o(g/s),C(n);)r++}const{fontName:I,fontColor:c}=this.data.defaultAppearanceData;this._defaultAppearance=function({fontSize:A,fontName:e,fontColor:t}){return`/${KA(e)} ${A} Tf ${lr(t,!0)}`}({fontSize:n,fontName:I,fontColor:c})}return[this._defaultAppearance,n,A/r]}_renderText(A,e,t,i,a,s,n,g){let r;r=1===a?(i-this._getTextWidth(A,e)*t)/2:2===a?i-this._getTextWidth(A,e)*t-n:n;const o=zA(r-s.shift);return s.shift=r,`${o} ${g=zA(g)} Td (${qA(A)}) Tj`}_getSaveFieldResources(A){const{localResources:e,appearanceResources:t,acroFormResources:i}=this._fieldResources,a=this.data.defaultAppearanceData?.fontName;if(!a)return e||CA.empty;for(const A of[e,t])if(A instanceof CA){const e=A.get("Font");if(e instanceof CA&&e.has(a))return A}if(i instanceof CA){const t=i.get("Font");if(t instanceof CA&&t.has(a)){const i=new CA(A);i.set(a,t.getRaw(a));const s=new CA(A);return s.set("Font",i),CA.merge({xref:A,dictArray:[s,e],mergeSubDicts:!0})}}return e||CA.empty}getFieldObject(){return null}}class Hu extends Ju{constructor(A){super(A);const{dict:e}=A;e.has("PMD")&&(this.flags|=2,this.data.hidden=!0,R("Barcodes are not supported")),this.data.hasOwnCanvas=this.data.readOnly&&!this.data.noHTML,this._hasText=!0,"string"!=typeof this.data.fieldValue&&(this.data.fieldValue="");let t=FA({dict:e,key:"Q"});(!Number.isInteger(t)||t<0||t>2)&&(t=null),this.data.textAlignment=t;let i=FA({dict:e,key:"MaxLen"});(!Number.isInteger(i)||i<0)&&(i=0),this.data.maxLen=i,this.data.multiLine=this.hasFieldFlag(4096),this.data.comb=this.hasFieldFlag(16777216)&&!this.hasFieldFlag(4096)&&!this.hasFieldFlag(c)&&!this.hasFieldFlag(1048576)&&0!==this.data.maxLen,this.data.doNotScroll=this.hasFieldFlag(8388608)}get hasTextContent(){return!!this.appearance&&!this._needAppearances}_getCombAppearance(A,e,t,i,a,s,n,g,r,o,I){const c=a/this.data.maxLen,C=this.getBorderAndBackgroundAppearances(I),B=[],h=e.getCharPositions(t);for(const[A,e]of h)B.push(`(${qA(t.substring(A,e))}) Tj`);const Q=B.join(` ${zA(c)} 0 Td `);return`/Tx BMC q ${C}BT `+A+` 1 0 0 1 ${zA(n)} ${zA(g+r)} Tm ${Q} ET Q EMC`}_getMultilineAppearance(A,e,t,i,a,s,n,g,r,o,I,c){const C=[],B=a-2*g,h={shift:0};for(let A=0,s=e.length;Ai?(r.push(A.substring(C,t)),C=t,B=Q,o=-1,c=-1):(B+=Q,o=t,I=a,c=e):B+Q>i?-1!==o?(r.push(A.substring(C,I)),C=I,e=c+1,o=-1,B=0):(r.push(A.substring(C,t)),C=t,B=Q):B+=Q}return Ce?`\\${e}`:"\\s+"));new RegExp(`^\\s*${s}\\s*$`).test(this.data.fieldValue)&&(this.data.textContent=this.data.fieldValue.split("\n"))}getFieldObject(){return{id:this.data.id,value:this.data.fieldValue,defaultValue:this.data.defaultFieldValue||"",multiline:this.data.multiLine,password:this.hasFieldFlag(c),charLimit:this.data.maxLen,comb:this.data.comb,editable:!this.data.readOnly,hidden:this.data.hidden,name:this.data.fieldName,rect:this.data.rect,actions:this.data.actions,page:this.data.pageIndex,strokeColor:this.data.borderColor,fillColor:this.data.backgroundColor,rotation:this.rotation,type:"text"}}}class Yu extends Ju{constructor(A){super(A),this.checkedAppearance=null,this.uncheckedAppearance=null,this.data.checkBox=!this.hasFieldFlag(32768)&&!this.hasFieldFlag(C),this.data.radioButton=this.hasFieldFlag(32768)&&!this.hasFieldFlag(C),this.data.pushButton=this.hasFieldFlag(C),this.data.isTooltipOnly=!1,this.data.checkBox?this._processCheckBox(A):this.data.radioButton?this._processRadioButton(A):this.data.pushButton?(this.data.hasOwnCanvas=!0,this.data.noHTML=!1,this._processPushButton(A)):R("Invalid field flags for button widget annotation")}async getOperatorList(A,e,t,a){if(this.data.pushButton)return super.getOperatorList(A,e,t,!1,a);let s=null,n=null;if(a){const A=a.get(this.data.id);s=A?A.value:null,n=A?A.rotation:null}if(null===s&&this.appearance)return super.getOperatorList(A,e,t,a);null==s&&(s=this.data.checkBox?this.data.fieldValue===this.data.exportValue:this.data.fieldValue===this.data.buttonValue);const g=s?this.checkedAppearance:this.uncheckedAppearance;if(g){const s=this.appearance,r=JA(g.dict.getArray("Matrix"),i);n&&g.dict.set("Matrix",this.getRotationMatrix(a)),this.appearance=g;const o=super.getOperatorList(A,e,t,a);return this.appearance=s,g.dict.set("Matrix",r),o}return{opList:new _g,separateForm:!1,separateCanvas:!1}}async save(A,e,t){return this.data.checkBox?this._saveCheckbox(A,e,t):this.data.radioButton?this._saveRadioButton(A,e,t):null}async _saveCheckbox(A,e,t){if(!t)return null;const i=t.get(this.data.id),a=this._buildFlags(i?.noView,i?.noPrint);let s=i?.rotation,n=i?.value;if(void 0===s&&void 0===a){if(void 0===n)return null;if(this.data.fieldValue===this.data.exportValue===n)return null}let g=A.xref.fetchIfRef(this.ref);if(!(g instanceof CA))return null;g=g.clone(),void 0===s&&(s=this.rotation),void 0===n&&(n=this.data.fieldValue===this.data.exportValue);const r={path:this.data.fieldName,value:n?this.data.exportValue:""},o=oA.get(n?this.data.exportValue:"Off");g.set("V",o),g.set("AS",o),g.set("M",`D:${eA()}`),void 0!==a&&g.set("F",a);const I=this._getMKDict(s);I&&g.set("MK",I);const c=[];return await Tr(this.ref,g,c,A.xref),[{ref:this.ref,data:c.join(""),xfa:r}]}async _saveRadioButton(A,e,t){if(!t)return null;const i=t.get(this.data.id),a=this._buildFlags(i?.noView,i?.noPrint);let s=i?.rotation,n=i?.value;if(void 0===s&&void 0===a){if(void 0===n)return null;if(this.data.fieldValue===this.data.buttonValue===n)return null}let g=A.xref.fetchIfRef(this.ref);if(!(g instanceof CA))return null;g=g.clone(),void 0===n&&(n=this.data.fieldValue===this.data.buttonValue),void 0===s&&(s=this.rotation);const r={path:this.data.fieldName,value:n?this.data.buttonValue:""},o=oA.get(n?this.data.buttonValue:"Off"),I=[];let c=null;if(n)if(this.parent instanceof BA){const e=A.xref.fetch(this.parent);e.set("V",o),await Tr(this.parent,e,I,A.xref),c=I.join(""),I.length=0}else this.parent instanceof CA&&this.parent.set("V",o);this.parent||g.set("V",o),g.set("AS",o),g.set("M",`D:${eA()}`),void 0!==a&&g.set("F",a);const C=this._getMKDict(s);C&&g.set("MK",C),await Tr(this.ref,g,I,A.xref);const B=[{ref:this.ref,data:I.join(""),xfa:r}];return c&&B.push({ref:this.parent,data:c,xfa:null}),B}_getDefaultCheckedAppearance(A,e){const t=this.data.rect[2]-this.data.rect[0],i=this.data.rect[3]-this.data.rect[1],a=[0,0,t,i],s=.8*Math.min(t,i);let n,g;"check"===e?(n={width:.755*s,height:.705*s},g="3"):"disc"===e?(n={width:.791*s,height:.705*s},g="l"):G(`_getDefaultCheckedAppearance - unsupported type: ${e}`);const r=`q BT /PdfJsZaDb ${s} Tf 0 g ${zA((t-n.width)/2)} ${zA((i-n.height)/2)} Td (${g}) Tj ET Q`,o=new CA(A.xref);o.set("FormType",1),o.set("Subtype",oA.get("Form")),o.set("Type",oA.get("XObject")),o.set("BBox",a),o.set("Matrix",[1,0,0,1,0,0]),o.set("Length",r.length);const I=new CA(A.xref),c=new CA(A.xref);c.set("PdfJsZaDb",this.fallbackFontDict),I.set("Font",c),o.set("Resources",I),this.checkedAppearance=new se(r),this.checkedAppearance.dict=o,this._streams.push(this.checkedAppearance)}_processCheckBox(A){const e=A.dict.get("AP");if(!(e instanceof CA))return;const t=e.get("N");if(!(t instanceof CA))return;const i=this._decodeFormValue(A.dict.get("AS"));"string"==typeof i&&(this.data.fieldValue=i);const a=null!==this.data.fieldValue&&"Off"!==this.data.fieldValue?this.data.fieldValue:"Yes",s=t.getKeys();if(0===s.length)s.push("Off",a);else if(1===s.length)"Off"===s[0]?s.push(a):s.unshift("Off");else if(s.includes(a))s.length=0,s.push("Off",a);else{const A=s.find((A=>"Off"!==A));s.length=0,s.push("Off",A)}s.includes(this.data.fieldValue)||(this.data.fieldValue="Off"),this.data.exportValue=s[1];const n=t.get(this.data.exportValue);this.checkedAppearance=n instanceof fA?n:null;const g=t.get("Off");this.uncheckedAppearance=g instanceof fA?g:null,this.checkedAppearance?this._streams.push(this.checkedAppearance):this._getDefaultCheckedAppearance(A,"check"),this.uncheckedAppearance&&this._streams.push(this.uncheckedAppearance),this._fallbackFontDict=this.fallbackFontDict,null===this.data.defaultFieldValue&&(this.data.defaultFieldValue="Off")}_processRadioButton(A){this.data.buttonValue=null;const e=A.dict.get("Parent");if(e instanceof CA){this.parent=A.dict.getRaw("Parent");const t=e.get("V");t instanceof oA&&(this.data.fieldValue=this._decodeFormValue(t))}const t=A.dict.get("AP");if(!(t instanceof CA))return;const i=t.get("N");if(!(i instanceof CA))return;for(const A of i.getKeys())if("Off"!==A){this.data.buttonValue=this._decodeFormValue(A);break}const a=i.get(this.data.buttonValue);this.checkedAppearance=a instanceof fA?a:null;const s=i.get("Off");this.uncheckedAppearance=s instanceof fA?s:null,this.checkedAppearance?this._streams.push(this.checkedAppearance):this._getDefaultCheckedAppearance(A,"disc"),this.uncheckedAppearance&&this._streams.push(this.uncheckedAppearance),this._fallbackFontDict=this.fallbackFontDict,null===this.data.defaultFieldValue&&(this.data.defaultFieldValue="Off")}_processPushButton(A){const{dict:e,annotationGlobals:t}=A;e.has("A")||e.has("AA")||this.data.alternativeText?(this.data.isTooltipOnly=!e.has("A")&&!e.has("AA"),no.parseDestDictionary({destDict:e,resultObj:this.data,docBaseUrl:t.baseUrl,docAttachments:t.attachments})):R("Push buttons without action dictionaries are not supported")}getFieldObject(){let A,e="button";return this.data.checkBox?(e="checkbox",A=this.data.exportValue):this.data.radioButton&&(e="radiobutton",A=this.data.buttonValue),{id:this.data.id,value:this.data.fieldValue||"Off",defaultValue:this.data.defaultFieldValue,exportValues:A,editable:!this.data.readOnly,name:this.data.fieldName,rect:this.data.rect,hidden:this.data.hidden,actions:this.data.actions,page:this.data.pageIndex,strokeColor:this.data.borderColor,fillColor:this.data.backgroundColor,rotation:this.rotation,type:e}}get fallbackFontDict(){const A=new CA;return A.set("BaseFont",oA.get("ZapfDingbats")),A.set("Type",oA.get("FallbackType")),A.set("Subtype",oA.get("FallbackType")),A.set("Encoding",oA.get("ZapfDingbatsEncoding")),U(this,"fallbackFontDict",A)}}class vu extends Ju{constructor(A){super(A);const{dict:e,xref:t}=A;this.indices=e.getArray("I"),this.hasIndices=Array.isArray(this.indices)&&this.indices.length>0,this.data.options=[];const i=FA({dict:e,key:"Opt"});if(Array.isArray(i))for(let A=0,e=i.length;A=0&&e0?this.data.fieldValue[0]:null;return{id:this.data.id,value:e,defaultValue:this.data.defaultFieldValue,editable:!this.data.readOnly,name:this.data.fieldName,rect:this.data.rect,numItems:this.data.fieldValue.length,multipleSelection:this.data.multiSelect,hidden:this.data.hidden,actions:this.data.actions,items:this.data.options,page:this.data.pageIndex,strokeColor:this.data.borderColor,fillColor:this.data.backgroundColor,rotation:this.rotation,type:A}}amendSavedDict(A,e){if(!this.hasIndices)return;let t=A?.get(this.data.id)?.value;Array.isArray(t)||(t=[t]);const i=[],{options:a}=this.data;for(let A=0,e=0,s=a.length;At&&(t=i,e=A)}[B,h]=this._computeFontSize(A,o-4,e,C,-1)}const Q=h*s,l=(Q-h)/2,E=Math.floor(r/Q);let u=0;if(c.length>0){const A=Math.min(...c),e=Math.max(...c);u=Math.max(0,e-E+1),u>A&&(u=A)}const d=Math.min(u+E+1,I),f=["/Tx BMC q",`1 1 ${o} ${r} re W n`];if(c.length){f.push("0.600006 0.756866 0.854904 rg");for(const A of c)u<=A&&AA.trimEnd()));const{coords:A,bbox:e,matrix:t}=Er.getFirstPositionInfo(this.rectangle,this.rotation,i);this.data.textPosition=this._transformPoint(A,e,t)}if(this._isOffscreenCanvasSupported){const a=A.dict.get("CA"),s=new Er(t,"sans-serif");this.appearance=s.createAppearance(this._contents.str,this.rectangle,this.rotation,i,e,a),this._streams.push(this.appearance)}else R("FreeTextAnnotation: OffscreenCanvas is not supported, annotation may not render correctly.")}}get hasTextContent(){return this._hasAppearance}static createNewDict(A,e,{apRef:t,ap:i}){const{color:a,fontSize:s,oldAnnotation:n,rect:g,rotation:r,user:o,value:I}=A,c=n||new CA(e);c.set("Type",oA.get("Annot")),c.set("Subtype",oA.get("FreeText")),n?(c.set("M",`D:${eA()}`),c.delete("RC")):c.set("CreationDate",`D:${eA()}`),c.set("Rect",g);const C=`/Helv ${s} Tf ${lr(a,!0)}`;if(c.set("DA",C),c.set("Contents",$A(I)),c.set("F",4),c.set("Border",[0,0,0]),c.set("Rotate",r),o&&c.set("T",$A(o)),t||i){const A=new CA(e);c.set("AP",A),t?A.set("N",t):A.set("N",i)}return c}static async createNewAppearanceStream(A,e,t){const{baseFontRef:i,evaluator:a,task:n}=t,{color:g,fontSize:r,rect:o,rotation:I,value:c}=A,C=new CA(e),B=new CA(e);if(i)B.set("Helv",i);else{const A=new CA(e);A.set("BaseFont",oA.get("Helvetica")),A.set("Type",oA.get("Font")),A.set("Subtype",oA.get("Type1")),A.set("Encoding",oA.get("WinAnsiEncoding")),B.set("Helv",A)}C.set("Font",B);const h=await Ju._getFontData(a,n,{fontName:"Helv",fontSize:r},C),[Q,l,E,u]=o;let d=E-Q,f=u-l;I%180!=0&&([d,f]=[f,d]);const p=c.split("\n"),m=r/1e3;let y=-1/0;const w=[];for(let A of p){const e=h.encodeString(A);if(e.length>1)return null;A=e.join(""),w.push(A);let t=0;const i=h.charsToGlyphs(A);for(const A of i)t+=A.width*m;y=Math.max(y,t)}let D=1;y>d&&(D=d/y);let b=1;const k=s*r,F=1*r,S=k*p.length;S>f&&(b=f/S);const R=r*Math.min(D,b);let G,N,x;switch(I){case 0:x=[1,0,0,1],N=[o[0],o[1],d,f],G=[o[0],o[3]-F];break;case 90:x=[0,1,-1,0],N=[o[1],-o[2],d,f],G=[o[1],-o[0]-F];break;case 180:x=[-1,0,0,-1],N=[-o[2],-o[3],d,f],G=[-o[2],-o[1]-F];break;case 270:x=[0,-1,1,0],N=[-o[3],o[0],d,f],G=[-o[3],o[2]-F]}const U=["q",`${x.join(" ")} 0 0 cm`,`${N.join(" ")} re W n`,"BT",`${lr(g,!0)}`,`0 Tc /Helv ${zA(R)} Tf`];U.push(`${G.join(" ")} Td (${qA(w[0])}) Tj`);const M=zA(k);for(let A=1,e=w.length;A(A.push(`${i[0]} ${i[1]} m`,`${i[2]} ${i[3]} l`,"S"),[e[0]-r,e[2]+r,e[7]-r,e[3]+r])})}}}class Ou extends Lu{constructor(A){super(A);const{dict:e,xref:t}=A;if(this.data.annotationType=5,this.data.hasOwnCanvas=this.data.noRotate,this.data.noHTML=!1,!this.appearance){const A=this.color?Gu(this.color):[0,0,0],i=e.get("CA"),a=Ru(e.getArray("IC"),null),s=a?Gu(a):null,n=s?i:null;if(0===this.borderStyle.width&&!s)return;this._setDefaultAppearance({xref:t,extra:`${this.borderStyle.width} w`,strokeColor:A,fillColor:s,strokeAlpha:i,fillAlpha:n,pointsCallback:(A,e)=>{const t=e[4]+this.borderStyle.width/2,i=e[5]+this.borderStyle.width/2,a=e[6]-e[4]-this.borderStyle.width,n=e[3]-e[7]-this.borderStyle.width;return A.push(`${t} ${i} ${a} ${n} re`),s?A.push("B"):A.push("S"),[e[0],e[2],e[7],e[3]]}})}}}class Xu extends Lu{constructor(A){super(A);const{dict:e,xref:t}=A;if(this.data.annotationType=6,!this.appearance){const A=this.color?Gu(this.color):[0,0,0],i=e.get("CA"),a=Ru(e.getArray("IC"),null),s=a?Gu(a):null,n=s?i:null;if(0===this.borderStyle.width&&!s)return;const g=4/3*Math.tan(Math.PI/8);this._setDefaultAppearance({xref:t,extra:`${this.borderStyle.width} w`,strokeColor:A,fillColor:s,strokeAlpha:i,fillAlpha:n,pointsCallback:(A,e)=>{const t=e[0]+this.borderStyle.width/2,i=e[1]-this.borderStyle.width/2,a=e[6]-this.borderStyle.width/2,n=e[7]+this.borderStyle.width/2,r=t+(a-t)/2,o=i+(n-i)/2,I=(a-t)/2*g,c=(n-i)/2*g;return A.push(`${r} ${n} m`,`${r+I} ${n} ${a} ${o+c} ${a} ${o} c`,`${a} ${o-c} ${r+I} ${i} ${r} ${i} c`,`${r-I} ${i} ${t} ${o-c} ${t} ${o} c`,`${t} ${o+c} ${r-I} ${n} ${r} ${n} c`,"h"),s?A.push("B"):A.push("S"),[e[0],e[2],e[7],e[3]]}})}}}class Vu extends Lu{constructor(A){super(A);const{dict:e,xref:t}=A;this.data.annotationType=8,this.data.hasOwnCanvas=this.data.noRotate,this.data.noHTML=!1,this.data.vertices=null,this instanceof ju||(this.setLineEndings(e.getArray("LE")),this.data.lineEndings=this.lineEndings);const i=e.getArray("Vertices");if(!LA(i,null))return;const a=this.data.vertices=Float32Array.from(i);if(!this.appearance){const A=this.color?Gu(this.color):[0,0,0],i=e.get("CA"),s=this.borderStyle.width||1,n=2*s,g=[1/0,1/0,-1/0,-1/0];for(let A=0,e=a.length;A{for(let e=0,t=a.length;e{for(const e of this.data.inkLists){for(let t=0,i=e.length;tA.points))),c.set("F",4),c.set("Rotate",o),g&&c.set("IT",oA.get("InkHighlight"));const C=new CA(e);c.set("BS",C),C.set("W",I),c.set("C",Array.from(a,(A=>A/255))),c.set("CA",s);const B=new CA(e);return c.set("AP",B),t?B.set("N",t):B.set("N",i),c}static async createNewAppearanceStream(A,e,t){if(A.outlines)return this.createNewAppearanceStreamForHighlight(A,e,t);const{color:i,rect:a,paths:s,thickness:n,opacity:g}=A,r=[`${n} w 1 J 1 j`,`${lr(i,!1)}`];1!==g&&r.push("/R0 gs");const o=[];for(const{bezier:A}of s){if(o.length=0,o.push(`${zA(A[0])} ${zA(A[1])} m`),2===A.length)o.push(`${zA(A[0])} ${zA(A[1])} l S`);else{for(let e=2,t=A.length;e(A.push(`${e[0]} ${e[1]} m`,`${e[2]} ${e[3]} l`,`${e[6]} ${e[7]} l`,`${e[4]} ${e[5]} l`,"f"),[e[0],e[2],e[7],e[3]])})}}else this.data.popupRef=null}static createNewDict(A,e,{apRef:t,ap:i}){const{color:a,oldAnnotation:s,opacity:n,rect:g,rotation:r,user:o,quadPoints:I}=A,c=s||new CA(e);if(c.set("Type",oA.get("Annot")),c.set("Subtype",oA.get("Highlight")),c.set(s?"M":"CreationDate",`D:${eA()}`),c.set("CreationDate",`D:${eA()}`),c.set("Rect",g),c.set("F",4),c.set("Border",[0,0,0]),c.set("Rotate",r),c.set("QuadPoints",I),c.set("C",Array.from(a,(A=>A/255))),c.set("CA",n),o&&c.set("T",$A(o)),t||i){const A=new CA(e);c.set("AP",A),A.set("N",t||i)}return c}static async createNewAppearanceStream(A,e,t){const{color:i,rect:a,outlines:s,opacity:n}=A,g=[`${lr(i,!0)}`,"/R0 gs"],r=[];for(const A of s){r.length=0,r.push(`${zA(A[0])} ${zA(A[1])} m`);for(let e=2,t=A.length;e(A.push(`${e[4]} ${e[5]+1.3} m`,`${e[6]} ${e[7]+1.3} l`,"S"),[e[0],e[2],e[7],e[3]])})}}else this.data.popupRef=null}}class ed extends Lu{constructor(A){super(A);const{dict:e,xref:t}=A;if(this.data.annotationType=11,this.data.quadPoints=Nu(e,null)){if(!this.appearance){const A=this.color?Gu(this.color):[0,0,0],i=e.get("CA");this._setDefaultAppearance({xref:t,extra:"[] 0 d 1 w",strokeColor:A,strokeAlpha:i,pointsCallback:(A,e)=>{const t=(e[1]-e[5])/6;let i=t,a=e[4];const s=e[5],n=e[6];A.push(`${a} ${s+i} m`);do{a+=2,i=0===i?t:0,A.push(`${a} ${s+i} l`)}while(a(A.push((e[0]+e[4])/2+" "+(e[1]+e[5])/2+" m",(e[2]+e[6])/2+" "+(e[3]+e[7])/2+" l","S"),[e[0],e[2],e[7],e[3]])})}}else this.data.popupRef=null}}class id extends Lu{#q;constructor(A){super(A),this.data.annotationType=13,this.#q=this.data.hasOwnCanvas=this.data.noRotate,this.data.isEditable=!this.data.noHTML,this.data.noHTML=!1}mustBeViewedWhenEditing(A,e=null){return A?!!this.data.isEditable&&(this.#q=this.data.hasOwnCanvas,this.data.hasOwnCanvas=!0,!0):(this.data.hasOwnCanvas=this.#q,!e?.has(this.data.id))}static async createImage(A,e){const{width:t,height:i}=A,a=new OffscreenCanvas(t,i),s=a.getContext("2d",{alpha:!0});s.drawImage(A,0,0);const n=s.getImageData(0,0,t,i).data,g=new Uint32Array(n.buffer),r=g.some(O.isLittleEndian?A=>A>>>24!=255:A=>255!=(255&A));r&&(s.fillStyle="white",s.fillRect(0,0,t,i),s.drawImage(A,0,0));const o=a.convertToBlob({type:"image/jpeg",quality:1}).then((A=>A.arrayBuffer())),I=oA.get("XObject"),c=oA.get("Image"),C=new CA(e);C.set("Type",I),C.set("Subtype",c),C.set("BitsPerComponent",8),C.set("ColorSpace",oA.get("DeviceRGB")),C.set("Filter",oA.get("DCTDecode")),C.set("BBox",[0,0,t,i]),C.set("Width",t),C.set("Height",i);let B=null;if(r){const A=new Uint8Array(g.length);if(O.isLittleEndian)for(let e=0,t=g.length;e>>24;else for(let e=0,t=g.length;e=0&&s<=1?s:null}}function sd(A){try{return _(A)}catch(e){return R(`UTF-8 decoding failed: "${e}".`),A}}class nd extends kr{constructor(A){super(A),this.node=null}onEndElement(A){const e=super.onEndElement(A);if(e&&"xfa:datasets"===A)throw this.node=e,new Error("Aborting DatasetXMLParser.")}}class gd{constructor(A){if(A.datasets)this.node=new kr({hasAttributes:!0}).parseFromString(A.datasets).documentElement;else{const e=new nd({hasAttributes:!0});try{e.parseFromString(A["xdp:xdp"])}catch{}this.node=e.node}}getValue(A){if(!this.node||!A)return"";const e=this.node.searchNode(vA(A),0);return e?"value"===e.firstChild?.nodeName?e.children.map((A=>sd(A.textContent))):sd(e.textContent):""}}class rd{#T=null;constructor(A,e){this.stream=A,this.pdfManager=e,this.entries=[],this._xrefStms=new Set,this._cacheMap=new Map,this._pendingRefs=new hA,this._newPersistentRefNum=null,this._newTemporaryRefNum=null,this._persistentRefsCache=null}getNewPersistentRef(A){null===this._newPersistentRefNum&&(this._newPersistentRefNum=this.entries.length||1);const e=this._newPersistentRefNum++;return this._cacheMap.set(e,A),BA.get(e,0)}getNewTemporaryRef(){if(null===this._newTemporaryRefNum&&(this._newTemporaryRefNum=this.entries.length||1,this._newPersistentRefNum)){this._persistentRefsCache=new Map;for(let A=this._newTemporaryRefNum;A0;){const[n,g]=s;if(!Number.isInteger(n)||!Number.isInteger(g))throw new K(`Invalid XRef range fields: ${n}, ${g}`);if(!Number.isInteger(t)||!Number.isInteger(i)||!Number.isInteger(a))throw new K(`Invalid XRef entry fields length: ${n}, ${g}`);for(let s=e.entryNum;s=A.length);)t+=String.fromCharCode(i),i=A[e];return t}function e(A,e,t){const i=t.length,a=A.length;let s=0;for(;e=i)break;e++,s++}return s}const t=/\b(endobj|\d+\s+\d+\s+obj|xref|trailer\s*<<)\b/g,i=/\b(startxref|\d+\s+\d+\s+obj)\b/g,a=/^(\d+)\s+(\d+)\s+obj\b/,s=new Uint8Array([116,114,97,105,108,101,114]),n=new Uint8Array([115,116,97,114,116,120,114,101,102]),g=new Uint8Array([47,88,82,101,102]);this.entries.length=0,this._cacheMap.clear();const r=this.stream;r.pos=0;const o=r.getBytes(),I=T(o),c=o.length;let C=r.start;const B=[],h=[];for(;C=c)break;Q=o[C]}while(10!==Q&&13!==Q);continue}const l=A(o,C);let E;if(l.startsWith("xref")&&(4===l.length||/\s/.test(l[4])))C+=e(o,C,s),B.push(C),C+=e(o,C,n);else if(E=a.exec(l)){const A=0|E[1],i=0|E[2],a=C+l.length;let s,n=!1;if(this.entries[A]){if(this.entries[A].gen===i)try{new ti({lexer:new si(r.makeSubStream(a))}).getObj(),n=!0}catch(A){A instanceof wA?R(`indexObjects -- checking object (${l}): "${A}".`):n=!0}}else n=!0;n&&(this.entries[A]={offset:C-r.start,gen:i,uncompressed:!0}),t.lastIndex=a;const B=t.exec(I);B?(s=t.lastIndex+1-C,"endobj"!==B[1]&&(R(`indexObjects: Found "${B[1]}" inside of another "obj", caused by missing "endobj" -- trying to recover.`),s-=B[1].length+1)):s=c-C;const Q=o.subarray(C,C+s),u=e(Q,0,g);u0?Math.max(...this._xrefStms):null)}getEntry(A){const e=this.entries[A];return e&&!e.free&&e.offset?e:null}fetchIfRef(A,e=!1){return A instanceof BA?this.fetch(A,e):A}fetch(A,e=!1){if(!(A instanceof BA))throw new Error("ref object is not a reference");const t=A.num,i=this._cacheMap.get(t);if(void 0!==i)return i instanceof CA&&!i.objId&&(i.objId=A.toString()),i;let a=this.getEntry(t);if(null===a)return this._cacheMap.set(t,a),a;if(this._pendingRefs.has(A))return this._pendingRefs.remove(A),R(`Ignoring circular reference: ${A}.`),aA;this._pendingRefs.put(A);try{a=a.uncompressed?this.fetchUncompressed(A,a,e):this.fetchCompressed(A,a,e),this._pendingRefs.remove(A)}catch(e){throw this._pendingRefs.remove(A),e}return a instanceof CA?a.objId=A.toString():a instanceof fA&&(a.dict.objId=A.toString()),a}fetchUncompressed(A,e,t=!1){const i=A.gen;let a=A.num;if(e.gen!==i){const s=`Inconsistent generation in XRef: ${A}`;if(this._generationFallback&&e.gen0&&e[3]-e[1]>0)return e;R(`Empty, or invalid, /${A} entry.`)}return null}get mediaBox(){return U(this,"mediaBox",this._getBoundingBox("MediaBox")||od)}get cropBox(){return U(this,"cropBox",this._getBoundingBox("CropBox")||this.mediaBox)}get userUnit(){let A=this.pageDict.get("UserUnit");return("number"!=typeof A||A<=0)&&(A=1),U(this,"userUnit",A)}get view(){const{cropBox:A,mediaBox:e}=this;if(A!==e&&!AA(A,e)){const t=V.intersect(A,e);if(t&&t[2]-t[0]>0&&t[3]-t[1]>0)return U(this,"view",t);R("Empty /CropBox and /MediaBox intersection.")}return U(this,"view",e)}get rotate(){let A=this._getInheritableProperty("Rotate")||0;return A%90!=0?A=0:A>=360?A%=360:A<0&&(A=(A%360+360)%360),U(this,"rotate",A)}_onSubStreamError(A,e){if(!this.evaluatorOptions.ignoreErrors)throw A;R(`getContentStream - ignoring sub-stream (${e}): "${A}".`)}getContentStream(){return this.pdfManager.ensure(this,"content").then((A=>A instanceof fA?A:Array.isArray(A)?new Se(A,this._onSubStreamError.bind(this)):new ne))}get xfaData(){return U(this,"xfaData",this.xfaFactory?{bbox:this.xfaFactory.getBoundingBox(this.pageIndex)}:null)}async#P(A,e,t){const i=[];for(const a of A)if(a.id){const A=BA.fromString(a.id);if(!A){R(`A non-linked annotation cannot be modified: ${a.id}`);continue}if(a.deleted){if(e.put(A,A),a.popupRef){const A=BA.fromString(a.popupRef);A&&e.put(A,A)}continue}t?.put(A),a.ref=A,i.push(this.xref.fetchAsync(A).then((A=>{A instanceof CA&&(a.oldAnnotation=A.clone())}),(()=>{R(`Cannot fetch \`oldAnnotation\` for: ${A}.`)}))),delete a.id}await Promise.all(i)}async saveNewAnnotations(A,e,t,i){if(this.xfaFactory)throw new Error("XFA: Cannot save new annotations.");const a=new gr({xref:this.xref,handler:A,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions}),s=new QA,n=new hA;await this.#P(t,s,n);const g=this.pageDict,r=this.annotations.filter((A=>!(A instanceof BA&&s.has(A)))),o=await Su.saveNewAnnotations(a,e,t,i);for(const{ref:A}of o.annotations)A instanceof BA&&!n.has(A)&&r.push(A);const I=g.get("Annots");g.set("Annots",r);const c=[];await Tr(this.ref,g,c,this.xref),I&&g.set("Annots",I);const C=o.dependencies;C.push({ref:this.ref,data:c.join("")},...o.annotations);for(const A of s)C.push({ref:A,data:null});return C}save(A,e,t){const i=new gr({xref:this.xref,handler:A,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions});return this._parsedAnnotations.then((function(A){const a=[];for(const s of A)a.push(s.save(i,e,t).catch((function(A){return R(`save - ignoring annotation data during "${e.name}" task: "${A}".`),null})));return Promise.all(a).then((function(A){return A.filter((A=>!!A))}))}))}loadResources(A){return this.resourcesPromise||=this.pdfManager.ensure(this,"resources"),this.resourcesPromise.then((()=>new ro(this.resources,A,this.xref).load()))}getOperatorList({handler:A,sink:e,task:t,intent:i,cacheKey:a,annotationStorage:s=null,modifiedIds:n=null}){const r=this.getContentStream(),o=this.loadResources(["ColorSpace","ExtGState","Font","Pattern","Properties","Shading","XObject"]),I=new gr({xref:this.xref,handler:A,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions}),c=(this.xfaFactory?null:_A(s))?.get(this.pageIndex);let C=Promise.resolve(null),B=null;if(c){const A=this.pdfManager.ensureDoc("annotationGlobals");let e;const i=new Set;for(const{bitmapId:A,bitmap:e}of c)!A||e||i.has(A)||i.add(A);const{isOffscreenCanvasSupported:a}=this.evaluatorOptions;if(i.size>0){const A=c.slice();for(const[e,t]of s)e.startsWith(g)&&t.bitmap&&i.has(t.bitmapId)&&A.push(t);e=Su.generateImages(A,this.xref,a)}else e=Su.generateImages(c,this.xref,a);B=new hA,C=Promise.all([A,this.#P(c,B,null)]).then((([A])=>A?Su.printNewAnnotations(A,I,t,c,e):null))}const h=Promise.all([r,o]).then((([s])=>{const n=new _g(i,e);return A.send("StartRenderPage",{transparency:I.hasBlendModes(this.resources,this.nonBlendModesSet),pageIndex:this.pageIndex,cacheKey:a}),I.getOperatorList({stream:s,task:t,resources:this.resources,operatorList:n}).then((function(){return n}))}));return Promise.all([h,this._parsedAnnotations,C]).then((function([A,e,a]){if(a){e=e.filter((A=>!(A.ref&&B.has(A.ref))));for(let A=0,t=a.length;AA.ref&&dA(A.ref,i.refToReplace)));s>=0&&(e.splice(s,1,i),a.splice(A--,1),t--)}}e=e.concat(a)}if(0===e.length||64&i)return A.flush(!0),{length:A.totalLength};const g=!!(16&i),r=!!(128&i),o=!!(1&i),c=!!(2&i),C=!!(4&i),h=[];for(const A of e)(o||c&&A.mustBeViewed(s,g)&&A.mustBeViewedWhenEditing(r,n)||C&&A.mustBePrinted(s))&&h.push(A.getOperatorList(I,t,i,s).catch((function(A){return R(`getOperatorList - ignoring annotation data during "${t.name}" task: "${A}".`),{opList:null,separateForm:!1,separateCanvas:!1}})));return Promise.all(h).then((function(e){let t=!1,i=!1;for(const{opList:a,separateForm:s,separateCanvas:n}of e)A.addOpList(a),t||=s,i||=n;return A.flush(!0,{form:t,canvas:i}),{length:A.totalLength}}))}))}async extractTextContent({handler:A,task:e,includeMarkedContent:t,disableNormalization:i,sink:a}){const s=this.getContentStream(),n=this.loadResources(["ExtGState","Font","Properties","XObject"]),g=this.pdfManager.ensureCatalog("lang"),[r,,o]=await Promise.all([s,n,g]);return new gr({xref:this.xref,handler:A,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions}).getTextContent({stream:r,task:e,resources:this.resources,includeMarkedContent:t,disableNormalization:i,sink:a,viewBox:this.view,lang:o})}async getStructTree(){const A=await this.pdfManager.ensureCatalog("structTreeRoot");return A?(await this._parsedAnnotations,(await this.pdfManager.ensure(this,"_parseStructTree",[A])).serializable):null}_parseStructTree(A){const e=new to(A,this.pageDict);return e.parse(this.ref),e}async getAnnotationsData(A,e,t){const i=await this._parsedAnnotations;if(0===i.length)return i;const a=[],s=[];let n;const g=!!(1&t),r=!!(2&t),o=!!(4&t);for(const t of i){const i=g||r&&t.viewable;(i||o&&t.printable)&&a.push(t.data),t.hasTextContent&&i&&(n||=new gr({xref:this.xref,handler:A,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions}),s.push(t.extractTextContent(n,e,[-1/0,-1/0,1/0,1/0]).catch((function(A){R(`getAnnotationsData - ignoring textContent during "${e.name}" task: "${A}".`)}))))}return await Promise.all(s),a}get annotations(){const A=this._getInheritableProperty("Annots");return U(this,"annotations",Array.isArray(A)?A:[])}get _parsedAnnotations(){return U(this,"_parsedAnnotations",this.pdfManager.ensure(this,"annotations").then((async A=>{if(0===A.length)return A;const[e,t]=await Promise.all([this.pdfManager.ensureDoc("annotationGlobals"),this.pdfManager.ensureDoc("fieldObjects")]);if(!e)return[];const i=t?.orphanFields,a=[];for(const t of A)a.push(Su.create(this.xref,t,e,this._localIdFactory,!1,i,this.ref).catch((function(A){return R(`_parsedAnnotations: "${A}".`),null})));const s=[];let n,g;for(const A of await Promise.all(a))A&&(A instanceof Ju?(g||=[]).push(A):A instanceof Pu?(n||=[]).push(A):s.push(A));return g&&s.push(...g),n&&s.push(...n),s})))}get jsActions(){return U(this,"jsActions",PA(this.xref,this.pageDict,Q))}}const cd=new Uint8Array([37,80,68,70,45]),Cd=new Uint8Array([115,116,97,114,116,120,114,101,102]),Bd=new Uint8Array([101,110,100,111,98,106]);function hd(A,e,t=1024,i=!1){const a=e.length,s=A.peekBytes(t),n=s.length-a;if(n<=0)return!1;if(i){const t=a-1;let i=s.length-1;for(;i>=t;){let n=0;for(;n=a)return A.pos+=i-t,!0;i--}}else{let t=0;for(;t<=n;){let i=0;for(;i=a)return A.pos+=t,!0;t++}}return!1}class Qd{constructor(A,e){if(e.length<=0)throw new H("The PDF file is empty, i.e. its size is zero bytes.");this.pdfManager=A,this.stream=e,this.xref=new rd(e,A),this._pagePromises=new Map,this._version=null;const t={font:0};this._globalIdFactory=class{static getDocId(){return`g_${A.docId}`}static createFontId(){return"f"+ ++t.font}static createObjId(){G("Abstract method `createObjId` called.")}static getPageObjId(){G("Abstract method `getPageObjId` called.")}}}parse(A){this.xref.parse(A),this.catalog=new no(this.pdfManager,this.xref)}get linearization(){let A=null;try{A=ni.create(this.stream)}catch(A){if(A instanceof yA)throw A;S(A)}return U(this,"linearization",A)}get startXRef(){const A=this.stream;let e=0;if(this.linearization){if(A.reset(),hd(A,Bd)){A.skip(6);let t=A.peekByte();for(;MA(t);)A.pos++,t=A.peekByte();e=A.pos-A.start}}else{const t=1024,i=Cd.length;let a=!1,s=A.end;for(;!a&&s>0;)s-=t-i,s<0&&(s=0),A.pos=s,a=hd(A,Cd,t,!0);if(a){let t;A.skip(9);do{t=A.getByte()}while(MA(t));let i="";for(;t>=32&&t<=57;)i+=String.fromCharCode(t),t=A.getByte();e=parseInt(i,10),isNaN(e)&&(e=0)}}return U(this,"startXRef",e)}checkHeader(){const A=this.stream;if(A.reset(),!hd(A,cd))return;A.moveStart(),A.skip(cd.length);let e,t="";for(;(e=A.getByte())>32&&t.length<7;)t+=String.fromCharCode(e);pA.test(t)?this._version=t:R(`Invalid PDF header version: ${t}`)}parseStartXRef(){this.xref.setStartXRef(this.startXRef)}get numPages(){let A=0;return A=this.catalog.hasActualNumPages?this.catalog.numPages:this.xfaFactory?this.xfaFactory.getNumPages():this.linearization?this.linearization.numPages:this.catalog.numPages,U(this,"numPages",A)}_hasOnlyDocumentSignatures(A,e=0){return!!Array.isArray(A)&&A.every((A=>{if(!((A=this.xref.fetchIfRef(A))instanceof CA))return!1;if(A.has("Kids"))return++e>10?(R("_hasOnlyDocumentSignatures: maximum recursion depth reached"),!1):this._hasOnlyDocumentSignatures(A.get("Kids"),e);const t=lA(A.get("FT"),"Sig"),i=A.get("Rect"),a=Array.isArray(i)&&i.every((A=>0===A));return t&&a}))}get _xfaStreams(){const A=this.catalog.acroForm;if(!A)return null;const e=A.get("XFA"),t={"xdp:xdp":"",template:"",datasets:"",config:"",connectionSet:"",localeSet:"",stylesheet:"","/xdp:xdp":""};if(e instanceof fA&&!e.isEmpty)return t["xdp:xdp"]=e,t;if(!Array.isArray(e)||0===e.length)return null;for(let A=0,i=e.length;A{c.set(A,e)}));const C=[];for(const[A,t]of c){const a=t.get("FontDescriptor");if(!(a instanceof CA))continue;let s=a.get("FontFamily");s=s.replaceAll(/[ ]+(\d)/g,"$1");const n={fontFamily:s,fontWeight:a.get("FontWeight"),italicAngle:-a.get("ItalicAngle")};VA(n)&&C.push(g.handleSetFont(i,[oA.get(A),1],null,r,e,I,null,n).catch((function(A){return R(`loadXfaFonts: "${A}".`),null})))}await Promise.all(C);const B=this.xfaFactory.setFonts(o);if(!B)return;n.ignoreErrors=!0,C.length=0,o.length=0;const h=new Set;for(const A of B)Pn(`${A}-Regular`)||h.add(A);h.size&&B.push("PdfJS-Fallback");for(const A of B)if(!h.has(A))for(const t of[{name:"Regular",fontWeight:400,italicAngle:0},{name:"Bold",fontWeight:700,italicAngle:0},{name:"Italic",fontWeight:400,italicAngle:12},{name:"BoldItalic",fontWeight:700,italicAngle:12}]){const a=`${A}-${t.name}`,s=Wn(a);C.push(g.handleSetFont(i,[oA.get(a),1],null,r,e,I,s,{fontFamily:A,fontWeight:t.fontWeight,italicAngle:t.italicAngle}).catch((function(A){return R(`loadXfaFonts: "${A}".`),null})))}await Promise.all(C),this.xfaFactory.appendFonts(o,h)}async serializeXfaData(A){return this.xfaFactory?this.xfaFactory.serializeData(A):null}get version(){return this.catalog.version||this._version}get formInfo(){const A={hasFields:!1,hasAcroForm:!1,hasXfa:!1,hasSignatures:!1},e=this.catalog.acroForm;if(!e)return U(this,"formInfo",A);try{const t=e.get("Fields"),i=Array.isArray(t)&&t.length>0;A.hasFields=i;const a=e.get("XFA");A.hasXfa=Array.isArray(a)&&a.length>0||a instanceof fA&&!a.isEmpty;const s=!!(1&e.get("SigFlags")),n=s&&this._hasOnlyDocumentSignatures(t);A.hasAcroForm=i&&!n,A.hasSignatures=s}catch(A){if(A instanceof yA)throw A;R(`Cannot fetch form information: "${A}".`)}return U(this,"formInfo",A)}get documentInfo(){const A={PDFFormatVersion:this.version,Language:this.catalog.lang,EncryptFilterName:this.xref.encrypt?this.xref.encrypt.filterName:null,IsLinearized:!!this.linearization,IsAcroFormPresent:this.formInfo.hasAcroForm,IsXFAPresent:this.formInfo.hasXfa,IsCollectionPresent:!!this.catalog.collection,IsSignaturesPresent:this.formInfo.hasSignatures};let e;try{e=this.xref.trailer.get("Info")}catch(A){if(A instanceof yA)throw A;S("The document information dictionary is invalid.")}if(!(e instanceof CA))return U(this,"documentInfo",A);for(const t of e.getKeys()){const i=e.get(t);switch(t){case"Title":case"Author":case"Subject":case"Keywords":case"Creator":case"Producer":case"CreationDate":case"ModDate":if("string"==typeof i){A[t]=z(i);continue}break;case"Trapped":if(i instanceof oA){A[t]=i;continue}break;default:let e;switch(typeof i){case"string":e=z(i);break;case"number":case"boolean":e=i;break;default:i instanceof oA&&(e=i)}if(void 0===e){R(`Bad value, for custom key "${t}", in Info: ${i}.`);continue}A.Custom||(A.Custom=Object.create(null)),A.Custom[t]=e;continue}R(`Bad value, for key "${t}", in Info: ${i}.`)}return U(this,"documentInfo",A)}get fingerprints(){function A(A){return"string"==typeof A&&A.length>0&&"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"!==A}function e(A){const e=[];for(const t of A){const A=t.toString(16);e.push(A.padStart(2,"0"))}return e.join("")}const t=this.xref.trailer.get("ID");let i,a;return Array.isArray(t)&&A(t[0])?(i=P(t[0]),t[1]!==t[0]&&A(t[1])&&(a=P(t[1]))):i=Gr(this.stream.getByteRange(0,1024),0,1024),U(this,"fingerprints",[e(i),a?e(a):null])}async _getLinearizationPage(A){const{catalog:e,linearization:t,xref:i}=this,a=BA.get(t.objectNumberFirst,0);try{const A=await i.fetchAsync(a);if(A instanceof CA){let t=A.getRaw("Type");if(t instanceof BA&&(t=await i.fetchAsync(t)),lA(t,"Page")||!A.has("Type")&&!A.has("Kids")&&A.has("Contents"))return e.pageKidsCountCache.has(a)||e.pageKidsCountCache.put(a,1),e.pageIndexCache.has(a)||e.pageIndexCache.put(a,0),[A,a]}throw new K("The Linearization dictionary doesn't point to a valid Page dictionary.")}catch(t){return R(`_getLinearizationPage: "${t.message}".`),e.getPageDict(A)}}getPage(A){const e=this._pagePromises.get(A);if(e)return e;const{catalog:t,linearization:i,xfaFactory:a}=this;let s;return s=a?Promise.resolve([CA.empty,null]):i?.pageFirst===A?this._getLinearizationPage(A):t.getPageDict(A),s=s.then((([e,i])=>new Id({pdfManager:this.pdfManager,xref:this.xref,pageIndex:A,pageDict:e,ref:i,globalIdFactory:this._globalIdFactory,fontCache:t.fontCache,builtInCMapCache:t.builtInCMapCache,standardFontDataCache:t.standardFontDataCache,globalImageCache:t.globalImageCache,systemFontCache:t.systemFontCache,nonBlendModesSet:t.nonBlendModesSet,xfaFactory:a}))),this._pagePromises.set(A,s),s}async checkFirstPage(A=!1){if(!A)try{await this.getPage(0)}catch(A){if(A instanceof DA)throw this._pagePromises.delete(0),await this.cleanup(),new bA}}async checkLastPage(A=!1){const{catalog:e,pdfManager:t}=this;let i;e.setActualNumPages();try{if(await Promise.all([t.ensureDoc("xfaFactory"),t.ensureDoc("linearization"),t.ensureCatalog("numPages")]),this.xfaFactory)return;if(i=this.linearization?this.linearization.numPages:e.numPages,!Number.isInteger(i))throw new K("Page count is not an integer.");if(i<=1)return;await this.getPage(i-1)}catch(a){if(this._pagePromises.delete(i-1),await this.cleanup(),a instanceof DA&&!A)throw new bA;let s;R(`checkLastPage - invalid /Pages tree /Count: ${i}.`);try{s=await e.getAllPageDicts(A)}catch(t){if(t instanceof DA&&!A)throw new bA;return void e.setActualNumPages(1)}for(const[A,[i,a]]of s){let s;i instanceof Error?(s=Promise.reject(i),s.catch((()=>{}))):s=Promise.resolve(new Id({pdfManager:t,xref:this.xref,pageIndex:A,pageDict:i,ref:a,globalIdFactory:this._globalIdFactory,fontCache:e.fontCache,builtInCMapCache:e.builtInCMapCache,standardFontDataCache:e.standardFontDataCache,globalImageCache:e.globalImageCache,systemFontCache:e.systemFontCache,nonBlendModesSet:e.nonBlendModesSet,xfaFactory:null})),this._pagePromises.set(A,s)}e.setActualNumPages(s.size)}}fontFallback(A,e){return this.catalog.fontFallback(A,e)}async cleanup(A=!1){return this.catalog?this.catalog.cleanup(A):pr()}async#W(A,e,t,i,a,s,n){const{xref:g}=this;if(!(t instanceof BA)||s.has(t))return;s.put(t);const r=await g.fetchAsync(t);if(!(r instanceof CA))return;if(r.has("T")){const e=z(await r.getAsync("T"));A=""===A?e:`${A}.${e}`}else{let t=r;for(;;){if(t=t.getRaw("Parent")||e,t instanceof BA){if(s.has(t))break;t=await g.fetchAsync(t)}if(!(t instanceof CA))break;if(t.has("T")){const e=z(await t.getAsync("T"));A=""===A?e:`${A}.${e}`;break}}}if(e&&!r.has("Parent")&&lA(r.get("Subtype"),"Widget")&&n.put(t,e),i.has(A)||i.set(A,[]),i.get(A).push(Su.create(g,t,a,null,!0,n,null).then((A=>A?.getFieldObject())).catch((function(A){return R(`#collectFieldObjects: "${A}".`),null}))),!r.has("Kids"))return;const o=await r.getAsync("Kids");if(Array.isArray(o))for(const e of o)await this.#W(A,t,e,i,a,s,n)}get fieldObjects(){return this.formInfo.hasFields?U(this,"fieldObjects",Promise.all([this.pdfManager.ensureDoc("annotationGlobals"),this.pdfManager.ensureCatalog("acroForm")]).then((async([A,e])=>{if(!A)return null;const t=new hA,i=Object.create(null),a=new Map,s=new QA;for(const i of await e.getAsync("Fields"))await this.#W("",null,i,a,A,t,s);const n=[];for(const[A,e]of a)n.push(Promise.all(e).then((e=>{(e=e.filter((A=>!!A))).length>0&&(i[A]=e)})));return await Promise.all(n),{allFields:i,orphanFields:s}}))):U(this,"fieldObjects",Promise.resolve(null))}get hasJSActions(){return U(this,"hasJSActions",this.pdfManager.ensureDoc("_parseHasJSActions"))}async _parseHasJSActions(){const[A,e]=await Promise.all([this.pdfManager.ensureCatalog("jsActions"),this.pdfManager.ensureDoc("fieldObjects")]);return!!A||!!e&&Object.values(e.allFields).some((A=>A.some((A=>null!==A.actions))))}get calculationOrderIds(){const A=this.catalog.acroForm;if(!A?.has("CO"))return U(this,"calculationOrderIds",null);const e=A.get("CO");if(!Array.isArray(e)||0===e.length)return U(this,"calculationOrderIds",null);const t=[];for(const A of e)A instanceof BA&&t.push(A.toString());return 0===t.length?U(this,"calculationOrderIds",null):U(this,"calculationOrderIds",t)}get annotationGlobals(){return U(this,"annotationGlobals",Su.createGlobals(this.pdfManager))}}class ld{constructor(A){this._docBaseUrl=function(A){if(A){const e=x(A);if(e)return e.href;R(`Invalid absolute docBaseUrl: "${A}".`)}return null}(A.docBaseUrl),this._docId=A.docId,this._password=A.password,this.enableXfa=A.enableXfa,A.evaluatorOptions.isOffscreenCanvasSupported&&=O.isOffscreenCanvasSupported,this.evaluatorOptions=Object.freeze(A.evaluatorOptions)}get docId(){return this._docId}get password(){return this._password}get docBaseUrl(){return this._docBaseUrl}get catalog(){return this.pdfDocument.catalog}ensureDoc(A,e){return this.ensure(this.pdfDocument,A,e)}ensureXRef(A,e){return this.ensure(this.pdfDocument.xref,A,e)}ensureCatalog(A,e){return this.ensure(this.pdfDocument.catalog,A,e)}getPage(A){return this.pdfDocument.getPage(A)}fontFallback(A,e){return this.pdfDocument.fontFallback(A,e)}loadXfaFonts(A,e){return this.pdfDocument.loadXfaFonts(A,e)}loadXfaImages(){return this.pdfDocument.loadXfaImages()}serializeXfaData(A){return this.pdfDocument.serializeXfaData(A)}cleanup(A=!1){return this.pdfDocument.cleanup(A)}async ensure(A,e,t){G("Abstract method `ensure` called")}requestRange(A,e){G("Abstract method `requestRange` called")}requestLoadedStream(A=!1){G("Abstract method `requestLoadedStream` called")}sendProgressiveData(A){G("Abstract method `sendProgressiveData` called")}updatePassword(A){this._password=A}terminate(A){G("Abstract method `terminate` called")}}class Ed extends ld{constructor(A){super(A);const e=new ae(A.source);this.pdfDocument=new Qd(this,e),this._loadedStreamPromise=Promise.resolve(e)}async ensure(A,e,t){const i=A[e];return"function"==typeof i?i.apply(A,t):i}requestRange(A,e){return Promise.resolve()}requestLoadedStream(A=!1){return this._loadedStreamPromise}terminate(A){}}class ud extends ld{constructor(A){super(A),this.streamManager=new re(A.source,{msgHandler:A.handler,length:A.length,disableAutoFetch:A.disableAutoFetch,rangeChunkSize:A.rangeChunkSize}),this.pdfDocument=new Qd(this,this.streamManager.getStream())}async ensure(A,e,t){try{const i=A[e];return"function"==typeof i?i.apply(A,t):i}catch(i){if(!(i instanceof yA))throw i;return await this.requestRange(i.begin,i.end),this.ensure(A,e,t)}}requestRange(A,e){return this.streamManager.requestRange(A,e)}requestLoadedStream(A=!1){return this.streamManager.requestAllChunks(A)}sendProgressiveData(A){this.streamManager.onReceiveData({chunk:A})}terminate(A){this.streamManager.abort(A)}}function dd(A){switch(A instanceof Error||"object"==typeof A&&null!==A||G('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),A.name){case"AbortException":return new q(A.message);case"MissingPDFException":return new Y(A.message);case"PasswordException":return new L(A.message,A.code);case"UnexpectedResponseException":return new v(A.message,A.status);case"UnknownErrorException":return new J(A.message,A.details);default:return new J(A.message,A.toString())}}class fd{constructor(A,e,t){this.sourceName=A,this.targetName=e,this.comObj=t,this.callbackId=1,this.streamId=1,this.streamSinks=Object.create(null),this.streamControllers=Object.create(null),this.callbackCapabilities=Object.create(null),this.actionHandler=Object.create(null),this._onComObjOnMessage=A=>{const e=A.data;if(e.targetName!==this.sourceName)return;if(e.stream)return void this.#Z(e);if(e.callback){const A=e.callbackId,t=this.callbackCapabilities[A];if(!t)throw new Error(`Cannot resolve callback ${A}`);if(delete this.callbackCapabilities[A],1===e.callback)t.resolve(e.data);else{if(2!==e.callback)throw new Error("Unexpected callback case");t.reject(dd(e.reason))}return}const i=this.actionHandler[e.action];if(!i)throw new Error(`Unknown action from worker: ${e.action}`);if(e.callbackId){const A=this.sourceName,a=e.sourceName;new Promise((function(A){A(i(e.data))})).then((function(i){t.postMessage({sourceName:A,targetName:a,callback:1,callbackId:e.callbackId,data:i})}),(function(i){t.postMessage({sourceName:A,targetName:a,callback:2,callbackId:e.callbackId,reason:dd(i)})}))}else e.streamId?this.#O(e):i(e.data)},t.addEventListener("message",this._onComObjOnMessage)}on(A,e){const t=this.actionHandler;if(t[A])throw new Error(`There is already an actionName called "${A}"`);t[A]=e}send(A,e,t){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:A,data:e},t)}sendWithPromise(A,e,t){const i=this.callbackId++,a=Promise.withResolvers();this.callbackCapabilities[i]=a;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:A,callbackId:i,data:e},t)}catch(A){a.reject(A)}return a.promise}sendWithStream(A,e,t,i){const a=this.streamId++,s=this.sourceName,n=this.targetName,g=this.comObj;return new ReadableStream({start:t=>{const r=Promise.withResolvers();return this.streamControllers[a]={controller:t,startCall:r,pullCall:null,cancelCall:null,isClosed:!1},g.postMessage({sourceName:s,targetName:n,action:A,streamId:a,data:e,desiredSize:t.desiredSize},i),r.promise},pull:A=>{const e=Promise.withResolvers();return this.streamControllers[a].pullCall=e,g.postMessage({sourceName:s,targetName:n,stream:6,streamId:a,desiredSize:A.desiredSize}),e.promise},cancel:A=>{N(A instanceof Error,"cancel must have a valid reason");const e=Promise.withResolvers();return this.streamControllers[a].cancelCall=e,this.streamControllers[a].isClosed=!0,g.postMessage({sourceName:s,targetName:n,stream:1,streamId:a,reason:dd(A)}),e.promise}},t)}#O(A){const e=A.streamId,t=this.sourceName,i=A.sourceName,a=this.comObj,s=this,n=this.actionHandler[A.action],g={enqueue(A,s=1,n){if(this.isCancelled)return;const g=this.desiredSize;this.desiredSize-=s,g>0&&this.desiredSize<=0&&(this.sinkCapability=Promise.withResolvers(),this.ready=this.sinkCapability.promise),a.postMessage({sourceName:t,targetName:i,stream:4,streamId:e,chunk:A},n)},close(){this.isCancelled||(this.isCancelled=!0,a.postMessage({sourceName:t,targetName:i,stream:3,streamId:e}),delete s.streamSinks[e])},error(A){N(A instanceof Error,"error must have a valid reason"),this.isCancelled||(this.isCancelled=!0,a.postMessage({sourceName:t,targetName:i,stream:5,streamId:e,reason:dd(A)}))},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:A.desiredSize,ready:null};g.sinkCapability.resolve(),g.ready=g.sinkCapability.promise,this.streamSinks[e]=g,new Promise((function(e){e(n(A.data,g))})).then((function(){a.postMessage({sourceName:t,targetName:i,stream:8,streamId:e,success:!0})}),(function(A){a.postMessage({sourceName:t,targetName:i,stream:8,streamId:e,reason:dd(A)})}))}#Z(A){const e=A.streamId,t=this.sourceName,i=A.sourceName,a=this.comObj,s=this.streamControllers[e],n=this.streamSinks[e];switch(A.stream){case 8:A.success?s.startCall.resolve():s.startCall.reject(dd(A.reason));break;case 7:A.success?s.pullCall.resolve():s.pullCall.reject(dd(A.reason));break;case 6:if(!n){a.postMessage({sourceName:t,targetName:i,stream:7,streamId:e,success:!0});break}n.desiredSize<=0&&A.desiredSize>0&&n.sinkCapability.resolve(),n.desiredSize=A.desiredSize,new Promise((function(A){A(n.onPull?.())})).then((function(){a.postMessage({sourceName:t,targetName:i,stream:7,streamId:e,success:!0})}),(function(A){a.postMessage({sourceName:t,targetName:i,stream:7,streamId:e,reason:dd(A)})}));break;case 4:if(N(s,"enqueue should have stream controller"),s.isClosed)break;s.controller.enqueue(A.chunk);break;case 3:if(N(s,"close should have stream controller"),s.isClosed)break;s.isClosed=!0,s.controller.close(),this.#X(s,e);break;case 5:N(s,"error should have stream controller"),s.controller.error(dd(A.reason)),this.#X(s,e);break;case 2:A.success?s.cancelCall.resolve():s.cancelCall.reject(dd(A.reason)),this.#X(s,e);break;case 1:if(!n)break;new Promise((function(e){e(n.onCancel?.(dd(A.reason)))})).then((function(){a.postMessage({sourceName:t,targetName:i,stream:2,streamId:e,success:!0})}),(function(A){a.postMessage({sourceName:t,targetName:i,stream:2,streamId:e,reason:dd(A)})})),n.sinkCapability.reject(dd(A.reason)),n.isCancelled=!0,delete this.streamSinks[e];break;default:throw new Error("Unexpected stream case")}}async#X(A,e){await Promise.allSettled([A.startCall?.promise,A.pullCall?.promise,A.cancelCall?.promise]),delete this.streamControllers[e]}destroy(){this.comObj.removeEventListener("message",this._onComObjOnMessage)}}class pd{constructor(A){this._msgHandler=A,this._contentLength=null,this._fullRequestReader=null,this._rangeRequestReaders=[]}getFullReader(){return N(!this._fullRequestReader,"PDFWorkerStream.getFullReader can only be called once."),this._fullRequestReader=new md(this._msgHandler),this._fullRequestReader}getRangeReader(A,e){const t=new yd(A,e,this._msgHandler);return this._rangeRequestReaders.push(t),t}cancelAllRequests(A){this._fullRequestReader?.cancel(A);for(const e of this._rangeRequestReaders.slice(0))e.cancel(A)}}class md{constructor(A){this._msgHandler=A,this.onProgress=null,this._contentLength=null,this._isRangeSupported=!1,this._isStreamingSupported=!1;const e=this._msgHandler.sendWithStream("GetReader");this._reader=e.getReader(),this._headersReady=this._msgHandler.sendWithPromise("ReaderHeadersReady").then((A=>{this._isStreamingSupported=A.isStreamingSupported,this._isRangeSupported=A.isRangeSupported,this._contentLength=A.contentLength}))}get headersReady(){return this._headersReady}get contentLength(){return this._contentLength}get isStreamingSupported(){return this._isStreamingSupported}get isRangeSupported(){return this._isRangeSupported}async read(){const{value:A,done:e}=await this._reader.read();return e?{value:void 0,done:!0}:{value:A.buffer,done:!1}}cancel(A){this._reader.cancel(A)}}class yd{constructor(A,e,t){this._msgHandler=t,this.onProgress=null;const i=this._msgHandler.sendWithStream("GetRangeReader",{begin:A,end:e});this._reader=i.getReader()}get isStreamingSupported(){return!1}async read(){const{value:A,done:e}=await this._reader.read();return e?{value:void 0,done:!0}:{value:A.buffer,done:!1}}cancel(A){this._reader.cancel(A)}}class wd{constructor(A){this.name=A,this.terminated=!1,this._capability=Promise.withResolvers()}get finished(){return this._capability.promise}finish(){this._capability.resolve()}terminate(){this.terminated=!0}ensureNotTerminated(){if(this.terminated)throw new Error("Worker task was terminated")}}class Dd{static setup(A,e){let t=!1;A.on("test",(function(e){t||(t=!0,A.send("test",e instanceof Uint8Array))})),A.on("configure",(function(A){var e;e=A.verbosity,Number.isInteger(e)&&(k=e)})),A.on("GetDocRequest",(function(A){return Dd.createDocumentHandler(A,e)}))}static createDocumentHandler(A,e){let t,i=!1,a=null;const s=new Set,n=F(),{docId:g,apiVersion:r}=A,o="4.7.76";if(r!==o)throw new Error(`The API version "${r}" does not match the Worker version "${o}".`);const I=[];for(const A in[])I.push(A);if(I.length)throw new Error("The `Array.prototype` contains unexpected enumerable properties: "+I.join(", ")+"; thus breaking e.g. `for...in` iteration of `Array`s.");const c=g+"_worker";let C=new fd(c,g,e);function B(){if(i)throw new Error("Worker was terminated")}function h(A){s.add(A)}function Q(A){A.finish(),s.delete(A)}async function l(A){await t.ensureDoc("checkHeader"),await t.ensureDoc("parseStartXRef"),await t.ensureDoc("parse",[A]),await t.ensureDoc("checkFirstPage",[A]),await t.ensureDoc("checkLastPage",[A]);const e=await t.ensureDoc("isPureXfa");if(e){const A=new wd("loadXfaFonts");h(A),await Promise.all([t.loadXfaFonts(C,A).catch((A=>{})).then((()=>Q(A))),t.loadXfaImages()])}const[i,a]=await Promise.all([t.ensureDoc("numPages"),t.ensureDoc("fingerprints")]);return{numPages:i,fingerprints:a,htmlForXfa:e?await t.ensureDoc("htmlForXfa"):null}}return C.on("GetPage",(function(A){return t.getPage(A.pageIndex).then((function(A){return Promise.all([t.ensure(A,"rotate"),t.ensure(A,"ref"),t.ensure(A,"userUnit"),t.ensure(A,"view")]).then((function([A,e,t,i]){return{rotate:A,ref:e,refStr:e?.toString()??null,userUnit:t,view:i}}))}))})),C.on("GetPageIndex",(function(A){const e=BA.get(A.num,A.gen);return t.ensureCatalog("getPageIndex",[e])})),C.on("GetDestinations",(function(A){return t.ensureCatalog("destinations")})),C.on("GetDestination",(function(A){return t.ensureCatalog("getDestination",[A.id])})),C.on("GetPageLabels",(function(A){return t.ensureCatalog("pageLabels")})),C.on("GetPageLayout",(function(A){return t.ensureCatalog("pageLayout")})),C.on("GetPageMode",(function(A){return t.ensureCatalog("pageMode")})),C.on("GetViewerPreferences",(function(A){return t.ensureCatalog("viewerPreferences")})),C.on("GetOpenAction",(function(A){return t.ensureCatalog("openAction")})),C.on("GetAttachments",(function(A){return t.ensureCatalog("attachments")})),C.on("GetDocJSActions",(function(A){return t.ensureCatalog("jsActions")})),C.on("GetPageJSActions",(function({pageIndex:A}){return t.getPage(A).then((function(A){return t.ensure(A,"jsActions")}))})),C.on("GetOutline",(function(A){return t.ensureCatalog("documentOutline")})),C.on("GetOptionalContentConfig",(function(A){return t.ensureCatalog("optionalContentConfig")})),C.on("GetPermissions",(function(A){return t.ensureCatalog("permissions")})),C.on("GetMetadata",(function(A){return Promise.all([t.ensureDoc("documentInfo"),t.ensureCatalog("metadata")])})),C.on("GetMarkInfo",(function(A){return t.ensureCatalog("markInfo")})),C.on("GetData",(function(A){return t.requestLoadedStream().then((function(A){return A.bytes}))})),C.on("GetAnnotations",(function({pageIndex:A,intent:e}){return t.getPage(A).then((function(t){const i=new wd(`GetAnnotations: page ${A}`);return h(i),t.getAnnotationsData(C,i,e).then((A=>(Q(i),A)),(A=>{throw Q(i),A}))}))})),C.on("GetFieldObjects",(function(A){return t.ensureDoc("fieldObjects").then((A=>A?.allFields||null))})),C.on("HasJSActions",(function(A){return t.ensureDoc("hasJSActions")})),C.on("GetCalculationOrderIds",(function(A){return t.ensureDoc("calculationOrderIds")})),C.on("SaveDocument",(async function({isPureXfa:A,numPages:e,annotationStorage:i,filename:a}){const s=[t.requestLoadedStream(),t.ensureCatalog("acroForm"),t.ensureCatalog("acroFormRef"),t.ensureDoc("startXRef"),t.ensureDoc("xref"),t.ensureDoc("linearization"),t.ensureCatalog("structTreeRoot")],n=[],g=A?null:_A(i),[r,o,I,c,B,h,l]=await Promise.all(s),E=B.trailer.getRaw("Root")||null;let u;if(g){l?await l.canUpdateStructTree({pdfManager:t,xref:B,newAnnotationsByPage:g})&&(u=l):await $r.canCreateStructureTree({catalogRef:E,pdfManager:t,newAnnotationsByPage:g})&&(u=null);const A=Su.generateImages(i.values(),B,t.evaluatorOptions.isOffscreenCanvasSupported),e=void 0===u?n:[];for(const[i,a]of g)e.push(t.getPage(i).then((e=>{const t=new wd(`Save (editor): page ${i}`);return e.saveNewAnnotations(C,t,a,A).finally((function(){Q(t)}))})));null===u?n.push(Promise.all(e).then((async A=>(await $r.createStructureTree({newAnnotationsByPage:g,xref:B,catalogRef:E,pdfManager:t,newRefs:A}),A)))):u&&n.push(Promise.all(e).then((async A=>(await u.updateStructureTree({newAnnotationsByPage:g,pdfManager:t,newRefs:A}),A))))}if(A)n.push(t.serializeXfaData(i));else for(let A=0;AA.needAppearances)),y=o instanceof CA&&o.get("XFA")||null;let w=null,D=!1;if(Array.isArray(y)){for(let A=0,e=y.length;A{"string"==typeof t&&(A[e]=z(t))})),b={rootRef:E,encryptRef:B.trailer.getRaw("Encrypt")||null,newRef:B.getNewTemporaryRef(),infoRef:B.trailer.getRaw("Info")||null,info:A,fileIds:B.trailer.get("ID")||null,startXRef:h?c:B.lastXRefStreamPos??c,filename:a}}return _r({originalData:r.bytes,xrefInfo:b,newRefs:f,xref:B,hasXfa:!!y,xfaDatasetsRef:w,hasXfaDatasetsEntry:D,needAppearances:m,acroFormRef:I,acroForm:o,xfaData:p,useXrefStream:uA(B.topDict,"XRef")}).finally((()=>{B.resetNewTemporaryRef()}))})),C.on("GetOperatorList",(function(A,e){const i=A.pageIndex;t.getPage(i).then((function(t){const a=new wd(`GetOperatorList: page ${i}`);h(a);const s=n>=5?Date.now():0;t.getOperatorList({handler:C,sink:e,task:a,intent:A.intent,cacheKey:A.cacheKey,annotationStorage:A.annotationStorage,modifiedIds:A.modifiedIds}).then((function(A){Q(a),s&&S(`page=${i+1} - getOperatorList: time=${Date.now()-s}ms, len=${A.length}`),e.close()}),(function(A){Q(a),a.terminated||e.error(A)}))}))})),C.on("GetTextContent",(function(A,e){const{pageIndex:i,includeMarkedContent:a,disableNormalization:s}=A;t.getPage(i).then((function(A){const t=new wd("GetTextContent: page "+i);h(t);const g=n>=5?Date.now():0;A.extractTextContent({handler:C,task:t,sink:e,includeMarkedContent:a,disableNormalization:s}).then((function(){Q(t),g&&S(`page=${i+1} - getTextContent: time=`+(Date.now()-g)+"ms"),e.close()}),(function(A){Q(t),t.terminated||e.error(A)}))}))})),C.on("GetStructTree",(function(A){return t.getPage(A.pageIndex).then((function(A){return t.ensure(A,"getStructTree")}))})),C.on("FontFallback",(function(A){return t.fontFallback(A.id,C)})),C.on("Cleanup",(function(A){return t.cleanup(!0)})),C.on("Terminate",(function(A){i=!0;const e=[];if(t){t.terminate(new q("Worker was terminated."));const A=t.cleanup();e.push(A),t=null}else pr();a&&a(new q("Worker was terminated."));for(const A of s)e.push(A.finished),A.terminate();return Promise.all(e).then((function(){C.destroy(),C=null}))})),C.on("Ready",(function(e){!function(A){function e(A){B(),C.send("GetDoc",{pdfInfo:A})}function s(A){if(B(),A instanceof L){const e=new wd(`PasswordException: response ${A.code}`);h(e),C.sendWithPromise("PasswordRequest",A).then((function({password:A}){Q(e),t.updatePassword(A),n()})).catch((function(){Q(e),C.send("DocException",A)}))}else A instanceof H||A instanceof Y||A instanceof v||A instanceof J?C.send("DocException",A):C.send("DocException",new J(A.message,A.toString()))}function n(){B(),l(!1).then(e,(function(A){B(),A instanceof bA?t.requestLoadedStream().then((function(){B(),l(!0).then(e,s)})):s(A)}))}B(),function({data:A,password:e,disableAutoFetch:t,rangeChunkSize:i,length:s,docBaseUrl:n,enableXfa:r,evaluatorOptions:o}){const I={source:null,disableAutoFetch:t,docBaseUrl:n,docId:g,enableXfa:r,evaluatorOptions:o,handler:C,length:s,password:e,rangeChunkSize:i},c=Promise.withResolvers();let h;if(A){try{I.source=A,h=new Ed(I),c.resolve(h)}catch(A){c.reject(A)}return c.promise}let Q,l=[];try{Q=new pd(C)}catch(A){return c.reject(A),c.promise}const E=Q.getFullReader();E.headersReady.then((function(){if(E.isRangeSupported){I.source=Q,I.length=E.contentLength,I.disableAutoFetch||=E.isStreamingSupported,h=new ud(I);for(const A of l)h.sendProgressiveData(A);l=[],c.resolve(h),a=null}})).catch((function(A){c.reject(A),a=null}));let u=0;return new Promise((function(A,e){const t=function({value:A,done:i}){try{if(B(),i)return h||function(){const A=kA(l);s&&A.length!==s&&R("reported HTTP length is different from actual");try{I.source=A,h=new Ed(I),c.resolve(h)}catch(A){c.reject(A)}l=[]}(),void(a=null);u+=A.byteLength,E.isStreamingSupported||C.send("DocProgress",{loaded:u,total:Math.max(u,E.contentLength||0)}),h?h.sendProgressiveData(A):l.push(A),E.read().then(t,e)}catch(A){e(A)}};E.read().then(t,e)})).catch((function(A){c.reject(A),a=null})),a=function(A){Q.cancelAllRequests(A)},c.promise}(A).then((function(A){if(i)throw A.terminate(new q("Worker was terminated.")),new Error("Worker was terminated");t=A,t.requestLoadedStream(!0).then((A=>{C.send("DataLoaded",{length:A.bytes.byteLength})}))})).then(n,s)}(A),A=null})),c}static initializeFromPort(A){const e=new fd("worker","main",A);Dd.setup(e,A),e.send("ready",null)}}var bd;return"undefined"==typeof window&&!t&&"undefined"!=typeof self&&"function"==typeof(bd=self).postMessage&&"onmessage"in bd&&Dd.initializeFromPort(self),e})())); \ No newline at end of file diff --git a/dist/332.index.js b/dist/332.index.js deleted file mode 100644 index 2d12f8c..0000000 --- a/dist/332.index.js +++ /dev/null @@ -1 +0,0 @@ -!function(A,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.FileViewer=e():A.FileViewer=e()}(self,(()=>(()=>{"use strict";var A={d:(e,t)=>{for(var i in t)A.o(t,i)&&!A.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},o:(A,e)=>Object.prototype.hasOwnProperty.call(A,e)},e=globalThis.pdfjsWorker={};A.d(e,{WorkerMessageHandler:()=>Rd});const t=!("object"!=typeof process||process+""!="[object process]"||process.versions.nw||process.versions.electron&&process.type&&"browser"!==process.type),i=[1,0,0,1,0,0],a=[.001,0,0,.001,0,0],s=1.35,n=.25925925925925924,g="pdfjs_internal_editor_",r={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},o="Group",I=32,c=8192,C=65536,B={E:"Mouse Enter",X:"Mouse Exit",D:"Mouse Down",U:"Mouse Up",Fo:"Focus",Bl:"Blur",PO:"PageOpen",PC:"PageClose",PV:"PageVisible",PI:"PageInvisible",K:"Keystroke",F:"Format",V:"Validate",C:"Calculate"},h={WC:"WillClose",WS:"WillSave",DS:"DidSave",WP:"WillPrint",DP:"DidPrint"},Q={O:"PageOpen",C:"PageClose"},l={ERRORS:0,WARNINGS:1,INFOS:5},E={NONE:0,BINARY:1},u=10,d=11,f=12,p=37,m=44,y=58,w=59,D=70,b=71,k=83,F=85;let S=l.WARNINGS;function R(){return S}function G(A){S>=l.INFOS&&console.log(`Info: ${A}`)}function N(A){S>=l.WARNINGS&&console.log(`Warning: ${A}`)}function x(A){throw new Error(A)}function U(A,e){A||x(e)}function M(A,e=null,t=null){if(!A)return null;try{if(t&&"string"==typeof A){if(t.addDefaultProtocol&&A.startsWith("www.")){const e=A.match(/\./g);e?.length>=2&&(A=`http://${A}`)}if(t.tryConvertEncoding)try{A=AA(A)}catch{}}const i=e?new URL(A,e):new URL(A);if(function(A){switch(A?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}(i))return i}catch{}return null}function L(A,e,t,i=!1){return Object.defineProperty(A,e,{value:t,enumerable:!i,configurable:!0,writable:!1}),t}const J=function(){function A(A,e){this.message=A,this.name=e}return A.prototype=new Error,A.constructor=A,A}();class H extends J{constructor(A,e){super(A,"PasswordException"),this.code=e}}class Y extends J{constructor(A,e){super(A,"UnknownErrorException"),this.details=e}}class v extends J{constructor(A){super(A,"InvalidPDFException")}}class K extends J{constructor(A){super(A,"MissingPDFException")}}class q extends J{constructor(A,e){super(A,"UnexpectedResponseException"),this.status=e}}class T extends J{constructor(A){super(A,"FormatError")}}class P extends J{constructor(A){super(A,"AbortException")}}function W(A){"object"==typeof A&&void 0!==A?.length||x("Invalid argument for bytesToString");const e=A.length,t=8192;if(e>24&255,A>>16&255,A>>8&255,255&A)}function X(A){return Object.keys(A).length}class V{static get isLittleEndian(){return L(this,"isLittleEndian",function(){const A=new Uint8Array(4);return A[0]=1,1===new Uint32Array(A.buffer,0,1)[0]}())}static get isEvalSupported(){return L(this,"isEvalSupported",function(){try{return new Function(""),!0}catch{return!1}}())}static get isOffscreenCanvasSupported(){return L(this,"isOffscreenCanvasSupported","undefined"!=typeof OffscreenCanvas)}static get platform(){return"undefined"!=typeof navigator&&"string"==typeof navigator?.platform?L(this,"platform",{isMac:navigator.platform.includes("Mac"),isWindows:navigator.platform.includes("Win"),isFirefox:"string"==typeof navigator?.userAgent&&navigator.userAgent.includes("Firefox")}):L(this,"platform",{isMac:!1,isWindows:!1,isFirefox:!1})}static get isCSSRoundSupported(){return L(this,"isCSSRoundSupported",globalThis.CSS?.supports?.("width: round(1.5px, 1px)"))}}const j=Array.from(Array(256).keys(),(A=>A.toString(16).padStart(2,"0")));class z{static makeHexColor(A,e,t){return`#${j[A]}${j[e]}${j[t]}`}static scaleMinMax(A,e){let t;A[0]?(A[0]<0&&(t=e[0],e[0]=e[2],e[2]=t),e[0]*=A[0],e[2]*=A[0],A[3]<0&&(t=e[1],e[1]=e[3],e[3]=t),e[1]*=A[3],e[3]*=A[3]):(t=e[0],e[0]=e[1],e[1]=t,t=e[2],e[2]=e[3],e[3]=t,A[1]<0&&(t=e[1],e[1]=e[3],e[3]=t),e[1]*=A[1],e[3]*=A[1],A[2]<0&&(t=e[0],e[0]=e[2],e[2]=t),e[0]*=A[2],e[2]*=A[2]),e[0]+=A[4],e[1]+=A[5],e[2]+=A[4],e[3]+=A[5]}static transform(A,e){return[A[0]*e[0]+A[2]*e[1],A[1]*e[0]+A[3]*e[1],A[0]*e[2]+A[2]*e[3],A[1]*e[2]+A[3]*e[3],A[0]*e[4]+A[2]*e[5]+A[4],A[1]*e[4]+A[3]*e[5]+A[5]]}static applyTransform(A,e){return[A[0]*e[0]+A[1]*e[2]+e[4],A[0]*e[1]+A[1]*e[3]+e[5]]}static applyInverseTransform(A,e){const t=e[0]*e[3]-e[1]*e[2];return[(A[0]*e[3]-A[1]*e[2]+e[2]*e[5]-e[4]*e[3])/t,(-A[0]*e[1]+A[1]*e[0]+e[4]*e[1]-e[5]*e[0])/t]}static getAxialAlignedBoundingBox(A,e){const t=this.applyTransform(A,e),i=this.applyTransform(A.slice(2,4),e),a=this.applyTransform([A[0],A[3]],e),s=this.applyTransform([A[2],A[1]],e);return[Math.min(t[0],i[0],a[0],s[0]),Math.min(t[1],i[1],a[1],s[1]),Math.max(t[0],i[0],a[0],s[0]),Math.max(t[1],i[1],a[1],s[1])]}static inverseTransform(A){const e=A[0]*A[3]-A[1]*A[2];return[A[3]/e,-A[1]/e,-A[2]/e,A[0]/e,(A[2]*A[5]-A[4]*A[3])/e,(A[4]*A[1]-A[5]*A[0])/e]}static singularValueDecompose2dScale(A){const e=[A[0],A[2],A[1],A[3]],t=A[0]*e[0]+A[1]*e[2],i=A[0]*e[1]+A[1]*e[3],a=A[2]*e[0]+A[3]*e[2],s=A[2]*e[1]+A[3]*e[3],n=(t+s)/2,g=Math.sqrt((t+s)**2-4*(t*s-a*i))/2,r=n+g||1,o=n-g||1;return[Math.sqrt(r),Math.sqrt(o)]}static normalizeRect(A){const e=A.slice(0);return A[0]>A[2]&&(e[0]=A[2],e[2]=A[0]),A[1]>A[3]&&(e[1]=A[3],e[3]=A[1]),e}static intersect(A,e){const t=Math.max(Math.min(A[0],A[2]),Math.min(e[0],e[2])),i=Math.min(Math.max(A[0],A[2]),Math.max(e[0],e[2]));if(t>i)return null;const a=Math.max(Math.min(A[1],A[3]),Math.min(e[1],e[3])),s=Math.min(Math.max(A[1],A[3]),Math.max(e[1],e[3]));return a>s?null:[t,a,i,s]}static#A(A,e,t,i,a,s,n,g,r,o){if(r<=0||r>=1)return;const I=1-r,c=r*r,C=c*r,B=I*(I*(I*A+3*r*e)+3*c*t)+C*i,h=I*(I*(I*a+3*r*s)+3*c*n)+C*g;o[0]=Math.min(o[0],B),o[1]=Math.min(o[1],h),o[2]=Math.max(o[2],B),o[3]=Math.max(o[3],h)}static#e(A,e,t,i,a,s,n,g,r,o,I,c){if(Math.abs(r)<1e-12)return void(Math.abs(o)>=1e-12&&this.#A(A,e,t,i,a,s,n,g,-I/o,c));const C=o**2-4*I*r;if(C<0)return;const B=Math.sqrt(C),h=2*r;this.#A(A,e,t,i,a,s,n,g,(-o+B)/h,c),this.#A(A,e,t,i,a,s,n,g,(-o-B)/h,c)}static bezierBoundingBox(A,e,t,i,a,s,n,g,r){return r?(r[0]=Math.min(r[0],A,n),r[1]=Math.min(r[1],e,g),r[2]=Math.max(r[2],A,n),r[3]=Math.max(r[3],e,g)):r=[Math.min(A,n),Math.min(e,g),Math.max(A,n),Math.max(e,g)],this.#e(A,t,a,n,e,i,s,g,3*(3*(t-a)-A+n),6*(A-2*t+a),3*(t-A),r),this.#e(A,t,a,n,e,i,s,g,3*(3*(i-s)-e+g),6*(e-2*i+s),3*(i-e),r),r}}const _=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,728,711,710,729,733,731,730,732,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8226,8224,8225,8230,8212,8211,402,8260,8249,8250,8722,8240,8222,8220,8221,8216,8217,8218,8482,64257,64258,321,338,352,376,381,305,322,339,353,382,0,8364];function $(A){if(A[0]>="ï"){let e;if("þ"===A[0]&&"ÿ"===A[1]?(e="utf-16be",A.length%2==1&&(A=A.slice(0,-1))):"ÿ"===A[0]&&"þ"===A[1]?(e="utf-16le",A.length%2==1&&(A=A.slice(0,-1))):"ï"===A[0]&&"»"===A[1]&&"¿"===A[2]&&(e="utf-8"),e)try{const t=new TextDecoder(e,{fatal:!0}),i=Z(A),a=t.decode(i);return a.includes("")?a.replaceAll(/\x1b[^\x1b]*(?:\x1b|$)/g,""):a}catch(A){N(`stringToPDFString: "${A}".`)}}const e=[];for(let t=0,i=A.length;t{x("Should not call `set` on the empty dictionary.")},L(this,"empty",A)}static merge({xref:A,dictArray:e,mergeSubDicts:t=!1}){const i=new hA(A),a=new Map;for(const A of e)if(A instanceof hA)for(const[e,i]of Object.entries(A._map)){let A=a.get(e);if(void 0===A)A=[],a.set(e,A);else if(!(t&&i instanceof hA))continue;A.push(i)}for(const[e,t]of a){if(1===t.length||!(t[0]instanceof hA)){i._map[e]=t[0];continue}const a=new hA(A);for(const A of t)for(const[e,t]of Object.entries(A._map))void 0===a._map[e]&&(a._map[e]=t);a.size>0&&(i._map[e]=a)}return a.clear(),i.size>0?i:hA.empty}clone(){const A=new hA(this.xref);for(const e of this.getKeys())A.set(e,this.getRaw(e));return A}delete(A){delete this._map[A]}}class QA{constructor(A,e){this.num=A,this.gen=e}toString(){return 0===this.gen?`${this.num}R`:`${this.num}R${this.gen}`}static fromString(A){const e=IA[A];if(e)return e;const t=/^(\d+)R(\d*)$/.exec(A);return t&&"0"!==t[1]?IA[A]=new QA(parseInt(t[1]),t[2]?parseInt(t[2]):0):null}static get(A,e){const t=0===e?`${A}R`:`${A}R${e}`;return IA[t]||=new QA(A,e)}}class lA{constructor(A=null){this._set=new Set(A?._set)}has(A){return this._set.has(A.toString())}put(A){this._set.add(A.toString())}remove(A){this._set.delete(A.toString())}[Symbol.iterator](){return this._set.values()}clear(){this._set.clear()}}class EA{constructor(){this._map=new Map}get size(){return this._map.size}get(A){return this._map.get(A.toString())}has(A){return this._map.has(A.toString())}put(A,e){this._map.set(A.toString(),e)}putAlias(A,e){this._map.set(A.toString(),this.get(e))}[Symbol.iterator](){return this._map.values()}clear(){this._map.clear()}*items(){for(const[A,e]of this._map)yield[QA.fromString(A),e]}}function uA(A,e){return A instanceof cA&&(void 0===e||A.name===e)}function dA(A,e){return A instanceof CA&&(void 0===e||A.cmd===e)}function fA(A,e){return A instanceof hA&&(void 0===e||uA(A.get("Type"),e))}function pA(A,e){return A.num===e.num&&A.gen===e.gen}class mA{get length(){x("Abstract getter `length` accessed")}get isEmpty(){x("Abstract getter `isEmpty` accessed")}get isDataLoaded(){return L(this,"isDataLoaded",!0)}getByte(){x("Abstract method `getByte` called")}getBytes(A){x("Abstract method `getBytes` called")}async getImageData(A,e){return this.getBytes(A,e)}async asyncGetBytes(){x("Abstract method `asyncGetBytes` called")}get isAsync(){return!1}get canAsyncDecodeImageFromBuffer(){return!1}peekByte(){const A=this.getByte();return-1!==A&&this.pos--,A}peekBytes(A){const e=this.getBytes(A);return this.pos-=e.length,e}getUint16(){const A=this.getByte(),e=this.getByte();return-1===A||-1===e?-1:(A<<8)+e}getInt32(){return(this.getByte()<<24)+(this.getByte()<<16)+(this.getByte()<<8)+this.getByte()}getByteRange(A,e){x("Abstract method `getByteRange` called")}getString(A){return W(this.getBytes(A))}skip(A){this.pos+=A||1}reset(){x("Abstract method `reset` called")}moveStart(){x("Abstract method `moveStart` called")}makeSubStream(A,e,t=null){x("Abstract method `makeSubStream` called")}getBaseStreams(){return null}}const yA=/^[1-9]\.\d$/;function wA(A){let e;return function(){return A&&(e=Object.create(null),A(e),A=null),e}}class DA extends J{constructor(A,e){super(`Missing data [${A}, ${e})`,"MissingDataException"),this.begin=A,this.end=e}}class bA extends J{constructor(A){super(A,"ParserEOFException")}}class kA extends J{constructor(A){super(A,"XRefEntryException")}}class FA extends J{constructor(A){super(A,"XRefParseException")}}function SA(A){const e=A.length;if(0===e)return new Uint8Array(0);if(1===e)return new Uint8Array(A[0]);let t=0;for(let i=0;i0,"The number should be a positive integer.");const t=[];let i;for(;A>=1e3;)A-=1e3,t.push("M");i=A/100|0,A%=100,t.push(GA[i]),i=A/10|0,A%=10,t.push(GA[10+i]),t.push(GA[20+A]);const a=t.join("");return e?a.toLowerCase():a}function xA(A){return A<=0?0:Math.ceil(Math.log2(A))}function UA(A,e){return A[e]<<24>>24}function MA(A,e){return A[e]<<8|A[e+1]}function LA(A,e){return(A[e]<<24|A[e+1]<<16|A[e+2]<<8|A[e+3])>>>0}function JA(A){return 32===A||9===A||13===A||10===A}function HA(A,e){return Array.isArray(A)?(null===e||A.length===e)&&A.every((A=>"number"==typeof A)):ArrayBuffer.isView(A)&&(0===A.length||"number"==typeof A[0])&&(null===e||A.length===e)}function YA(A,e){return HA(A,6)?A:e}function vA(A,e){return HA(A,4)?A:e}function KA(A,e){return HA(A,4)?z.normalizeRect(A):e}function qA(A){const e=/(.+)\[(\d+)\]$/;return A.split(".").map((A=>{const t=A.match(e);return t?{name:t[1],pos:parseInt(t[2],10)}:{name:A,pos:0}}))}function TA(A){const e=[];let t=0;for(let i=0,a=A.length;i126||35===a||40===a||41===a||60===a||62===a||91===a||93===a||123===a||125===a||47===a||37===a)&&(t"\n"===A?"\\n":"\r"===A?"\\r":`\\${A}`))}function WA(A,e,t,i){if(!A)return;let a=null;if(A instanceof QA){if(i.has(A))return;a=A,i.put(a),A=e.fetch(A)}if(Array.isArray(A))for(const a of A)WA(a,e,t,i);else if(A instanceof hA){if(uA(A.get("S"),"JavaScript")){const e=A.get("JS");let i;e instanceof mA?i=e.getString():"string"==typeof e&&(i=e),i&&=$(i).replaceAll("\0",""),i&&t.push(i)}WA(A.getRaw("Next"),e,t,i)}a&&i.remove(a)}function ZA(A,e,t){const i=Object.create(null),a=RA({dict:e,key:"AA",stopWhenFound:!1});if(a)for(let e=a.length-1;e>=0;e--){const s=a[e];if(s instanceof hA)for(const e of s.getKeys()){const a=t[e];if(!a)continue;const n=[];WA(s.getRaw(e),A,n,new lA),n.length>0&&(i[a]=n)}}if(e.has("A")){const t=[];WA(e.get("A"),A,t,new lA),t.length>0&&(i.Action=t)}return X(i)>0?i:null}const OA={60:"<",62:">",38:"&",34:""",39:"'"};function*XA(A){for(let e=0,t=A.length;e55295&&(t<57344||t>65533)&&e++,yield t}}function VA(A){const e=[];let t=0;for(let i=0,a=A.length;i55295&&(a<57344||a>65533)&&i++,t=i+1}return 0===e.length?A:(t: ${A}.`),!1;return!0}function zA(A){const e=new Set(["100","200","300","400","500","600","700","800","900","1000","normal","bold","bolder","lighter"]),{fontFamily:t,fontWeight:i,italicAngle:a}=A;if(!jA(t,!0))return!1;const s=i?i.toString():"";A.fontWeight=e.has(s)?s:"400";const n=parseFloat(a);return A.italicAngle=isNaN(n)||n<-90||n>90?"14":a.toString(),!0}function _A(A){const e=new RegExp("^\\s*("+["app.launchURL","window.open","xfa.host.gotoURL"].join("|").replaceAll(".","\\.")+")\\((?:'|\")([^'\"]*)(?:'|\")(?:,\\s*(\\w+)\\)|\\))","i").exec(A);if(e?.[2]){const A=e[2];let t=!1;return"true"===e[3]&&"app.launchURL"===e[1]&&(t=!0),{url:A,newWindow:t}}return null}function $A(A){if(Number.isInteger(A))return A.toString();const e=Math.round(100*A);return e%100==0?(e/100).toString():e%10==0?A.toFixed(1):A.toFixed(2)}function Ae(A){if(!A)return null;const e=new Map;for(const[t,i]of A){if(!t.startsWith(g))continue;let A=e.get(i.pageIndex);A||(A=[],e.set(i.pageIndex,A)),A.push(i)}return e.size>0?e:null}function ee(A){return function(A){return/^[\x00-\x7F]*$/.test(A)}(A)?A:ie(A,!0)}function te(A){const e=[];for(let t=0,i=A.length;t>8&255).toString(16).padStart(2,"0"),(255&i).toString(16).padStart(2,"0"))}return e.join("")}function ie(A,e=!1){const t=[];e&&t.push("þÿ");for(let e=0,i=A.length;e>8&255),String.fromCharCode(255&i))}return t.join("")}function ae(A,e,t){switch(A){case 90:return[0,1,-1,0,e,0];case 180:return[-1,0,0,-1,e,t];case 270:return[0,-1,1,0,0,t];default:throw new Error("Invalid rotation")}}function se(A){return Math.ceil(Math.ceil(Math.log2(1+A))/8)}class ne extends mA{constructor(A,e,t,i){super(),this.bytes=A instanceof Uint8Array?A:new Uint8Array(A),this.start=e||0,this.pos=this.start,this.end=e+t||this.bytes.length,this.dict=i}get length(){return this.end-this.start}get isEmpty(){return 0===this.length}getByte(){return this.pos>=this.end?-1:this.bytes[this.pos++]}getBytes(A){const e=this.bytes,t=this.pos,i=this.end;if(!A)return e.subarray(t,i);let a=t+A;return a>i&&(a=i),this.pos=a,e.subarray(t,a)}getByteRange(A,e){return A<0&&(A=0),e>this.end&&(e=this.end),this.bytes.subarray(A,e)}reset(){this.pos=this.start}moveStart(){this.start=this.pos}makeSubStream(A,e,t=null){return new ne(this.bytes.buffer,A,e,t)}}class ge extends ne{constructor(A){super(Z(A))}}class re extends ne{constructor(){super(new Uint8Array(0))}}class oe extends ne{constructor(A,e,t){super(new Uint8Array(A),0,A,null),this.chunkSize=e,this._loadedChunks=new Set,this.numChunks=Math.ceil(A/e),this.manager=t,this.progressiveDataLength=0,this.lastSuccessfulEnsureByteChunk=-1}getMissingChunks(){const A=[];for(let e=0,t=this.numChunks;e=this.end?this.numChunks:Math.floor(e/this.chunkSize);for(let A=t;Athis.numChunks)&&e!==this.lastSuccessfulEnsureByteChunk){if(!this._loadedChunks.has(e))throw new DA(A,A+1);this.lastSuccessfulEnsureByteChunk=e}}ensureRange(A,e){if(A>=e)return;if(e<=this.progressiveDataLength)return;const t=Math.floor(A/this.chunkSize);if(t>this.numChunks)return;const i=Math.min(Math.floor((e-1)/this.chunkSize)+1,this.numChunks);for(let a=t;a=this.end?-1:(A>=this.progressiveDataLength&&this.ensureByte(A),this.bytes[this.pos++])}getBytes(A){const e=this.bytes,t=this.pos,i=this.end;if(!A)return i>this.progressiveDataLength&&this.ensureRange(t,i),e.subarray(t,i);let a=t+A;return a>i&&(a=i),a>this.progressiveDataLength&&this.ensureRange(t,a),this.pos=a,e.subarray(t,a)}getByteRange(A,e){return A<0&&(A=0),e>this.end&&(e=this.end),e>this.progressiveDataLength&&this.ensureRange(A,e),this.bytes.subarray(A,e)}makeSubStream(A,e,t=null){function i(){}e?A+e>this.progressiveDataLength&&this.ensureRange(A,A+e):A>=this.progressiveDataLength&&this.ensureByte(A),i.prototype=Object.create(this),i.prototype.getMissingChunks=function(){const A=this.chunkSize,e=Math.floor(this.start/A),t=Math.floor((this.end-1)/A)+1,i=[];for(let A=e;A{const s=({value:n,done:g})=>{try{if(g){const e=SA(i);return i=null,void A(e)}a+=n.byteLength,t.isStreamingSupported&&this.onProgress({loaded:a}),i.push(n),t.read().then(s,e)}catch(A){e(A)}};t.read().then(s,e)})).then((e=>{this.aborted||this.onReceiveData({chunk:e,begin:A})}))}requestAllChunks(A=!1){if(!A){const A=this.stream.getMissingChunks();this._requestChunks(A)}return this._loadedStreamCapability.promise}_requestChunks(A){const e=this.currRequestId++,t=new Set;this._chunksNeededByRequest.set(e,t);for(const e of A)this.stream.hasChunk(e)||t.add(e);if(0===t.size)return Promise.resolve();const i=Promise.withResolvers();this._promisesByRequest.set(e,i);const a=[];for(const A of t){let t=this._requestsByChunk.get(A);t||(t=[],this._requestsByChunk.set(A,t),a.push(A)),t.push(e)}if(a.length>0){const A=this.groupChunks(a);for(const e of A){const A=e.beginChunk*this.chunkSize,t=Math.min(e.endChunk*this.chunkSize,this.length);this.sendRequest(A,t).catch(i.reject)}}return i.promise.catch((A=>{if(!this.aborted)throw A}))}getStream(){return this.stream}requestRange(A,e){e=Math.min(e,this.length);const t=this.getBeginChunk(A),i=this.getEndChunk(e),a=[];for(let A=t;A=0&&i+1!==s&&(e.push({beginChunk:t,endChunk:i+1}),t=s),a+1===A.length&&e.push({beginChunk:t,endChunk:s+1}),i=s}return e}onProgress(A){this.msgHandler.send("DocProgress",{loaded:this.stream.numChunksLoaded*this.chunkSize+A.loaded,total:this.length})}onReceiveData(A){const e=A.chunk,t=void 0===A.begin,i=t?this.progressiveDataLength:A.begin,a=i+e.byteLength,s=Math.floor(i/this.chunkSize),n=a0||g.push(t)}}}if(!this.disableAutoFetch&&0===this._requestsByChunk.size){let A;if(1===this.stream.numChunksLoaded){const e=this.stream.numChunks-1;this.stream.hasChunk(e)||(A=e)}else A=this.stream.nextEmptyChunk(n);Number.isInteger(A)&&this._requestChunks([A])}for(const A of g){const e=this._promisesByRequest.get(A);this._promisesByRequest.delete(A),e.resolve()}this.msgHandler.send("DocProgress",{loaded:this.stream.numChunksLoaded*this.chunkSize,total:this.length})}onError(A){this._loadedStreamCapability.reject(A)}getBeginChunk(A){return Math.floor(A/this.chunkSize)}getEndChunk(A){return Math.floor((A-1)/this.chunkSize)+1}abort(A){this.aborted=!0,this.pdfNetworkStream?.cancelAllRequests(A);for(const e of this._promisesByRequest.values())e.reject(A)}}class ce{constructor(A,e){this.name=A,this.numComps=e}getRgb(A,e){const t=new Uint8ClampedArray(3);return this.getRgbItem(A,e,t,0),t}getRgbItem(A,e,t,i){x("Should not call ColorSpace.getRgbItem")}getRgbBuffer(A,e,t,i,a,s,n){x("Should not call ColorSpace.getRgbBuffer")}getOutputLength(A,e){x("Should not call ColorSpace.getOutputLength")}isPassthrough(A){return!1}isDefaultDecode(A,e){return ce.isDefaultDecode(A,this.numComps)}fillRgb(A,e,t,i,a,s,n,g,r){const o=e*t;let I=null;const c=1<c&&"DeviceGray"!==this.name&&"DeviceRGB"!==this.name){const e=n<=8?new Uint8Array(c):new Uint16Array(c);for(let A=0;A=.99554525?1:this.#Q(0,1,1.055*A**(1/2.4)-.055)}#Q(A,e,t){return Math.max(A,Math.min(e,t))}#l(A){return A<0?-this.#l(-A):A>8?((A+16)/116)**3:A*fe.#I}#E(A,e,t){if(0===A[0]&&0===A[1]&&0===A[2])return t[0]=e[0],t[1]=e[1],void(t[2]=e[2]);const i=this.#l(0),a=(1-i)/(1-this.#l(A[0])),s=1-a,n=(1-i)/(1-this.#l(A[1])),g=1-n,r=(1-i)/(1-this.#l(A[2])),o=1-r;t[0]=e[0]*a+s,t[1]=e[1]*n+g,t[2]=e[2]*r+o}#u(A,e,t){if(1===A[0]&&1===A[2])return t[0]=e[0],t[1]=e[1],void(t[2]=e[2]);const i=t;this.#c(fe.#i,e,i);const a=fe.#g;this.#C(A,i,a),this.#c(fe.#a,a,t)}#d(A,e,t){const i=t;this.#c(fe.#i,e,i);const a=fe.#g;this.#B(A,i,a),this.#c(fe.#a,a,t)}#t(A,e,t,i,a){const s=this.#Q(0,1,A[e]*a),n=this.#Q(0,1,A[e+1]*a),g=this.#Q(0,1,A[e+2]*a),r=1===s?1:s**this.GR,o=1===n?1:n**this.GG,I=1===g?1:g**this.GB,c=this.MXA*r+this.MXB*o+this.MXC*I,C=this.MYA*r+this.MYB*o+this.MYC*I,B=this.MZA*r+this.MZB*o+this.MZC*I,h=fe.#r;h[0]=c,h[1]=C,h[2]=B;const Q=fe.#o;this.#u(this.whitePoint,h,Q);const l=fe.#r;this.#E(this.blackPoint,Q,l);const E=fe.#o;this.#d(fe.#n,l,E);const u=fe.#r;this.#c(fe.#s,E,u),t[i]=255*this.#h(u[0]),t[i+1]=255*this.#h(u[1]),t[i+2]=255*this.#h(u[2])}getRgbItem(A,e,t,i){this.#t(A,e,t,i,1)}getRgbBuffer(A,e,t,i,a,s,n){const g=1/((1<this.amax||this.bmin>this.bmax)&&(G("Invalid Range, falling back to defaults"),this.amin=-100,this.amax=100,this.bmin=-100,this.bmax=100)}#f(A){return A>=6/29?A**3:108/841*(A-4/29)}#p(A,e,t,i){return t+A*(i-t)/e}#t(A,e,t,i,a){let s=A[e],n=A[e+1],g=A[e+2];!1!==t&&(s=this.#p(s,t,0,100),n=this.#p(n,t,this.amin,this.amax),g=this.#p(g,t,this.bmin,this.bmax)),n>this.amax?n=this.amax:nthis.bmax?g=this.bmax:g>>0}function ye(A,e){return 1===e?String.fromCharCode(A[0],A[1]):3===e?String.fromCharCode(A[0],A[1],A[2],A[3]):String.fromCharCode(...A.subarray(0,e+1))}function we(A,e,t){let i=0;for(let a=t;a>=0;a--)i+=A[a]+e[a],A[a]=255&i,i>>=8}function De(A,e){let t=1;for(let i=e;i>=0&&t>0;i--)t+=A[i],A[i]=255&t,t>>=8}const be=16;class ke{constructor(A){this.buffer=A,this.pos=0,this.end=A.length,this.tmpBuf=new Uint8Array(19)}readByte(){return this.pos>=this.end?-1:this.buffer[this.pos++]}readNumber(){let A,e=0;do{const t=this.readByte();if(t<0)throw new T("unexpected EOF in bcmap");A=!(128&t),e=e<<7|127&t}while(!A);return e}readSigned(){const A=this.readNumber();return 1&A?~(A>>>1):A>>>1}readHex(A,e){A.set(this.buffer.subarray(this.pos,this.pos+e+1)),this.pos+=e+1}readHexNumber(A,e){let t;const i=this.tmpBuf;let a=0;do{const A=this.readByte();if(A<0)throw new T("unexpected EOF in bcmap");t=!(128&A),i[a++]=127&A}while(!t);let s=e,n=0,g=0;for(;s>=0;){for(;g<8&&i.length>0;)n|=i[--a]<>=8,g-=8}}readHexSigned(A,e){this.readHexNumber(A,e);const t=1&A[e]?255:0;let i=0;for(let a=0;a<=e;a++)i=(1&i)<<8|A[a],A[a]=i>>1^t}readString(){const A=this.readNumber(),e=new Array(A);for(let t=0;t=0;){const A=C>>5;if(7===A){switch(31&C){case 0:i.readString();break;case 1:s=i.readString()}continue}const t=!!(16&C),a=15&C;if(a+1>be)throw new Error("BinaryCMapReader.process: Invalid dataSize.");const B=1,h=i.readNumber();switch(A){case 0:i.readHex(n,a),i.readHexNumber(g,a),we(g,n,a),e.addCodespaceRange(a+1,me(n,a),me(g,a));for(let A=1;Aa&&(i=a)}else{for(;!this.eof;)this.readBlock(e);i=this.bufferLength}return this.pos=i,this.buffer.subarray(t,i)}async getImageData(A,e=null){if(!this.canAsyncDecodeImageFromBuffer)return this.getBytes(A,e);const t=await this.stream.asyncGetBytes();return this.decodeImage(t,e)}reset(){this.pos=0}makeSubStream(A,e,t=null){if(void 0===e)for(;!this.eof;)this.readBlock();else{const t=A+e;for(;this.bufferLength<=t&&!this.eof;)this.readBlock()}return new ne(this.buffer,A,e,t)}getBaseStreams(){return this.str?this.str.getBaseStreams():null}}class Ge extends Re{constructor(A,e=null){let t=0;for(const e of A)t+=e instanceof Re?e._rawMinBufferLength:e.length;super(t),this.streams=A,this._onError=e}readBlock(){const A=this.streams;if(0===A.length)return void(this.eof=!0);const e=A.shift();let t;try{t=e.getBytes()}catch(A){if(this._onError)return void this._onError(A,e.dict?.objId);throw A}const i=this.bufferLength,a=i+t.length;this.ensureBuffer(a).set(t,i),this.bufferLength=a}getBaseStreams(){const A=[];for(const e of this.streams){const t=e.getBaseStreams();t&&A.push(...t)}return A.length>0?A:null}}class Ne extends Re{constructor(A,e){e&&(e*=.8),super(e),this.str=A,this.dict=A.dict,this.input=new Uint8Array(5)}readBlock(){const A=this.str;let e=A.getByte();for(;JA(e);)e=A.getByte();if(-1===e||126===e)return void(this.eof=!0);const t=this.bufferLength;let i,a;if(122===e){for(i=this.ensureBuffer(t+4),a=0;a<4;++a)i[t+a]=0;this.bufferLength+=4}else{const s=this.input;for(s[0]=e,a=1;a<5;++a){for(e=A.getByte();JA(e);)e=A.getByte();if(s[a]=e,-1===e||126===e)break}if(i=this.ensureBuffer(t+a-1),this.bufferLength+=a-1,a<5){for(;a<5;++a)s[a]=117;this.eof=!0}let n=0;for(a=0;a<5;++a)n=85*n+(s[a]-33);for(a=3;a>=0;--a)i[t+a]=255&n,n>>=8}}}class xe extends Re{constructor(A,e){e&&(e*=.5),super(e),this.str=A,this.dict=A.dict,this.firstDigit=-1}readBlock(){const A=this.str.getBytes(8e3);if(!A.length)return void(this.eof=!0);const e=A.length+1>>1,t=this.ensureBuffer(this.bufferLength+e);let i=this.bufferLength,a=this.firstDigit;for(const e of A){let A;if(e>=48&&e<=57)A=15&e;else{if(!(e>=65&&e<=70||e>=97&&e<=102)){if(62===e){this.eof=!0;break}continue}A=9+(15&e)}a<0?a=A:(t[i++]=a<<4|A,a=-1)}a>=0&&this.eof&&(t[i++]=a<<4,a=-1),this.firstDigit=a,this.bufferLength=i}}const Ue=-1,Me=[[-1,-1],[-1,-1],[7,8],[7,7],[6,6],[6,6],[6,5],[6,5],[4,0],[4,0],[4,0],[4,0],[4,0],[4,0],[4,0],[4,0],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2]],Le=[[-1,-1],[12,-2],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[11,1792],[11,1792],[12,1984],[12,2048],[12,2112],[12,2176],[12,2240],[12,2304],[11,1856],[11,1856],[11,1920],[11,1920],[12,2368],[12,2432],[12,2496],[12,2560]],Je=[[-1,-1],[-1,-1],[-1,-1],[-1,-1],[8,29],[8,29],[8,30],[8,30],[8,45],[8,45],[8,46],[8,46],[7,22],[7,22],[7,22],[7,22],[7,23],[7,23],[7,23],[7,23],[8,47],[8,47],[8,48],[8,48],[6,13],[6,13],[6,13],[6,13],[6,13],[6,13],[6,13],[6,13],[7,20],[7,20],[7,20],[7,20],[8,33],[8,33],[8,34],[8,34],[8,35],[8,35],[8,36],[8,36],[8,37],[8,37],[8,38],[8,38],[7,19],[7,19],[7,19],[7,19],[8,31],[8,31],[8,32],[8,32],[6,1],[6,1],[6,1],[6,1],[6,1],[6,1],[6,1],[6,1],[6,12],[6,12],[6,12],[6,12],[6,12],[6,12],[6,12],[6,12],[8,53],[8,53],[8,54],[8,54],[7,26],[7,26],[7,26],[7,26],[8,39],[8,39],[8,40],[8,40],[8,41],[8,41],[8,42],[8,42],[8,43],[8,43],[8,44],[8,44],[7,21],[7,21],[7,21],[7,21],[7,28],[7,28],[7,28],[7,28],[8,61],[8,61],[8,62],[8,62],[8,63],[8,63],[8,0],[8,0],[8,320],[8,320],[8,384],[8,384],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[7,27],[7,27],[7,27],[7,27],[8,59],[8,59],[8,60],[8,60],[9,1472],[9,1536],[9,1600],[9,1728],[7,18],[7,18],[7,18],[7,18],[7,24],[7,24],[7,24],[7,24],[8,49],[8,49],[8,50],[8,50],[8,51],[8,51],[8,52],[8,52],[7,25],[7,25],[7,25],[7,25],[8,55],[8,55],[8,56],[8,56],[8,57],[8,57],[8,58],[8,58],[6,192],[6,192],[6,192],[6,192],[6,192],[6,192],[6,192],[6,192],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[8,448],[8,448],[8,512],[8,512],[9,704],[9,768],[8,640],[8,640],[8,576],[8,576],[9,832],[9,896],[9,960],[9,1024],[9,1088],[9,1152],[9,1216],[9,1280],[9,1344],[9,1408],[7,256],[7,256],[7,256],[7,256],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[6,16],[6,16],[6,16],[6,16],[6,16],[6,16],[6,16],[6,16],[6,17],[6,17],[6,17],[6,17],[6,17],[6,17],[6,17],[6,17],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[6,14],[6,14],[6,14],[6,14],[6,14],[6,14],[6,14],[6,14],[6,15],[6,15],[6,15],[6,15],[6,15],[6,15],[6,15],[6,15],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7]],He=[[-1,-1],[-1,-1],[12,-2],[12,-2],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[11,1792],[11,1792],[11,1792],[11,1792],[12,1984],[12,1984],[12,2048],[12,2048],[12,2112],[12,2112],[12,2176],[12,2176],[12,2240],[12,2240],[12,2304],[12,2304],[11,1856],[11,1856],[11,1856],[11,1856],[11,1920],[11,1920],[11,1920],[11,1920],[12,2368],[12,2368],[12,2432],[12,2432],[12,2496],[12,2496],[12,2560],[12,2560],[10,18],[10,18],[10,18],[10,18],[10,18],[10,18],[10,18],[10,18],[12,52],[12,52],[13,640],[13,704],[13,768],[13,832],[12,55],[12,55],[12,56],[12,56],[13,1280],[13,1344],[13,1408],[13,1472],[12,59],[12,59],[12,60],[12,60],[13,1536],[13,1600],[11,24],[11,24],[11,24],[11,24],[11,25],[11,25],[11,25],[11,25],[13,1664],[13,1728],[12,320],[12,320],[12,384],[12,384],[12,448],[12,448],[13,512],[13,576],[12,53],[12,53],[12,54],[12,54],[13,896],[13,960],[13,1024],[13,1088],[13,1152],[13,1216],[10,64],[10,64],[10,64],[10,64],[10,64],[10,64],[10,64],[10,64]],Ye=[[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[11,23],[11,23],[12,50],[12,51],[12,44],[12,45],[12,46],[12,47],[12,57],[12,58],[12,61],[12,256],[10,16],[10,16],[10,16],[10,16],[10,17],[10,17],[10,17],[10,17],[12,48],[12,49],[12,62],[12,63],[12,30],[12,31],[12,32],[12,33],[12,40],[12,41],[11,22],[11,22],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[9,15],[9,15],[9,15],[9,15],[9,15],[9,15],[9,15],[9,15],[12,128],[12,192],[12,26],[12,27],[12,28],[12,29],[11,19],[11,19],[11,20],[11,20],[12,34],[12,35],[12,36],[12,37],[12,38],[12,39],[11,21],[11,21],[12,42],[12,43],[10,0],[10,0],[10,0],[10,0],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12]],ve=[[-1,-1],[-1,-1],[-1,-1],[-1,-1],[6,9],[6,8],[5,7],[5,7],[4,6],[4,6],[4,6],[4,6],[4,5],[4,5],[4,5],[4,5],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2]];class Ke{constructor(A,e={}){if(!A||"function"!=typeof A.next)throw new Error('CCITTFaxDecoder - invalid "source" parameter.');let t;for(this.source=A,this.eof=!1,this.encoding=e.K||0,this.eoline=e.EndOfLine||!1,this.byteAlign=e.EncodedByteAlign||!1,this.columns=e.Columns||1728,this.rows=e.Rows||0,this.eoblock=e.EndOfBlock??!0,this.black=e.BlackIs1||!1,this.codingLine=new Uint32Array(this.columns+1),this.refLine=new Uint32Array(this.columns+2),this.codingLine[0]=this.columns,this.codingPos=0,this.row=0,this.nextLine2D=this.encoding<0,this.inputBits=0,this.inputBuf=0,this.outputBits=0,this.rowsDone=!1;0===(t=this._lookBits(12));)this._eatBits(1);1===t&&this._eatBits(12),this.encoding>0&&(this.nextLine2D=!this._lookBits(1),this._eatBits(1))}readNextChar(){if(this.eof)return-1;const A=this.refLine,e=this.codingLine,t=this.columns;let i,a,s,n,g;if(0===this.outputBits){if(this.rowsDone&&(this.eof=!0),this.eof)return-1;let s,g,r;if(this.err=!1,this.nextLine2D){for(n=0;e[n]=64);do{g+=r=this._getWhiteCode()}while(r>=64)}else{do{s+=r=this._getWhiteCode()}while(r>=64);do{g+=r=this._getBlackCode()}while(r>=64)}for(this._addPixels(e[this.codingPos]+s,a),e[this.codingPos]0?--i:++i;A[i]<=e[this.codingPos]&&A[i]0?--i:++i;A[i]<=e[this.codingPos]&&A[i]0?--i:++i;A[i]<=e[this.codingPos]&&A[i]=64);else do{s+=r=this._getWhiteCode()}while(r>=64);this._addPixels(e[this.codingPos]+s,a),a^=1}let o=!1;if(this.byteAlign&&(this.inputBits&=-8),this.eoblock||this.row!==this.rows-1){if(s=this._lookBits(12),this.eoline)for(;s!==Ue&&1!==s;)this._eatBits(1),s=this._lookBits(12);else for(;0===s;)this._eatBits(1),s=this._lookBits(12);1===s?(this._eatBits(12),o=!0):s===Ue&&(this.eof=!0)}else this.rowsDone=!0;if(!this.eof&&this.encoding>0&&!this.rowsDone&&(this.nextLine2D=!this._lookBits(1),this._eatBits(1)),this.eoblock&&o&&this.byteAlign){if(s=this._lookBits(12),1===s){if(this._eatBits(12),this.encoding>0&&(this._lookBits(1),this._eatBits(1)),this.encoding>=0)for(n=0;n<4;++n)s=this._lookBits(12),1!==s&&G("bad rtc code: "+s),this._eatBits(12),this.encoding>0&&(this._lookBits(1),this._eatBits(1));this.eof=!0}}else if(this.err&&this.eoline){for(;;){if(s=this._lookBits(13),s===Ue)return this.eof=!0,-1;if(s>>1==1)break;this._eatBits(1)}this._eatBits(12),this.encoding>0&&(this._eatBits(1),this.nextLine2D=!(1&s))}this.outputBits=e[0]>0?e[this.codingPos=0]:e[this.codingPos=1],this.row++}if(this.outputBits>=8)g=1&this.codingPos?0:255,this.outputBits-=8,0===this.outputBits&&e[this.codingPos]s?(g<<=s,1&this.codingPos||(g|=255>>8-s),this.outputBits-=s,s=0):(g<<=this.outputBits,1&this.codingPos||(g|=255>>8-this.outputBits),s-=this.outputBits,this.outputBits=0,e[this.codingPos]0&&(g<<=s,s=0))}while(s)}return this.black&&(g^=255),g}_addPixels(A,e){const t=this.codingLine;let i=this.codingPos;A>t[i]&&(A>this.columns&&(G("row is wrong length"),this.err=!0,A=this.columns),1&i^e&&++i,t[i]=A),this.codingPos=i}_addPixelsNeg(A,e){const t=this.codingLine;let i=this.codingPos;if(A>t[i])A>this.columns&&(G("row is wrong length"),this.err=!0,A=this.columns),1&i^e&&++i,t[i]=A;else if(A0&&A=a){const e=t[A-a];if(e[0]===i)return this._eatBits(i),[!0,e[1],!0]}}return[!1,0,!1]}_getTwoDimCode(){let A,e=0;if(this.eoblock){if(e=this._lookBits(7),A=Me[e],A?.[0]>0)return this._eatBits(A[0]),A[1]}else{const A=this._findTableCode(1,7,Me);if(A[0]&&A[2])return A[1]}return G("Bad two dim code"),Ue}_getWhiteCode(){let A,e=0;if(this.eoblock){if(e=this._lookBits(12),e===Ue)return 1;if(A=e>>5?Je[e>>3]:Le[e],A[0]>0)return this._eatBits(A[0]),A[1]}else{let A=this._findTableCode(1,9,Je);if(A[0])return A[1];if(A=this._findTableCode(11,12,Le),A[0])return A[1]}return G("bad white code"),this._eatBits(1),1}_getBlackCode(){let A,e;if(this.eoblock){if(A=this._lookBits(13),A===Ue)return 1;if(e=A>>7?!(A>>9)&&A>>7?Ye[(A>>1)-64]:ve[A>>7]:He[A],e[0]>0)return this._eatBits(e[0]),e[1]}else{let A=this._findTableCode(2,6,ve);if(A[0])return A[1];if(A=this._findTableCode(7,12,Ye,64),A[0])return A[1];if(A=this._findTableCode(10,13,He),A[0])return A[1]}return G("bad black code"),this._eatBits(1),1}_lookBits(A){let e;for(;this.inputBits>16-A;this.inputBuf=this.inputBuf<<8|e,this.inputBits+=8}return this.inputBuf>>this.inputBits-A&65535>>16-A}_eatBits(A){(this.inputBits-=A)<0&&(this.inputBits=0)}}class qe extends Re{constructor(A,e,t){super(e),this.str=A,this.dict=A.dict,t instanceof hA||(t=hA.empty);const i={next:()=>A.getByte()};this.ccittFaxDecoder=new Ke(i,{K:t.get("K"),EndOfLine:t.get("EndOfLine"),EncodedByteAlign:t.get("EncodedByteAlign"),Columns:t.get("Columns"),Rows:t.get("Rows"),EndOfBlock:t.get("EndOfBlock"),BlackIs1:t.get("BlackIs1")})}readBlock(){for(;!this.eof;){const A=this.ccittFaxDecoder.readNextChar();if(-1===A)return void(this.eof=!0);this.ensureBuffer(this.bufferLength+1),this.buffer[this.bufferLength++]=A}}}const Te=new Int32Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Pe=new Int32Array([3,4,5,6,7,8,9,10,65547,65549,65551,65553,131091,131095,131099,131103,196643,196651,196659,196667,262211,262227,262243,262259,327811,327843,327875,327907,258,258,258]),We=new Int32Array([1,2,3,4,65541,65543,131081,131085,196625,196633,262177,262193,327745,327777,393345,393409,459009,459137,524801,525057,590849,591361,657409,658433,724993,727041,794625,798721,868353,876545]),Ze=[new Int32Array([459008,524368,524304,524568,459024,524400,524336,590016,459016,524384,524320,589984,524288,524416,524352,590048,459012,524376,524312,589968,459028,524408,524344,590032,459020,524392,524328,59e4,524296,524424,524360,590064,459010,524372,524308,524572,459026,524404,524340,590024,459018,524388,524324,589992,524292,524420,524356,590056,459014,524380,524316,589976,459030,524412,524348,590040,459022,524396,524332,590008,524300,524428,524364,590072,459009,524370,524306,524570,459025,524402,524338,590020,459017,524386,524322,589988,524290,524418,524354,590052,459013,524378,524314,589972,459029,524410,524346,590036,459021,524394,524330,590004,524298,524426,524362,590068,459011,524374,524310,524574,459027,524406,524342,590028,459019,524390,524326,589996,524294,524422,524358,590060,459015,524382,524318,589980,459031,524414,524350,590044,459023,524398,524334,590012,524302,524430,524366,590076,459008,524369,524305,524569,459024,524401,524337,590018,459016,524385,524321,589986,524289,524417,524353,590050,459012,524377,524313,589970,459028,524409,524345,590034,459020,524393,524329,590002,524297,524425,524361,590066,459010,524373,524309,524573,459026,524405,524341,590026,459018,524389,524325,589994,524293,524421,524357,590058,459014,524381,524317,589978,459030,524413,524349,590042,459022,524397,524333,590010,524301,524429,524365,590074,459009,524371,524307,524571,459025,524403,524339,590022,459017,524387,524323,589990,524291,524419,524355,590054,459013,524379,524315,589974,459029,524411,524347,590038,459021,524395,524331,590006,524299,524427,524363,590070,459011,524375,524311,524575,459027,524407,524343,590030,459019,524391,524327,589998,524295,524423,524359,590062,459015,524383,524319,589982,459031,524415,524351,590046,459023,524399,524335,590014,524303,524431,524367,590078,459008,524368,524304,524568,459024,524400,524336,590017,459016,524384,524320,589985,524288,524416,524352,590049,459012,524376,524312,589969,459028,524408,524344,590033,459020,524392,524328,590001,524296,524424,524360,590065,459010,524372,524308,524572,459026,524404,524340,590025,459018,524388,524324,589993,524292,524420,524356,590057,459014,524380,524316,589977,459030,524412,524348,590041,459022,524396,524332,590009,524300,524428,524364,590073,459009,524370,524306,524570,459025,524402,524338,590021,459017,524386,524322,589989,524290,524418,524354,590053,459013,524378,524314,589973,459029,524410,524346,590037,459021,524394,524330,590005,524298,524426,524362,590069,459011,524374,524310,524574,459027,524406,524342,590029,459019,524390,524326,589997,524294,524422,524358,590061,459015,524382,524318,589981,459031,524414,524350,590045,459023,524398,524334,590013,524302,524430,524366,590077,459008,524369,524305,524569,459024,524401,524337,590019,459016,524385,524321,589987,524289,524417,524353,590051,459012,524377,524313,589971,459028,524409,524345,590035,459020,524393,524329,590003,524297,524425,524361,590067,459010,524373,524309,524573,459026,524405,524341,590027,459018,524389,524325,589995,524293,524421,524357,590059,459014,524381,524317,589979,459030,524413,524349,590043,459022,524397,524333,590011,524301,524429,524365,590075,459009,524371,524307,524571,459025,524403,524339,590023,459017,524387,524323,589991,524291,524419,524355,590055,459013,524379,524315,589975,459029,524411,524347,590039,459021,524395,524331,590007,524299,524427,524363,590071,459011,524375,524311,524575,459027,524407,524343,590031,459019,524391,524327,589999,524295,524423,524359,590063,459015,524383,524319,589983,459031,524415,524351,590047,459023,524399,524335,590015,524303,524431,524367,590079]),9],Oe=[new Int32Array([327680,327696,327688,327704,327684,327700,327692,327708,327682,327698,327690,327706,327686,327702,327694,0,327681,327697,327689,327705,327685,327701,327693,327709,327683,327699,327691,327707,327687,327703,327695,0]),5];class Xe extends Re{constructor(A,e){super(e),this.str=A,this.dict=A.dict;const t=A.getByte(),i=A.getByte();if(-1===t||-1===i)throw new T(`Invalid header in flate stream: ${t}, ${i}`);if(8!=(15&t))throw new T(`Unknown compression method in flate stream: ${t}, ${i}`);if(((t<<8)+i)%31!=0)throw new T(`Bad FCHECK in flate stream: ${t}, ${i}`);if(32&i)throw new T(`FDICT bit set in flate stream: ${t}, ${i}`);this.codeSize=0,this.codeBuf=0}async getImageData(A,e){const t=await this.asyncGetBytes();return t?.subarray(0,A)||this.getBytes(A)}async asyncGetBytes(){this.str.reset();const A=this.str.getBytes();try{const{readable:e,writable:t}=new DecompressionStream("deflate"),i=t.getWriter();i.write(A),i.close();const a=[];let s=0;for await(const A of e)a.push(A),s+=A.byteLength;const n=new Uint8Array(s);let g=0;for(const A of a)n.set(A,g),g+=A.byteLength;return n}catch{return this.str=new ne(A,2,A.length,this.str.dict),this.reset(),null}}get isAsync(){return!0}getBits(A){const e=this.str;let t,i=this.codeSize,a=this.codeBuf;for(;i>A,this.codeSize=i-=A,t}getCode(A){const e=this.str,t=A[0],i=A[1];let a,s=this.codeSize,n=this.codeBuf;for(;s>16,o=65535&g;if(r<1||s>r,this.codeSize=s-r,o}generateHuffmanTable(A){const e=A.length;let t,i=0;for(t=0;ti&&(i=A[t]);const a=1<>=1;for(t=A;t>=1,0===e){let e;if(-1===(e=i.getByte()))return void this.#m("Bad block header in flate stream");let t=e;if(-1===(e=i.getByte()))return void this.#m("Bad block header in flate stream");if(t|=e<<8,-1===(e=i.getByte()))return void this.#m("Bad block header in flate stream");let a=e;if(-1===(e=i.getByte()))return void this.#m("Bad block header in flate stream");if(a|=e<<8,a!==(65535&~t)&&(0!==t||0!==a))throw new T("Bad uncompressed block length in flate stream");this.codeBuf=0,this.codeSize=0;const s=this.bufferLength,n=s+t;if(A=this.ensureBuffer(n),this.bufferLength=n,0===t)-1===i.peekByte()&&(this.eof=!0);else{const e=i.getBytes(t);A.set(e,s),e.length0;)I[g++]=B}a=this.generateHuffmanTable(I.subarray(0,A)),s=this.generateHuffmanTable(I.subarray(A,o))}}A=this.buffer;let n=A?A.length:0,g=this.bufferLength;for(;;){let e=this.getCode(a);if(e<256){g+1>=n&&(A=this.ensureBuffer(g+1),n=A.length),A[g++]=e;continue}if(256===e)return void(this.bufferLength=g);e-=257,e=Pe[e];let i=e>>16;i>0&&(i=this.getBits(i)),t=(65535&e)+i,e=this.getCode(s),e=We[e],i=e>>16,i>0&&(i=this.getBits(i));const r=(65535&e)+i;g+t>=n&&(A=this.ensureBuffer(g+t),n=A.length);for(let e=0;e>9&127,this.clow=this.clow<<7&65535,this.ct-=7,this.a=32768}byteIn(){const A=this.data;let e=this.bp;255===A[e]?A[e+1]>143?(this.clow+=65280,this.ct=8):(e++,this.clow+=A[e]<<9,this.ct=7,this.bp=e):(e++,this.clow+=e65535&&(this.chigh+=this.clow>>16,this.clow&=65535)}readBit(A,e){let t=A[e]>>1,i=1&A[e];const a=Ve[t],s=a.qe;let n,g=this.a-s;if(this.chigh>15&1,this.clow=this.clow<<1&65535,this.ct--}while(!(32768&g));return this.a=g,A[e]=t<<1|i,n}}class ze extends J{constructor(A){super(A,"Jbig2Error")}}class _e{getContexts(A){return A in this?this[A]:this[A]=new Int8Array(65536)}}class $e{constructor(A,e,t){this.data=A,this.start=e,this.end=t}get decoder(){return L(this,"decoder",new je(this.data,this.start,this.end))}get contextCache(){return L(this,"contextCache",new _e)}}const At=2**31-1,et=-(2**31);function tt(A,e,t){const i=A.getContexts(e);let a=1;function s(A){let e=0;for(let s=0;s>>0}const n=s(1),g=s(1)?s(1)?s(1)?s(1)?s(1)?s(32)+4436:s(12)+340:s(8)+84:s(6)+20:s(4)+4:s(2);let r;return 0===n?r=g:g>0&&(r=-g),r>=et&&r<=At?r:null}function it(A,e,t){const i=A.getContexts("IAID");let a=1;for(let A=0;A=w&&N=D)for(H=H<<1&l,Q=0;Q=0&&U=0&&(M=S[x][U],M&&(H|=M<=A?o<<=1:o=o<<1|p[g][r];for(B=0;B=d||r<0||r>=u?o<<=1:o=o<<1|i[g][r];const h=m.readBit(y,o);e[n]=h}}return p}function ct(A,e,t,i,a,s,n,g,r,o,I,c,C,B,h,Q,l,E,u){if(A&&e)throw new ze("refinement with Huffman is not supported");const d=[];let f,p;for(f=0;f1&&(a=A?u.readBits(E):tt(y,"IAIT",m));const s=n*w+a,D=A?B.symbolIDTable.decode(u):it(y,m,r),b=e&&(A?u.readBit():tt(y,"IARI",m));let k=g[D],F=k[0].length,S=k.length;if(b){const A=tt(y,"IARDW",m),e=tt(y,"IARDH",m);F+=A,S+=e,k=It(F,S,h,k,(A>>1)+tt(y,"IARDX",m),(e>>1)+tt(y,"IARDY",m),!1,Q,l)}let R=0;o?1&c?R=S-1:i+=S-1:c>1?i+=F-1:R=F-1;const G=s-(1&c?0:S-1),N=i-(2&c?F-1:0);let x,U,M;if(o)for(x=0;x>5&7;const r=[31&n];let o=e+6;if(7===n){g=536870911&LA(A,o-1),o+=3;let e=g+7>>3;for(r[0]=A[o++];--e>0;)r.push(A[o++])}else if(5===n||6===n)throw new ze("invalid referred-to flags");t.retainBits=r;let I=4;t.number<=256?I=1:t.number<=65536&&(I=2);const c=[];let C,B;for(C=0;C>>24&255,s[3]=e.height>>16&255,s[4]=e.height>>8&255,s[5]=255&e.height,C=o,B=A.length;C>2&3,A.huffmanDWSelector=e>>4&3,A.bitmapSizeSelector=e>>6&1,A.aggregationInstancesSelector=e>>7&1,A.bitmapCodingContextUsed=!!(256&e),A.bitmapCodingContextRetained=!!(512&e),A.template=e>>10&3,A.refinementTemplate=e>>12&1,o+=2,!A.huffman){for(r=0===A.template?4:1,n=[],g=0;g>2&3,I.stripSize=1<>4&3,I.transposed=!!(64&c),I.combinationOperator=c>>7&3,I.defaultPixelValue=c>>9&1,I.dsOffset=c<<17>>27,I.refinementTemplate=c>>15&1,I.huffman){const A=MA(i,o);o+=2,I.huffmanFS=3&A,I.huffmanDS=A>>2&3,I.huffmanDT=A>>4&3,I.huffmanRefinementDW=A>>6&3,I.huffmanRefinementDH=A>>8&3,I.huffmanRefinementDX=A>>10&3,I.huffmanRefinementDY=A>>12&3,I.huffmanRefinementSizeSelector=!!(16384&A)}if(I.refinement&&!I.refinementTemplate){for(n=[],g=0;g<2;g++)n.push({x:UA(i,o),y:UA(i,o+1)}),o+=2;I.refinementAt=n}I.numberOfSymbolInstances=LA(i,o),o+=4,s=[I,t.referredTo,i,o,a];break;case 16:const C={},B=i[o++];C.mmr=!!(1&B),C.template=B>>1&3,C.patternWidth=i[o++],C.patternHeight=i[o++],C.maxPatternIndex=LA(i,o),o+=4,s=[C,t.number,i,o,a];break;case 22:case 23:const h={};h.info=ht(i,o),o+=Qt;const Q=i[o++];h.mmr=!!(1&Q),h.template=Q>>1&3,h.enableSkip=!!(8&Q),h.combinationOperator=Q>>4&7,h.defaultPixelValue=Q>>7&1,h.gridWidth=LA(i,o),o+=4,h.gridHeight=LA(i,o),o+=4,h.gridOffsetX=4294967295&LA(i,o),o+=4,h.gridOffsetY=4294967295&LA(i,o),o+=4,h.gridVectorX=MA(i,o),o+=2,h.gridVectorY=MA(i,o),o+=2,s=[h,t.referredTo,i,o,a];break;case 38:case 39:const l={};l.info=ht(i,o),o+=Qt;const E=i[o++];if(l.mmr=!!(1&E),l.template=E>>1&3,l.prediction=!!(8&E),!l.mmr){for(r=0===l.template?4:1,n=[],g=0;g>2&1,u.combinationOperator=d>>3&3,u.requiresBuffer=!!(32&d),u.combinationOperatorOverride=!!(64&d),s=[u];break;case 49:case 50:case 51:case 62:break;case 53:s=[t.number,i,o,a];break;default:throw new ze(`segment type ${t.typeName}(${t.type}) is not implemented`)}const I="on"+t.typeName;I in e&&e[I].apply(e,s)}function Et(A,e){for(let t=0,i=A.length;t>3,t=new Uint8ClampedArray(e*A.height);A.defaultPixelValue&&t.fill(255),this.buffer=t}drawBitmap(A,e){const t=this.currentPageInfo,i=A.width,a=A.height,s=t.width+7>>3,n=t.combinationOperatorOverride?A.combinationOperator:t.combinationOperator,g=this.buffer,r=128>>(7&A.x);let o,I,c,C,B=A.y*s+(A.x>>3);switch(n){case 0:for(o=0;o>=1,c||(c=128,C++);B+=s}break;case 2:for(o=0;o>=1,c||(c=128,C++);B+=s}break;default:throw new ze(`operator ${n} is not supported`)}}onImmediateGenericRegion(A,e,t,i){const a=A.info,s=new $e(e,t,i),n=ot(A.mmr,a.width,a.height,A.template,A.prediction,null,A.at,s);this.drawBitmap(a,n)}onImmediateLosslessGenericRegion(){this.onImmediateGenericRegion(...arguments)}onSymbolDictionary(A,e,t,i,a,s){let n,g;A.huffman&&(n=function(A,e,t){let i,a,s,n,g=0;switch(A.huffmanDHSelector){case 0:case 1:i=yt(A.huffmanDHSelector+4);break;case 3:i=Dt(g,e,t),g++;break;default:throw new ze("invalid Huffman DH selector")}switch(A.huffmanDWSelector){case 0:case 1:a=yt(A.huffmanDWSelector+2);break;case 3:a=Dt(g,e,t),g++;break;default:throw new ze("invalid Huffman DW selector")}return A.bitmapSizeSelector?(s=Dt(g,e,t),g++):s=yt(1),n=A.aggregationInstancesSelector?Dt(g,e,t):yt(1),{tableDeltaHeight:i,tableDeltaWidth:a,tableBitmapSize:s,tableAggregateInstances:n}}(A,t,this.customTables),g=new wt(i,a,s));let r=this.symbols;r||(this.symbols=r={});const o=[];for(const A of t){const e=r[A];e&&o.push(...e)}const I=new $e(i,a,s);r[e]=function(A,e,t,i,a,s,n,g,r,o,I,c){if(A&&e)throw new ze("symbol refinement with Huffman is not supported");const C=[];let B=0,h=xA(t.length+i);const Q=I.decoder,l=I.contextCache;let E,u;for(A&&(E=yt(1),u=[],h=Math.max(h,1));C.length1)d=ct(A,e,i,B,0,a,1,t.concat(C),h,0,0,1,0,s,r,o,I,0,c);else{const A=it(l,Q,h),e=tt(l,"IARDX",Q),a=tt(l,"IARDY",Q);d=It(i,B,r,A=32){let t,i,n;switch(e){case 32:if(0===A)throw new ze("no previous value in symbol ID table");i=a.readBits(2)+3,t=s[A-1].prefixLength;break;case 33:i=a.readBits(3)+3,t=0;break;case 34:i=a.readBits(7)+11,t=0;break;default:throw new ze("invalid code length in symbol ID table")}for(n=0;n=0;l--)k=A?kt(b,r,o,!0):ot(!1,r,o,t,!1,null,w,h),D[l]=k;for(F=0;F=0;E--)R^=D[E][F][S],G|=R<>8,U=c+F*C-S*B>>8,x>=0&&x+p<=i&&U>=0&&U+m<=a)for(l=0;l=a))for(L=Q[e],M=N[l],E=0;E=0&&A>1&7),r=1+(i>>4&7),o=[];let I,c,C=a;do{I=n.readBits(g),c=n.readBits(r),o.push(new dt([C,I,c,0])),C+=1<>e&1;if(e<=0)this.children[t]=new ft(A);else{let i=this.children[t];i||(this.children[t]=i=new ft(null)),i.buildTree(A,e-1)}}decodeNode(A){if(this.isLeaf){if(this.isOOB)return null;const e=A.readBits(this.rangeLength);return this.rangeLow+(this.isLowerRange?-e:e)}const e=this.children[A.readBit()];if(!e)throw new ze("invalid Huffman data");return e.decodeNode(A)}}class pt{constructor(A,e){e||this.assignPrefixCodes(A),this.rootNode=new ft(null);for(let e=0,t=A.length;e0&&this.rootNode.buildTree(t,t.prefixLength-1)}}decode(A){return this.rootNode.decodeNode(A)}assignPrefixCodes(A){const e=A.length;let t=0;for(let i=0;i=this.end)throw new ze("end of data while reading bit");this.currentByte=this.data[this.position++],this.shift=7}const A=this.currentByte>>this.shift&1;return this.shift--,A}readBits(A){let e,t=0;for(e=A-1;e>=0;e--)t|=this.readBit()<=this.end?-1:this.data[this.position++]}}function Dt(A,e,t){let i=0;for(let a=0,s=e.length;a>t&1,t--}if(i&&!g){const A=5;for(let e=0;e>3,c=7&i,C=A.length;t=new Uint32Array(t.buffer);let B=0;for(let i=0;i0&&!A[s-1];)s--;const n=[{children:[],index:0}];let g,r=n[0];for(t=0;t0;)r=n.pop();for(r.index++,n.push(r);n.length<=t;)n.push(g={children:[],index:0}),r.children[r.index]=g.children,r=g;a++}t+10)return h--,B>>h&1;if(B=A[e++],255===B){const i=A[e++];if(i){if(220===i&&o){const i=MA(A,e+=2);if(e+=2,i>0&&i!==t.scanLines)throw new Nt("Found DNL marker (0xFFDC) while parsing scan data",i)}else if(217===i){if(o){const A=m*(8===t.precision?8:0);if(A>0&&Math.round(t.scanLines/A)>=5)throw new Nt("Found EOI marker (0xFFD9) while parsing scan data, possibly caused by incorrect `scanLines` parameter",A)}throw new xt("Found EOI marker (0xFFD9) while parsing scan data")}throw new Gt(`unexpected marker ${(B<<8|i).toString(16)}`)}}return h=7,B>>>7}function l(A){let e=A;for(;;){switch(e=e[Q()],typeof e){case"number":return e;case"object":continue}throw new Gt("invalid huffman sequence")}}function E(A){let e=0;for(;A>0;)e=e<<1|Q(),A--;return e}function u(A){if(1===A)return 1===Q()?1:-1;const e=E(A);return e>=1<0)return void f--;let t=s;const i=n;for(;t<=i;){const i=l(A.huffmanTableAC),a=15&i,s=i>>4;if(0===a){if(s<15){f=E(s)+(1<>4,0===a)o<15?(f=E(o)+(1<>4;if(0===i){if(s<15)break;a+=16;continue}a+=s;const n=Ut[a];A.blockData[e+n]=u(i),a++}};let x,U=0;const M=1===D?i[0].blocksPerLine*i[0].blocksPerColumn:I*t.mcusPerColumn;let L,J;for(;U<=M;){const t=a?Math.min(M-U,a):M;if(t>0){for(k=0;k0?"unexpected":"excessive"} MCU data, current marker is: ${x.invalid}`),e=x.offset),!(x.marker>=65488&&x.marker<=65495))break;e+=2}return e-C}function Zt(A,e,t){const i=A.quantizationTable,a=A.blockData;let s,n,g,r,o,I,c,C,B,h,Q,l,E,u,d,f,p;if(!i)throw new Gt("missing required Quantization Table.");for(let A=0;A<64;A+=8)B=a[e+A],h=a[e+A+1],Q=a[e+A+2],l=a[e+A+3],E=a[e+A+4],u=a[e+A+5],d=a[e+A+6],f=a[e+A+7],B*=i[A],h|Q|l|E|u|d|f?(h*=i[A+1],Q*=i[A+2],l*=i[A+3],E*=i[A+4],u*=i[A+5],d*=i[A+6],f*=i[A+7],s=Kt*B+128>>8,n=Kt*E+128>>8,g=Q,r=d,o=qt*(h-f)+128>>8,C=qt*(h+f)+128>>8,I=l<<4,c=u<<4,s=s+n+1>>1,n=s-n,p=g*vt+r*Yt+128>>8,g=g*Yt-r*vt+128>>8,r=p,o=o+c+1>>1,c=o-c,C=C+I+1>>1,I=C-I,s=s+r+1>>1,r=s-r,n=n+g+1>>1,g=n-g,p=o*Ht+C*Jt+2048>>12,o=o*Jt-C*Ht+2048>>12,C=p,p=I*Lt+c*Mt+2048>>12,I=I*Mt-c*Lt+2048>>12,c=p,t[A]=s+C,t[A+7]=s-C,t[A+1]=n+c,t[A+6]=n-c,t[A+2]=g+I,t[A+5]=g-I,t[A+3]=r+o,t[A+4]=r-o):(p=Kt*B+512>>10,t[A]=p,t[A+1]=p,t[A+2]=p,t[A+3]=p,t[A+4]=p,t[A+5]=p,t[A+6]=p,t[A+7]=p);for(let A=0;A<8;++A)B=t[A],h=t[A+8],Q=t[A+16],l=t[A+24],E=t[A+32],u=t[A+40],d=t[A+48],f=t[A+56],h|Q|l|E|u|d|f?(s=Kt*B+2048>>12,n=Kt*E+2048>>12,g=Q,r=d,o=qt*(h-f)+2048>>12,C=qt*(h+f)+2048>>12,I=l,c=u,s=4112+(s+n+1>>1),n=s-n,p=g*vt+r*Yt+2048>>12,g=g*Yt-r*vt+2048>>12,r=p,o=o+c+1>>1,c=o-c,C=C+I+1>>1,I=C-I,s=s+r+1>>1,r=s-r,n=n+g+1>>1,g=n-g,p=o*Ht+C*Jt+2048>>12,o=o*Jt-C*Ht+2048>>12,C=p,p=I*Lt+c*Mt+2048>>12,I=I*Mt-c*Lt+2048>>12,c=p,B=s+C,f=s-C,h=n+c,d=n-c,Q=g+I,u=g-I,l=r+o,E=r-o,B<16?B=0:B>=4080?B=255:B>>=4,h<16?h=0:h>=4080?h=255:h>>=4,Q<16?Q=0:Q>=4080?Q=255:Q>>=4,l<16?l=0:l>=4080?l=255:l>>=4,E<16?E=0:E>=4080?E=255:E>>=4,u<16?u=0:u>=4080?u=255:u>>=4,d<16?d=0:d>=4080?d=255:d>>=4,f<16?f=0:f>=4080?f=255:f>>=4,a[e+A]=B,a[e+A+8]=h,a[e+A+16]=Q,a[e+A+24]=l,a[e+A+32]=E,a[e+A+40]=u,a[e+A+48]=d,a[e+A+56]=f):(p=Kt*B+8192>>14,p=p<-2040?0:p>=2024?255:p+2056>>4,a[e+A]=p,a[e+A+8]=p,a[e+A+16]=p,a[e+A+24]=p,a[e+A+32]=p,a[e+A+40]=p,a[e+A+48]=p,a[e+A+56]=p)}function Ot(A,e){const t=e.blocksPerLine,i=e.blocksPerColumn,a=new Int16Array(64);for(let A=0;A=i)return null;const s=MA(A,e);if(s>=65472&&s<=65534)return{invalid:null,marker:s,offset:e};let n=MA(A,a);for(;!(n>=65472&&n<=65534);){if(++a>=i)return null;n=MA(A,a)}return{invalid:s.toString(16),marker:n,offset:a}}class Vt{constructor({decodeTransform:A=null,colorTransform:e=-1}={}){this._decodeTransform=A,this._colorTransform=e}parse(A,{dnlScanLines:e=null}={}){function t(){const e=MA(A,n);n+=2;let t=n+e-2;const i=Xt(A,t,n);i?.invalid&&(N("readDataBlock - incorrect length, current marker is: "+i.invalid),t=i.offset);const a=A.subarray(n,t);return n+=a.length,a}function i(A){const e=Math.ceil(A.samplesPerLine/8/A.maxH),t=Math.ceil(A.scanLines/8/A.maxV);for(const i of A.components){const a=Math.ceil(Math.ceil(A.samplesPerLine/8)*i.h/A.maxH),s=Math.ceil(Math.ceil(A.scanLines/8)*i.v/A.maxV),n=e*i.h,g=t*i.v*64*(n+1);i.blockData=new Int16Array(g),i.blocksPerLine=a,i.blocksPerColumn=s}A.mcusPerLine=e,A.mcusPerColumn=t}let a,s,n=0,g=null,r=null,o=0;const I=[],c=[],C=[];let B=MA(A,n);if(n+=2,65496!==B)throw new Gt("SOI not found");B=MA(A,n),n+=2;A:for(;65497!==B;){let h,Q,l;switch(B){case 65504:case 65505:case 65506:case 65507:case 65508:case 65509:case 65510:case 65511:case 65512:case 65513:case 65514:case 65515:case 65516:case 65517:case 65518:case 65519:case 65534:const E=t();65504===B&&74===E[0]&&70===E[1]&&73===E[2]&&70===E[3]&&0===E[4]&&(g={version:{major:E[5],minor:E[6]},densityUnits:E[7],xDensity:E[8]<<8|E[9],yDensity:E[10]<<8|E[11],thumbWidth:E[12],thumbHeight:E[13],thumbData:E.subarray(14,14+3*E[12]*E[13])}),65518===B&&65===E[0]&&100===E[1]&&111===E[2]&&98===E[3]&&101===E[4]&&(r={version:E[5]<<8|E[6],flags0:E[7]<<8|E[8],flags1:E[9]<<8|E[10],transformCode:E[11]});break;case 65499:const u=MA(A,n);n+=2;const d=u+n-2;let f;for(;n>4){if(e>>4!=1)throw new Gt("DQT - invalid table spec");for(Q=0;Q<64;Q++)f=Ut[Q],t[f]=MA(A,n),n+=2}else for(Q=0;Q<64;Q++)f=Ut[Q],t[f]=A[n++];I[15&e]=t}break;case 65472:case 65473:case 65474:if(a)throw new Gt("Only single frame JPEGs supported");n+=2,a={},a.extended=65473===B,a.progressive=65474===B,a.precision=A[n++];const p=MA(A,n);n+=2,a.scanLines=e||p,a.samplesPerLine=MA(A,n),n+=2,a.components=[],a.componentIds={};const m=A[n++];let y=0,w=0;for(h=0;h>4,i=15&A[n+1];y>4?c:C)[15&e]=Tt(t,a)}break;case 65501:n+=2,s=MA(A,n),n+=2;break;case 65498:const b=1==++o&&!e;n+=2;const k=A[n++],F=[];for(h=0;h>4],i.huffmanTableAC=c[15&s],F.push(i)}const S=A[n++],R=A[n++],G=A[n++];try{const e=Wt(A,n,a,F,s,S,R,G>>4,15&G,b);n+=e}catch(e){if(e instanceof Nt)return N(`${e.message} -- attempting to re-parse the JPEG image.`),this.parse(A,{dnlScanLines:e.scanLines});if(e instanceof xt){N(`${e.message} -- ignoring the rest of the image data.`);break A}throw e}break;case 65500:n+=4;break;case 65535:255!==A[n]&&n--;break;default:const x=Xt(A,n-2,n-3);if(x?.invalid){N("JpegImage.parse - unexpected data, current marker is: "+x.invalid),n=x.offset;break}if(!x||n>=A.length-1){N("JpegImage.parse - reached the end of the image data without finding an EOI marker (0xFFD9).");break A}throw new Gt("JpegImage.parse - unknown marker: "+B.toString(16))}B=MA(A,n),n+=2}if(!a)throw new Gt("JpegImage.parse - no frame data found.");this.width=a.samplesPerLine,this.height=a.scanLines,this.jfif=g,this.adobe=r,this.components=[];for(const A of a.components){const e=I[A.quantizationId];e&&(A.quantizationTable=e),this.components.push({index:A.index,output:Ot(0,A),scaleX:A.h/a.maxH,scaleY:A.v/a.maxV,blocksPerLine:A.blocksPerLine,blocksPerColumn:A.blocksPerColumn})}this.numComponents=this.components.length}_getLinearizedBlockData(A,e,t=!1){const i=this.width/A,a=this.height/e;let s,n,g,r,o,I,c,C,B,h,Q,l=0;const E=this.components.length,u=A*e*E,d=new Uint8ClampedArray(u),f=new Uint32Array(A),p=4294967288;let m;for(c=0;c>8)+y[B+1];return d}get _isColorConversionNeeded(){return this.adobe?!!this.adobe.transformCode:3===this.numComponents?0!==this._colorTransform&&(82!==this.components[0].index||71!==this.components[1].index||66!==this.components[2].index):1===this._colorTransform}_convertYccToRgb(A){let e,t,i;for(let a=0,s=A.length;a4)throw new Gt("Unsupported color mode");const s=this._getLinearizedBlockData(A,e,a);if(1===this.numComponents&&(t||i)){const A=s.length*(t?4:3),e=new Uint8ClampedArray(A);let i=0;if(t)!function(A,e){if(V.isLittleEndian)for(let t=0,i=A.length;t0&&(A=A.subarray(e));break}const e={decodeTransform:void 0,colorTransform:void 0},t=this.dict.getArray("D","Decode");if((this.forceRGBA||this.forceRGB)&&Array.isArray(t)){const A=this.dict.get("BPC","BitsPerComponent")||8,i=t.length,a=new Int32Array(i);let s=!1;const n=(1<{e=A,t=i})),i.decode=function(A,{numComponents:e=4,isIndexedColormap:t=!1,smaskInData:a=!1}){const s=A.length,n=i._malloc(s);i.HEAPU8.set(A,n);const g=i._jp2_decode(n,s,e>0?e:0,!!t,!!a);if(i._free(n),g){const{errorMessages:A}=i;return A?(delete i.errorMessages,A):"Unknown error"}const{imageData:r}=i;return i.imageData=null,r};var a=Object.assign({},i),s="./this.program",n="";"undefined"!=typeof document&&document.currentScript&&(n=document.currentScript.src),zt&&(n=zt),n=n.startsWith("blob:")?"":n.substr(0,n.replace(/[?#].*/,"").lastIndexOf("/")+1);var g,r,o,I,c,C=i.print||console.log.bind(console),B=i.printErr||console.error.bind(console);function h(){var A=r.buffer;i.HEAP8=o=new Int8Array(A),i.HEAP16=new Int16Array(A),i.HEAPU8=I=new Uint8Array(A),i.HEAPU16=new Uint16Array(A),i.HEAP32=new Int32Array(A),i.HEAPU32=c=new Uint32Array(A),i.HEAPF32=new Float32Array(A),i.HEAPF64=new Float64Array(A)}Object.assign(i,a),a=null,i.arguments&&i.arguments,i.thisProgram&&(s=i.thisProgram),i.quit&&i.quit,i.wasmBinary&&(g=i.wasmBinary);var Q,l=[],E=[],u=[],d=0,f=null,p=null,m="data:application/octet-stream;base64,",y=A=>A.startsWith(m);function w(A,e){var t,i=function(A){if(A==Q&&g)return new Uint8Array(g);var e=function(A){if(y(A))return function(A){for(var e=atob(A),t=new Uint8Array(e.length),i=0;i{for(;A.length>0;)A.shift()(i)};i.noExitRuntime;var b,k=A=>{var e=(A-r.buffer.byteLength+65535)/65536;try{return r.grow(e),h(),1}catch(A){}},F={},S=()=>{if(!S.strings){var A={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:s||"./this.program"};for(var e in F)void 0===F[e]?delete A[e]:A[e]=F[e];var t=[];for(var e in A)t.push(`${e}=${A[e]}`);S.strings=t}return S.strings},R=[null,[],[]],G="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0,N=(A,e,t)=>{for(var i=e+t,a=e;A[a]&&!(a>=i);)++a;if(a-e>16&&A.buffer&&G)return G.decode(A.subarray(e,a));for(var s="";e>10,56320|1023&o)}}else s+=String.fromCharCode((31&n)<<6|g)}else s+=String.fromCharCode(n)}return s},x=(A,e)=>A?N(I,A,e):"",U={c:(A,e,t)=>I.copyWithin(A,e,e+t),g:function(A,e){A>>=2;const t=i.imageData=new Uint8ClampedArray(e),a=i.HEAP32.subarray(A,A+e);t.set(a)},f:function(A,e,t,a){A>>=2,e>>=2,t>>=2;const s=i.imageData=new Uint8ClampedArray(3*a),n=i.HEAP32.subarray(A,A+a),g=i.HEAP32.subarray(e,e+a),r=i.HEAP32.subarray(t,t+a);for(let A=0;A>=2,e>>=2,t>>=2,a>>=2;const n=i.imageData=new Uint8ClampedArray(4*s),g=i.HEAP32.subarray(A,A+s),r=i.HEAP32.subarray(e,e+s),o=i.HEAP32.subarray(t,t+s),I=i.HEAP32.subarray(a,a+s);for(let A=0;A{var e=I.length,t=2147483648;if((A>>>=0)>t)return!1;for(var i,a=1;a<=4;a*=2){var s=e*(1+.2/a);s=Math.min(s,A+100663296);var n=Math.min(t,(i=Math.max(A,s))+(65536-i%65536)%65536);if(k(n))return!0}return!1},l:(A,e)=>{var t=0;return S().forEach(((i,a)=>{var s=e+t;c[A+4*a>>2]=s,((A,e)=>{for(var t=0;t{var t=S();c[A>>2]=t.length;var i=0;return t.forEach((A=>i+=A.length+1)),c[e>>2]=i,0},n:A=>52,j:function(A,e,t,i,a){return 70},b:(A,e,t,i)=>{for(var a,s,n,g=0,r=0;r>2],h=c[e+4>>2];e+=8;for(var Q=0;Q>2]=g,0},o:function(A,e){A>>=2;const t=i.imageData=new Uint8ClampedArray(4*e),a=i.HEAP32.subarray(A,A+e);for(let A=0;A>=2,e>>=2;const a=i.imageData=new Uint8ClampedArray(4*t),s=i.HEAP32.subarray(A,A+t),n=i.HEAP32.subarray(e,e+t);for(let A=0;A>=2,e>>=2,t>>=2;const s=i.imageData=new Uint8ClampedArray(4*a),n=i.HEAP32.subarray(A,A+a),g=i.HEAP32.subarray(e,e+a),r=i.HEAP32.subarray(t,t+a);for(let A=0;A0||(function(){if(i.preRun)for("function"==typeof i.preRun&&(i.preRun=[i.preRun]);i.preRun.length;)A=i.preRun.shift(),l.unshift(A);var A;D(l)}(),d>0||(i.setStatus?(i.setStatus("Running..."),setTimeout((function(){setTimeout((function(){i.setStatus("")}),1),A()}),1)):A()))}if(M.q,i._malloc=M.r,i._free=M.s,i._jp2_decode=M.u,p=function A(){b||L(),b||(p=A)},i.preInit)for("function"==typeof i.preInit&&(i.preInit=[i.preInit]);i.preInit.length>0;)i.preInit.pop()();return L(),i});const $t=_t;class Ai extends J{constructor(A){super(A,"JpxError")}}class ei{static#y=null;static decode(A,e){e||={},this.#y||=$t({warn:N});const t=this.#y.decode(A,e);if("string"==typeof t)throw new Ai(t);return t}static cleanup(){this.#y=null}static parseImageProperties(A){let e=A.getByte();for(;e>=0;){const t=e;if(e=A.getByte(),65361==(t<<8|e)){A.skip(4);const e=A.getInt32()>>>0,t=A.getInt32()>>>0,i=A.getInt32()>>>0,a=A.getInt32()>>>0;return A.skip(16),{width:e-i,height:t-a,bitsPerComponent:8,componentsCount:A.getUint16()}}}throw new Ai("No size marker found in JPX stream")}}class ti extends Re{constructor(A,e,t){super(e),this.stream=A,this.dict=A.dict,this.maybeLength=e,this.params=t}get bytes(){return L(this,"bytes",this.stream.getBytes(this.maybeLength))}ensureBuffer(A){}readBlock(A){this.decodeImage(null,A)}decodeImage(A,e){return this.eof||(A||=this.bytes,this.buffer=ei.decode(A,e),this.bufferLength=this.buffer.length,this.eof=!0),this.buffer}get canAsyncDecodeImageFromBuffer(){return this.stream.isAsync}}class ii extends Re{constructor(A,e,t){super(e),this.str=A,this.dict=A.dict,this.cachedData=0,this.bitsCached=0;const i=4096,a={earlyChange:t,codeLength:9,nextCode:258,dictionaryValues:new Uint8Array(i),dictionaryLengths:new Uint16Array(i),dictionaryPrevCodes:new Uint16Array(i),currentSequence:new Uint8Array(i),currentSequenceLength:0};for(let A=0;A<256;++A)a.dictionaryValues[A]=A,a.dictionaryLengths[A]=1;this.lzwState=a}readBits(A){let e=this.bitsCached,t=this.cachedData;for(;e>>e&(1<0;if(A<256)C[0]=A,B=1;else{if(!(A>=258)){if(256===A){I=9,n=258,B=0;continue}this.eof=!0,delete this.lzwState;break}if(A=0;e--)C[e]=g[t],t=o[t];else C[B++]=C[0]}if(a&&(o[n]=c,r[n]=r[c]+1,g[n]=C[0],n++,I=n+s&n+s-1?I:0|Math.min(Math.log(n+s)/.6931471805599453+1,12)),c=A,h+=B,i15))throw new T(`Unsupported predictor: ${i}`);this.readBlock=2===i?this.readBlockTiff:this.readBlockPng,this.str=A,this.dict=A.dict;const a=this.colors=t.get("Colors")||1,s=this.bits=t.get("BPC","BitsPerComponent")||8,n=this.columns=t.get("Columns")||1;return this.pixBytes=a*s+7>>3,this.rowBytes=n*a*s+7>>3,this}readBlockTiff(){const A=this.rowBytes,e=this.bufferLength,t=this.ensureBuffer(e+A),i=this.bits,a=this.colors,s=this.str.getBytes(A);if(this.eof=!s.length,this.eof)return;let n,g=0,r=0,o=0,I=0,c=e;if(1===i&&1===a)for(n=0;n>1,A^=A>>2,A^=A>>4,g=(1&A)<<7,t[c++]=A}else if(8===i){for(n=0;n>8&255,t[c++]=255&A}}else{const A=new Uint8Array(a+1),c=(1<>o-i)&c,o-=i,r=r<=8&&(t[B++]=r>>I-8&255,I-=8);I>0&&(t[B++]=(r<<8-I)+(g&(1<<8-I)-1))}this.bufferLength+=A}readBlockPng(){const A=this.rowBytes,e=this.pixBytes,t=this.str.getByte(),i=this.str.getBytes(A);if(this.eof=!i.length,this.eof)return;const a=this.bufferLength,s=this.ensureBuffer(a+A);let n=s.subarray(a-A,a);0===n.length&&(n=new Uint8Array(A));let g,r,o,I=a;switch(t){case 0:for(g=0;g>1)+i[g];for(;g>1)+i[g]&255,I++;break;case 4:for(g=0;g0){const A=this.str.getBytes(i);e.set(A,t),t+=i}}else{i=257-i;const a=A[1];e=this.ensureBuffer(t+i+1);for(let A=0;A>")&&this.buf1!==gA;){if(!(this.buf1 instanceof cA)){G("Malformed dictionary: key must be a name object"),this.shift();continue}const e=this.buf1.name;if(this.shift(),this.buf1===gA)break;i.set(e,this.getObj(A))}if(this.buf1===gA){if(this.recoveryMode)return i;throw new bA("End of file inside dictionary.")}return dA(this.buf2,"stream")?this.allowStreams?this.makeStream(i,A):i:(this.shift(),i);default:return e}if(Number.isInteger(e)){if(Number.isInteger(this.buf1)&&dA(this.buf2,"R")){const A=QA.get(e,this.buf1);return this.shift(),this.shift(),A}return e}return"string"==typeof e&&A?A.decryptString(e):e}findDefaultInlineStreamEnd(A){const{knownCommands:e}=this.lexer,t=A.pos;let i,a,s=0;for(;-1!==(i=A.getByte());)if(0===s)s=69===i?1:0;else if(1===s)s=73===i?2:0;else if(32===i||10===i||13===i){a=A.pos;const t=A.peekBytes(15),n=t.length;if(0===n)break;for(let A=0;A127)){s=0;break}if(2!==s)continue;if(!e){N("findDefaultInlineStreamEnd - `lexer.knownCommands` is undefined.");continue}const g=new oi(new ne(t.slice()),e);g._hexStringWarn=()=>{};let r=0;for(;;){const A=g.getObj();if(A===gA){s=0;break}if(A instanceof CA){const t=e[A.cmd];if(!t){s=0;break}if(t.variableArgs?r<=t.numArgs:r===t.numArgs)break;r=0}else r++}if(2===s)break}else s=0;-1===i&&(N("findDefaultInlineStreamEnd: Reached the end of the stream without finding a valid EI marker"),a&&(N('... trying to recover by using the last "EI" occurrence.'),A.skip(-(A.pos-a))));let n=4;return A.skip(-n),i=A.peekByte(),A.skip(n),JA(i)||n--,A.pos-n-t}findDCTDecodeInlineStreamEnd(A){const e=A.pos;let t,i,a=!1;for(;-1!==(t=A.getByte());)if(255===t){switch(A.getByte()){case 0:break;case 255:A.skip(-1);break;case 217:a=!0;break;case 192:case 193:case 194:case 195:case 197:case 198:case 199:case 201:case 202:case 203:case 205:case 206:case 207:case 196:case 204:case 218:case 219:case 220:case 221:case 222:case 223:case 224:case 225:case 226:case 227:case 228:case 229:case 230:case 231:case 232:case 233:case 234:case 235:case 236:case 237:case 238:case 239:case 254:i=A.getUint16(),i>2?A.skip(i-2):A.skip(-2)}if(a)break}const s=A.pos-e;return-1===t?(N("Inline DCTDecode image stream: EOI marker not found, searching for /EI/ instead."),A.skip(-s),this.findDefaultInlineStreamEnd(A)):(this.inlineStreamSkipEI(A),s)}findASCII85DecodeInlineStreamEnd(A){const e=A.pos;let t;for(;-1!==(t=A.getByte());)if(126===t){const e=A.pos;for(t=A.peekByte();JA(t);)A.skip(),t=A.peekByte();if(62===t){A.skip();break}if(A.pos>e){const e=A.peekBytes(2);if(69===e[0]&&73===e[1])break}}const i=A.pos-e;return-1===t?(N("Inline ASCII85Decode image stream: EOD marker not found, searching for /EI/ instead."),A.skip(-i),this.findDefaultInlineStreamEnd(A)):(this.inlineStreamSkipEI(A),i)}findASCIIHexDecodeInlineStreamEnd(A){const e=A.pos;let t;for(;-1!==(t=A.getByte())&&62!==t;);const i=A.pos-e;return-1===t?(N("Inline ASCIIHexDecode image stream: EOD marker not found, searching for /EI/ instead."),A.skip(-i),this.findDefaultInlineStreamEnd(A)):(this.inlineStreamSkipEI(A),i)}inlineStreamSkipEI(A){let e,t=0;for(;-1!==(e=A.getByte());)if(0===t)t=69===e?1:0;else if(1===t)t=73===e?2:0;else if(2===t)break}makeInlineImage(A){const e=this.lexer,t=e.stream,i=Object.create(null);let a;for(;!dA(this.buf1,"ID")&&this.buf1!==gA;){if(!(this.buf1 instanceof cA))throw new T("Dictionary key must be a name object");const e=this.buf1.name;if(this.shift(),this.buf1===gA)break;i[e]=this.getObj(A)}-1!==e.beginInlineImagePos&&(a=t.pos-e.beginInlineImagePos);const s=this.xref.fetchIfRef(i.F||i.Filter);let n;if(s instanceof cA)n=s.name;else if(Array.isArray(s)){const A=this.xref.fetchIfRef(s[0]);A instanceof cA&&(n=A.name)}const g=t.pos;let r,o;switch(n){case"DCT":case"DCTDecode":r=this.findDCTDecodeInlineStreamEnd(t);break;case"A85":case"ASCII85Decode":r=this.findASCII85DecodeInlineStreamEnd(t);break;case"AHx":case"ASCIIHexDecode":r=this.findASCIIHexDecodeInlineStreamEnd(t);break;default:r=this.findDefaultInlineStreamEnd(t)}if(r<1e3&&a>0){const A=t.pos;t.pos=e.beginInlineImagePos,o=function(A){const e=[],t=A.length;let i=0;for(;i=i){let i=!1;for(const A of a){const e=A.length;let a=0;for(;a=s){i=!0;break}if(a>=e){JA(n[r+g+a])&&(G(`Found "${W([...t,...A])}" when searching for endstream command.`),i=!0);break}}if(i)return e.pos+=r,e.pos-A}r++}e.pos+=g}return-1}makeStream(A,e){const t=this.lexer;let i=t.stream;t.skipToNextLine();const a=i.pos-1;let s=A.get("Length");if(Number.isInteger(s)||(G(`Bad length "${s&&s.toString()}" in stream.`),s=0),i.pos=a+s,t.nextChar(),this.tryShift()&&dA(this.buf2,"endstream"))this.shift();else{if(s=this.#w(a),s<0)throw new T("Missing endstream command.");t.nextChar(),this.shift(),this.shift()}return this.shift(),i=i.makeSubStream(a,s,A),e&&(i=e.createStream(i,s)),i=this.filter(i,A,s),i.dict=A,i}filter(A,e,t){let i=e.get("F","Filter"),a=e.get("DP","DecodeParms");if(i instanceof cA)return Array.isArray(a)&&N("/DecodeParms should not be an Array, when /Filter is a Name."),this.makeFilter(A,i.name,t,a);let s=t;if(Array.isArray(i)){const e=i,t=a;for(let n=0,g=e.length;n=48&&A<=57?15&A:A>=65&&A<=70||A>=97&&A<=102?9+(15&A):-1}class oi{constructor(A,e=null){this.stream=A,this.nextChar(),this.strBuf=[],this.knownCommands=e,this._hexStringNumWarn=0,this.beginInlineImagePos=-1}nextChar(){return this.currentChar=this.stream.getByte()}peekChar(){return this.stream.peekByte()}getNumber(){let A=this.currentChar,e=!1,t=0,i=1;if(45===A?(i=-1,A=this.nextChar(),45===A&&(A=this.nextChar())):43===A&&(A=this.nextChar()),10===A||13===A)do{A=this.nextChar()}while(10===A||13===A);if(46===A&&(t=10,A=this.nextChar()),A<48||A>57){const e=`Invalid number: ${String.fromCharCode(A)} (charCode ${A})`;if(JA(A)||-1===A)return G(`Lexer.getNumber - "${e}".`),0;throw new T(e)}let a=A-48,s=0,n=1;for(;(A=this.nextChar())>=0;)if(A>=48&&A<=57){const i=A-48;e?s=10*s+i:(0!==t&&(t*=10),a=10*a+i)}else if(46===A){if(0!==t)break;t=1}else if(45===A)N("Badly formatted number: minus sign in the middle");else{if(69!==A&&101!==A)break;if(A=this.peekChar(),43===A||45===A)n=45===A?-1:1,this.nextChar();else if(A<48||A>57)break;e=!0}return 0!==t&&(a/=t),e&&(a*=10**(n*s)),i*a}getString(){let A=1,e=!1;const t=this.strBuf;t.length=0;let i=this.nextChar();for(;;){let a=!1;switch(0|i){case-1:N("Unterminated string"),e=!0;break;case 40:++A,t.push("(");break;case 41:0==--A?(this.nextChar(),e=!0):t.push(")");break;case 92:switch(i=this.nextChar(),i){case-1:N("Unterminated string"),e=!0;break;case 110:t.push("\n");break;case 114:t.push("\r");break;case 116:t.push("\t");break;case 98:t.push("\b");break;case 102:t.push("\f");break;case 92:case 40:case 41:t.push(String.fromCharCode(i));break;case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:let A=15&i;i=this.nextChar(),a=!0,i>=48&&i<=55&&(A=(A<<3)+(15&i),i=this.nextChar(),i>=48&&i<=55&&(a=!1,A=(A<<3)+(15&i))),t.push(String.fromCharCode(A));break;case 13:10===this.peekChar()&&this.nextChar();break;case 10:break;default:t.push(String.fromCharCode(i))}break;default:t.push(String.fromCharCode(i))}if(e)break;a||(i=this.nextChar())}return t.join("")}getName(){let A,e;const t=this.strBuf;for(t.length=0;(A=this.nextChar())>=0&&!gi[A];)if(35===A){if(A=this.nextChar(),gi[A]){N("Lexer_getName: NUMBER SIGN (#) should be followed by a hexadecimal number."),t.push("#");break}const i=ri(A);if(-1!==i){e=A,A=this.nextChar();const a=ri(A);if(-1===a){if(N(`Lexer_getName: Illegal digit (${String.fromCharCode(A)}) in hexadecimal number.`),t.push("#",String.fromCharCode(e)),gi[A])break;t.push(String.fromCharCode(A));continue}t.push(String.fromCharCode(i<<4|a))}else t.push("#",String.fromCharCode(A))}else t.push(String.fromCharCode(A));return t.length>127&&N(`Name token is longer than allowed by the spec: ${t.length}`),cA.get(t.join(""))}_hexStringWarn(A){5!=this._hexStringNumWarn++?this._hexStringNumWarn>5||N(`getHexString - ignoring invalid character: ${A}`):N("getHexString - ignoring additional invalid characters.")}getHexString(){const A=this.strBuf;A.length=0;let e=this.currentChar,t=-1,i=-1;for(this._hexStringNumWarn=0;;){if(e<0){N("Unterminated hex string");break}if(62===e){this.nextChar();break}1!==gi[e]?(i=ri(e),-1===i?this._hexStringWarn(e):-1===t?t=i:(A.push(String.fromCharCode(t<<4|i)),t=-1),e=this.nextChar()):e=this.nextChar()}return-1!==t&&A.push(String.fromCharCode(t<<4)),A.join("")}getObj(){let A=!1,e=this.currentChar;for(;;){if(e<0)return gA;if(A)10!==e&&13!==e||(A=!1);else if(37===e)A=!0;else if(1!==gi[e])break;e=this.nextChar()}switch(0|e){case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:case 43:case 45:case 46:return this.getNumber();case 40:return this.getString();case 47:return this.getName();case 91:return this.nextChar(),CA.get("[");case 93:return this.nextChar(),CA.get("]");case 60:return e=this.nextChar(),60===e?(this.nextChar(),CA.get("<<")):this.getHexString();case 62:return e=this.nextChar(),62===e?(this.nextChar(),CA.get(">>")):CA.get(">");case 123:return this.nextChar(),CA.get("{");case 125:return this.nextChar(),CA.get("}");case 41:throw this.nextChar(),new T(`Illegal character: ${e}`)}let t=String.fromCharCode(e);if(e<32||e>127){const A=this.peekChar();if(A>=32&&A<=127)return this.nextChar(),CA.get(t)}const i=this.knownCommands;let a=void 0!==i?.[t];for(;(e=this.nextChar())>=0&&!gi[e];){const A=t+String.fromCharCode(e);if(a&&void 0===i[A])break;if(128===t.length)throw new T(`Command token too long: ${t.length}`);t=A,a=void 0!==i?.[t]}return"true"===t||"false"!==t&&("null"===t?null:("BI"===t&&(this.beginInlineImagePos=this.stream.pos),CA.get(t)))}skipToNextLine(){let A=this.currentChar;for(;A>=0;){if(13===A){A=this.nextChar(),10===A&&this.nextChar();break}if(10===A){this.nextChar();break}A=this.nextChar()}}}class Ii{static create(A){function e(A,e,t=!1){const i=A.get(e);if(Number.isInteger(i)&&(t?i>=0:i>0))return i;throw new Error(`The "${e}" parameter in the linearization dictionary is invalid.`)}const t=new ni({lexer:new oi(A),xref:null}),i=t.getObj(),a=t.getObj(),s=t.getObj(),n=t.getObj();let g,r;if(!(Number.isInteger(i)&&Number.isInteger(a)&&dA(s,"obj")&&n instanceof hA&&"number"==typeof(g=n.get("Linearized"))&&g>0))return null;if((r=e(n,"L"))!==A.length)throw new Error('The "L" parameter in the linearization dictionary does not equal the stream length.');return{length:r,hints:function(A){const e=A.get("H");let t;if(Array.isArray(e)&&(2===(t=e.length)||4===t)){for(let A=0;A0))throw new Error(`Hint (${A}) in the linearization dictionary is invalid.`)}return e}throw new Error("Hint array in the linearization dictionary is invalid.")}(n),objectNumberFirst:e(n,"O"),endFirst:e(n,"E"),numPages:e(n,"N"),mainXRefEntriesOffset:e(n,"T"),pageFirst:n.has("P")?e(n,"P",!0):0}}}const ci=["Adobe-GB1-UCS2","Adobe-CNS1-UCS2","Adobe-Japan1-UCS2","Adobe-Korea1-UCS2","78-EUC-H","78-EUC-V","78-H","78-RKSJ-H","78-RKSJ-V","78-V","78ms-RKSJ-H","78ms-RKSJ-V","83pv-RKSJ-H","90ms-RKSJ-H","90ms-RKSJ-V","90msp-RKSJ-H","90msp-RKSJ-V","90pv-RKSJ-H","90pv-RKSJ-V","Add-H","Add-RKSJ-H","Add-RKSJ-V","Add-V","Adobe-CNS1-0","Adobe-CNS1-1","Adobe-CNS1-2","Adobe-CNS1-3","Adobe-CNS1-4","Adobe-CNS1-5","Adobe-CNS1-6","Adobe-GB1-0","Adobe-GB1-1","Adobe-GB1-2","Adobe-GB1-3","Adobe-GB1-4","Adobe-GB1-5","Adobe-Japan1-0","Adobe-Japan1-1","Adobe-Japan1-2","Adobe-Japan1-3","Adobe-Japan1-4","Adobe-Japan1-5","Adobe-Japan1-6","Adobe-Korea1-0","Adobe-Korea1-1","Adobe-Korea1-2","B5-H","B5-V","B5pc-H","B5pc-V","CNS-EUC-H","CNS-EUC-V","CNS1-H","CNS1-V","CNS2-H","CNS2-V","ETHK-B5-H","ETHK-B5-V","ETen-B5-H","ETen-B5-V","ETenms-B5-H","ETenms-B5-V","EUC-H","EUC-V","Ext-H","Ext-RKSJ-H","Ext-RKSJ-V","Ext-V","GB-EUC-H","GB-EUC-V","GB-H","GB-V","GBK-EUC-H","GBK-EUC-V","GBK2K-H","GBK2K-V","GBKp-EUC-H","GBKp-EUC-V","GBT-EUC-H","GBT-EUC-V","GBT-H","GBT-V","GBTpc-EUC-H","GBTpc-EUC-V","GBpc-EUC-H","GBpc-EUC-V","H","HKdla-B5-H","HKdla-B5-V","HKdlb-B5-H","HKdlb-B5-V","HKgccs-B5-H","HKgccs-B5-V","HKm314-B5-H","HKm314-B5-V","HKm471-B5-H","HKm471-B5-V","HKscs-B5-H","HKscs-B5-V","Hankaku","Hiragana","KSC-EUC-H","KSC-EUC-V","KSC-H","KSC-Johab-H","KSC-Johab-V","KSC-V","KSCms-UHC-H","KSCms-UHC-HW-H","KSCms-UHC-HW-V","KSCms-UHC-V","KSCpc-EUC-H","KSCpc-EUC-V","Katakana","NWP-H","NWP-V","RKSJ-H","RKSJ-V","Roman","UniCNS-UCS2-H","UniCNS-UCS2-V","UniCNS-UTF16-H","UniCNS-UTF16-V","UniCNS-UTF32-H","UniCNS-UTF32-V","UniCNS-UTF8-H","UniCNS-UTF8-V","UniGB-UCS2-H","UniGB-UCS2-V","UniGB-UTF16-H","UniGB-UTF16-V","UniGB-UTF32-H","UniGB-UTF32-V","UniGB-UTF8-H","UniGB-UTF8-V","UniJIS-UCS2-H","UniJIS-UCS2-HW-H","UniJIS-UCS2-HW-V","UniJIS-UCS2-V","UniJIS-UTF16-H","UniJIS-UTF16-V","UniJIS-UTF32-H","UniJIS-UTF32-V","UniJIS-UTF8-H","UniJIS-UTF8-V","UniJIS2004-UTF16-H","UniJIS2004-UTF16-V","UniJIS2004-UTF32-H","UniJIS2004-UTF32-V","UniJIS2004-UTF8-H","UniJIS2004-UTF8-V","UniJISPro-UCS2-HW-V","UniJISPro-UCS2-V","UniJISPro-UTF8-V","UniJISX0213-UTF32-H","UniJISX0213-UTF32-V","UniJISX02132004-UTF32-H","UniJISX02132004-UTF32-V","UniKS-UCS2-H","UniKS-UCS2-V","UniKS-UTF16-H","UniKS-UTF16-V","UniKS-UTF32-H","UniKS-UTF32-V","UniKS-UTF8-H","UniKS-UTF8-V","V","WP-Symbol"],Ci=2**24-1;class Bi{constructor(A=!1){this.codespaceRanges=[[],[],[],[]],this.numCodespaceRanges=0,this._map=[],this.name="",this.vertical=!1,this.useCMap=null,this.builtInCMap=A}addCodespaceRange(A,e,t){this.codespaceRanges[A-1].push(e,t),this.numCodespaceRanges++}mapCidRange(A,e,t){if(e-A>Ci)throw new Error("mapCidRange - ignoring data above MAX_MAP_RANGE.");for(;A<=e;)this._map[A++]=t++}mapBfRange(A,e,t){if(e-A>Ci)throw new Error("mapBfRange - ignoring data above MAX_MAP_RANGE.");const i=t.length-1;for(;A<=e;){this._map[A++]=t;const e=t.charCodeAt(i)+1;t=e>255?t.substring(0,i-1)+String.fromCharCode(t.charCodeAt(i-1)+1)+"\0":t.substring(0,i)+String.fromCharCode(e)}}mapBfRangeToArray(A,e,t){if(e-A>Ci)throw new Error("mapBfRangeToArray - ignoring data above MAX_MAP_RANGE.");const i=t.length;let a=0;for(;A<=e&&a>>0;const n=a[s];for(let A=0,e=n.length;A=e&&i<=a)return t.charcode=i,void(t.length=s+1)}}t.charcode=0,t.length=1}getCharCodeLength(A){const e=this.codespaceRanges;for(let t=0,i=e.length;t=a&&A<=s)return t+1}}return 1}get length(){return this._map.length}get isIdentityCMap(){if("Identity-H"!==this.name&&"Identity-V"!==this.name)return!1;if(65536!==this._map.length)return!1;for(let A=0;A<65536;A++)if(this._map[A]!==A)return!1;return!0}}class hi extends Bi{constructor(A,e){super(),this.vertical=A,this.addCodespaceRange(e,0,65535)}mapCidRange(A,e,t){x("should not call mapCidRange")}mapBfRange(A,e,t){x("should not call mapBfRange")}mapBfRangeToArray(A,e,t){x("should not call mapBfRangeToArray")}mapOne(A,e){x("should not call mapCidOne")}lookup(A){return Number.isInteger(A)&&A<=65535?A:void 0}contains(A){return Number.isInteger(A)&&A<=65535}forEach(A){for(let e=0;e<=65535;e++)A(e,e)}charCodeOf(A){return Number.isInteger(A)&&A<=65535?A:-1}getMap(){const A=new Array(65536);for(let e=0;e<=65535;e++)A[e]=e;return A}get length(){return 65536}get isIdentityCMap(){x("should not access .isIdentityCMap")}}function Qi(A){let e=0;for(let t=0;t>>0}function li(A){if("string"!=typeof A)throw new T("Malformed CMap: expected string.")}function Ei(A){if(!Number.isInteger(A))throw new T("Malformed CMap: expected int.")}function ui(A,e){for(;;){let t=e.getObj();if(t===gA)break;if(dA(t,"endbfchar"))return;li(t);const i=Qi(t);t=e.getObj(),li(t);const a=t;A.mapOne(i,a)}}function di(A,e){for(;;){let t=e.getObj();if(t===gA)break;if(dA(t,"endbfrange"))return;li(t);const i=Qi(t);t=e.getObj(),li(t);const a=Qi(t);if(t=e.getObj(),Number.isInteger(t)||"string"==typeof t){const e=Number.isInteger(t)?String.fromCharCode(t):t;A.mapBfRange(i,a,e)}else{if(!dA(t,"["))break;{t=e.getObj();const s=[];for(;!dA(t,"]")&&t!==gA;)s.push(t),t=e.getObj();A.mapBfRangeToArray(i,a,s)}}}throw new T("Invalid bf range.")}function fi(A,e){for(;;){let t=e.getObj();if(t===gA)break;if(dA(t,"endcidchar"))return;li(t);const i=Qi(t);t=e.getObj(),Ei(t);const a=t;A.mapOne(i,a)}}function pi(A,e){for(;;){let t=e.getObj();if(t===gA)break;if(dA(t,"endcidrange"))return;li(t);const i=Qi(t);t=e.getObj(),li(t);const a=Qi(t);t=e.getObj(),Ei(t);const s=t;A.mapCidRange(i,a,s)}}function mi(A,e){for(;;){let t=e.getObj();if(t===gA)break;if(dA(t,"endcodespacerange"))return;if("string"!=typeof t)break;const i=Qi(t);if(t=e.getObj(),"string"!=typeof t)break;const a=Qi(t);A.addCodespaceRange(t.length,i,a)}throw new T("Invalid codespace range.")}function yi(A,e){const t=e.getObj();Number.isInteger(t)&&(A.vertical=!!t)}function wi(A,e){const t=e.getObj();t instanceof cA&&(A.name=t.name)}async function Di(A,e,t,i){let a,s;A:for(;;)try{const t=e.getObj();if(t===gA)break;if(t instanceof cA)"WMode"===t.name?yi(A,e):"CMapName"===t.name&&wi(A,e),a=t;else if(t instanceof CA)switch(t.cmd){case"endcmap":break A;case"usecmap":a instanceof cA&&(s=a.name);break;case"begincodespacerange":mi(A,e);break;case"beginbfchar":ui(A,e);break;case"begincidchar":fi(A,e);break;case"beginbfrange":di(A,e);break;case"begincidrange":pi(A,e)}}catch(A){if(A instanceof DA)throw A;N("Invalid cMap data: "+A);continue}return!i&&s&&(i=s),i?bi(A,t,i):A}async function bi(A,e,t){if(A.useCMap=await ki(t,e),0===A.numCodespaceRanges){const e=A.useCMap.codespaceRanges;for(let t=0;tbi(a,e,A)));if(i===E.NONE){const A=new oi(new ne(t));return Di(a,A,e,null)}throw new Error(`Invalid CMap "compressionType" value: ${i}`)}class Fi{static async create({encoding:A,fetchBuiltInCMap:e,useCMap:t}){if(A instanceof cA)return ki(A.name,e);if(A instanceof mA){const i=await Di(new Bi,new oi(A),e,t);return i.isIdentityCMap?ki(i.name,e):i}throw new Error("Encoding required.")}}const Si=[".notdef","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quoteright","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","quoteleft","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","exclamdown","cent","sterling","fraction","yen","florin","section","currency","quotesingle","quotedblleft","guillemotleft","guilsinglleft","guilsinglright","fi","fl","endash","dagger","daggerdbl","periodcentered","paragraph","bullet","quotesinglbase","quotedblbase","quotedblright","guillemotright","ellipsis","perthousand","questiondown","grave","acute","circumflex","tilde","macron","breve","dotaccent","dieresis","ring","cedilla","hungarumlaut","ogonek","caron","emdash","AE","ordfeminine","Lslash","Oslash","OE","ordmasculine","ae","dotlessi","lslash","oslash","oe","germandbls","onesuperior","logicalnot","mu","trademark","Eth","onehalf","plusminus","Thorn","onequarter","divide","brokenbar","degree","thorn","threequarters","twosuperior","registered","minus","eth","multiply","threesuperior","copyright","Aacute","Acircumflex","Adieresis","Agrave","Aring","Atilde","Ccedilla","Eacute","Ecircumflex","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Ntilde","Oacute","Ocircumflex","Odieresis","Ograve","Otilde","Scaron","Uacute","Ucircumflex","Udieresis","Ugrave","Yacute","Ydieresis","Zcaron","aacute","acircumflex","adieresis","agrave","aring","atilde","ccedilla","eacute","ecircumflex","edieresis","egrave","iacute","icircumflex","idieresis","igrave","ntilde","oacute","ocircumflex","odieresis","ograve","otilde","scaron","uacute","ucircumflex","udieresis","ugrave","yacute","ydieresis","zcaron"],Ri=[".notdef","space","exclamsmall","Hungarumlautsmall","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","commasuperior","threequartersemdash","periodsuperior","questionsmall","asuperior","bsuperior","centsuperior","dsuperior","esuperior","isuperior","lsuperior","msuperior","nsuperior","osuperior","rsuperior","ssuperior","tsuperior","ff","fi","fl","ffi","ffl","parenleftinferior","parenrightinferior","Circumflexsmall","hyphensuperior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","exclamdownsmall","centoldstyle","Lslashsmall","Scaronsmall","Zcaronsmall","Dieresissmall","Brevesmall","Caronsmall","Dotaccentsmall","Macronsmall","figuredash","hypheninferior","Ogoneksmall","Ringsmall","Cedillasmall","onequarter","onehalf","threequarters","questiondownsmall","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","zerosuperior","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior","Agravesmall","Aacutesmall","Acircumflexsmall","Atildesmall","Adieresissmall","Aringsmall","AEsmall","Ccedillasmall","Egravesmall","Eacutesmall","Ecircumflexsmall","Edieresissmall","Igravesmall","Iacutesmall","Icircumflexsmall","Idieresissmall","Ethsmall","Ntildesmall","Ogravesmall","Oacutesmall","Ocircumflexsmall","Otildesmall","Odieresissmall","OEsmall","Oslashsmall","Ugravesmall","Uacutesmall","Ucircumflexsmall","Udieresissmall","Yacutesmall","Thornsmall","Ydieresissmall"],Gi=[".notdef","space","dollaroldstyle","dollarsuperior","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","commasuperior","threequartersemdash","periodsuperior","asuperior","bsuperior","centsuperior","dsuperior","esuperior","isuperior","lsuperior","msuperior","nsuperior","osuperior","rsuperior","ssuperior","tsuperior","ff","fi","fl","ffi","ffl","parenleftinferior","parenrightinferior","hyphensuperior","colonmonetary","onefitted","rupiah","centoldstyle","figuredash","hypheninferior","onequarter","onehalf","threequarters","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","zerosuperior","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior"],Ni=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclamsmall","Hungarumlautsmall","","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","commasuperior","threequartersemdash","periodsuperior","questionsmall","","asuperior","bsuperior","centsuperior","dsuperior","esuperior","","","","isuperior","","","lsuperior","msuperior","nsuperior","osuperior","","","rsuperior","ssuperior","tsuperior","","ff","fi","fl","ffi","ffl","parenleftinferior","","parenrightinferior","Circumflexsmall","hyphensuperior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","exclamdownsmall","centoldstyle","Lslashsmall","","","Scaronsmall","Zcaronsmall","Dieresissmall","Brevesmall","Caronsmall","","Dotaccentsmall","","","Macronsmall","","","figuredash","hypheninferior","","","Ogoneksmall","Ringsmall","Cedillasmall","","","","onequarter","onehalf","threequarters","questiondownsmall","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","","","zerosuperior","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior","Agravesmall","Aacutesmall","Acircumflexsmall","Atildesmall","Adieresissmall","Aringsmall","AEsmall","Ccedillasmall","Egravesmall","Eacutesmall","Ecircumflexsmall","Edieresissmall","Igravesmall","Iacutesmall","Icircumflexsmall","Idieresissmall","Ethsmall","Ntildesmall","Ogravesmall","Oacutesmall","Ocircumflexsmall","Otildesmall","Odieresissmall","OEsmall","Oslashsmall","Ugravesmall","Uacutesmall","Ucircumflexsmall","Udieresissmall","Yacutesmall","Thornsmall","Ydieresissmall"],xi=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclamsmall","Hungarumlautsmall","centoldstyle","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","","threequartersemdash","","questionsmall","","","","","Ethsmall","","","onequarter","onehalf","threequarters","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","","","","","","","ff","fi","fl","ffi","ffl","parenleftinferior","","parenrightinferior","Circumflexsmall","hypheninferior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","","","asuperior","centsuperior","","","","","Aacutesmall","Agravesmall","Acircumflexsmall","Adieresissmall","Atildesmall","Aringsmall","Ccedillasmall","Eacutesmall","Egravesmall","Ecircumflexsmall","Edieresissmall","Iacutesmall","Igravesmall","Icircumflexsmall","Idieresissmall","Ntildesmall","Oacutesmall","Ogravesmall","Ocircumflexsmall","Odieresissmall","Otildesmall","Uacutesmall","Ugravesmall","Ucircumflexsmall","Udieresissmall","","eightsuperior","fourinferior","threeinferior","sixinferior","eightinferior","seveninferior","Scaronsmall","","centinferior","twoinferior","","Dieresissmall","","Caronsmall","osuperior","fiveinferior","","commainferior","periodinferior","Yacutesmall","","dollarinferior","","","Thornsmall","","nineinferior","zeroinferior","Zcaronsmall","AEsmall","Oslashsmall","questiondownsmall","oneinferior","Lslashsmall","","","","","","","Cedillasmall","","","","","","OEsmall","figuredash","hyphensuperior","","","","","exclamdownsmall","","Ydieresissmall","","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","ninesuperior","zerosuperior","","esuperior","rsuperior","tsuperior","","","isuperior","ssuperior","dsuperior","","","","","","lsuperior","Ogoneksmall","Brevesmall","Macronsmall","bsuperior","nsuperior","msuperior","commasuperior","periodsuperior","Dotaccentsmall","Ringsmall","","","",""],Ui=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quotesingle","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","grave","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","","Adieresis","Aring","Ccedilla","Eacute","Ntilde","Odieresis","Udieresis","aacute","agrave","acircumflex","adieresis","atilde","aring","ccedilla","eacute","egrave","ecircumflex","edieresis","iacute","igrave","icircumflex","idieresis","ntilde","oacute","ograve","ocircumflex","odieresis","otilde","uacute","ugrave","ucircumflex","udieresis","dagger","degree","cent","sterling","section","bullet","paragraph","germandbls","registered","copyright","trademark","acute","dieresis","notequal","AE","Oslash","infinity","plusminus","lessequal","greaterequal","yen","mu","partialdiff","summation","product","pi","integral","ordfeminine","ordmasculine","Omega","ae","oslash","questiondown","exclamdown","logicalnot","radical","florin","approxequal","Delta","guillemotleft","guillemotright","ellipsis","space","Agrave","Atilde","Otilde","OE","oe","endash","emdash","quotedblleft","quotedblright","quoteleft","quoteright","divide","lozenge","ydieresis","Ydieresis","fraction","currency","guilsinglleft","guilsinglright","fi","fl","daggerdbl","periodcentered","quotesinglbase","quotedblbase","perthousand","Acircumflex","Ecircumflex","Aacute","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Oacute","Ocircumflex","apple","Ograve","Uacute","Ucircumflex","Ugrave","dotlessi","circumflex","tilde","macron","breve","dotaccent","ring","cedilla","hungarumlaut","ogonek","caron"],Mi=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quoteright","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","quoteleft","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","exclamdown","cent","sterling","fraction","yen","florin","section","currency","quotesingle","quotedblleft","guillemotleft","guilsinglleft","guilsinglright","fi","fl","","endash","dagger","daggerdbl","periodcentered","","paragraph","bullet","quotesinglbase","quotedblbase","quotedblright","guillemotright","ellipsis","perthousand","","questiondown","","grave","acute","circumflex","tilde","macron","breve","dotaccent","dieresis","","ring","cedilla","","hungarumlaut","ogonek","caron","emdash","","","","","","","","","","","","","","","","","AE","","ordfeminine","","","","","Lslash","Oslash","OE","ordmasculine","","","","","","ae","","","","dotlessi","","","lslash","oslash","oe","germandbls","","","",""],Li=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quotesingle","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","grave","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","bullet","Euro","bullet","quotesinglbase","florin","quotedblbase","ellipsis","dagger","daggerdbl","circumflex","perthousand","Scaron","guilsinglleft","OE","bullet","Zcaron","bullet","bullet","quoteleft","quoteright","quotedblleft","quotedblright","bullet","endash","emdash","tilde","trademark","scaron","guilsinglright","oe","bullet","zcaron","Ydieresis","space","exclamdown","cent","sterling","currency","yen","brokenbar","section","dieresis","copyright","ordfeminine","guillemotleft","logicalnot","hyphen","registered","macron","degree","plusminus","twosuperior","threesuperior","acute","mu","paragraph","periodcentered","cedilla","onesuperior","ordmasculine","guillemotright","onequarter","onehalf","threequarters","questiondown","Agrave","Aacute","Acircumflex","Atilde","Adieresis","Aring","AE","Ccedilla","Egrave","Eacute","Ecircumflex","Edieresis","Igrave","Iacute","Icircumflex","Idieresis","Eth","Ntilde","Ograve","Oacute","Ocircumflex","Otilde","Odieresis","multiply","Oslash","Ugrave","Uacute","Ucircumflex","Udieresis","Yacute","Thorn","germandbls","agrave","aacute","acircumflex","atilde","adieresis","aring","ae","ccedilla","egrave","eacute","ecircumflex","edieresis","igrave","iacute","icircumflex","idieresis","eth","ntilde","ograve","oacute","ocircumflex","otilde","odieresis","divide","oslash","ugrave","uacute","ucircumflex","udieresis","yacute","thorn","ydieresis"],Ji=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","universal","numbersign","existential","percent","ampersand","suchthat","parenleft","parenright","asteriskmath","plus","comma","minus","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","congruent","Alpha","Beta","Chi","Delta","Epsilon","Phi","Gamma","Eta","Iota","theta1","Kappa","Lambda","Mu","Nu","Omicron","Pi","Theta","Rho","Sigma","Tau","Upsilon","sigma1","Omega","Xi","Psi","Zeta","bracketleft","therefore","bracketright","perpendicular","underscore","radicalex","alpha","beta","chi","delta","epsilon","phi","gamma","eta","iota","phi1","kappa","lambda","mu","nu","omicron","pi","theta","rho","sigma","tau","upsilon","omega1","omega","xi","psi","zeta","braceleft","bar","braceright","similar","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","Euro","Upsilon1","minute","lessequal","fraction","infinity","florin","club","diamond","heart","spade","arrowboth","arrowleft","arrowup","arrowright","arrowdown","degree","plusminus","second","greaterequal","multiply","proportional","partialdiff","bullet","divide","notequal","equivalence","approxequal","ellipsis","arrowvertex","arrowhorizex","carriagereturn","aleph","Ifraktur","Rfraktur","weierstrass","circlemultiply","circleplus","emptyset","intersection","union","propersuperset","reflexsuperset","notsubset","propersubset","reflexsubset","element","notelement","angle","gradient","registerserif","copyrightserif","trademarkserif","product","radical","dotmath","logicalnot","logicaland","logicalor","arrowdblboth","arrowdblleft","arrowdblup","arrowdblright","arrowdbldown","lozenge","angleleft","registersans","copyrightsans","trademarksans","summation","parenlefttp","parenleftex","parenleftbt","bracketlefttp","bracketleftex","bracketleftbt","bracelefttp","braceleftmid","braceleftbt","braceex","","angleright","integral","integraltp","integralex","integralbt","parenrighttp","parenrightex","parenrightbt","bracketrighttp","bracketrightex","bracketrightbt","bracerighttp","bracerightmid","bracerightbt",""],Hi=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","a1","a2","a202","a3","a4","a5","a119","a118","a117","a11","a12","a13","a14","a15","a16","a105","a17","a18","a19","a20","a21","a22","a23","a24","a25","a26","a27","a28","a6","a7","a8","a9","a10","a29","a30","a31","a32","a33","a34","a35","a36","a37","a38","a39","a40","a41","a42","a43","a44","a45","a46","a47","a48","a49","a50","a51","a52","a53","a54","a55","a56","a57","a58","a59","a60","a61","a62","a63","a64","a65","a66","a67","a68","a69","a70","a71","a72","a73","a74","a203","a75","a204","a76","a77","a78","a79","a81","a82","a83","a84","a97","a98","a99","a100","","a89","a90","a93","a94","a91","a92","a205","a85","a206","a86","a87","a88","a95","a96","","","","","","","","","","","","","","","","","","","","a101","a102","a103","a104","a106","a107","a108","a112","a111","a110","a109","a120","a121","a122","a123","a124","a125","a126","a127","a128","a129","a130","a131","a132","a133","a134","a135","a136","a137","a138","a139","a140","a141","a142","a143","a144","a145","a146","a147","a148","a149","a150","a151","a152","a153","a154","a155","a156","a157","a158","a159","a160","a161","a163","a164","a196","a165","a192","a166","a167","a168","a169","a170","a171","a172","a173","a162","a174","a175","a176","a177","a178","a179","a193","a180","a199","a181","a200","a182","","a201","a183","a184","a197","a185","a194","a198","a186","a195","a187","a188","a189","a190","a191",""];function Yi(A){switch(A){case"WinAnsiEncoding":return Li;case"StandardEncoding":return Mi;case"MacRomanEncoding":return Ui;case"SymbolSetEncoding":return Ji;case"ZapfDingbatsEncoding":return Hi;case"ExpertEncoding":return Ni;case"MacExpertEncoding":return xi;default:return null}}const vi=[".notdef","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quoteright","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","quoteleft","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","exclamdown","cent","sterling","fraction","yen","florin","section","currency","quotesingle","quotedblleft","guillemotleft","guilsinglleft","guilsinglright","fi","fl","endash","dagger","daggerdbl","periodcentered","paragraph","bullet","quotesinglbase","quotedblbase","quotedblright","guillemotright","ellipsis","perthousand","questiondown","grave","acute","circumflex","tilde","macron","breve","dotaccent","dieresis","ring","cedilla","hungarumlaut","ogonek","caron","emdash","AE","ordfeminine","Lslash","Oslash","OE","ordmasculine","ae","dotlessi","lslash","oslash","oe","germandbls","onesuperior","logicalnot","mu","trademark","Eth","onehalf","plusminus","Thorn","onequarter","divide","brokenbar","degree","thorn","threequarters","twosuperior","registered","minus","eth","multiply","threesuperior","copyright","Aacute","Acircumflex","Adieresis","Agrave","Aring","Atilde","Ccedilla","Eacute","Ecircumflex","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Ntilde","Oacute","Ocircumflex","Odieresis","Ograve","Otilde","Scaron","Uacute","Ucircumflex","Udieresis","Ugrave","Yacute","Ydieresis","Zcaron","aacute","acircumflex","adieresis","agrave","aring","atilde","ccedilla","eacute","ecircumflex","edieresis","egrave","iacute","icircumflex","idieresis","igrave","ntilde","oacute","ocircumflex","odieresis","ograve","otilde","scaron","uacute","ucircumflex","udieresis","ugrave","yacute","ydieresis","zcaron","exclamsmall","Hungarumlautsmall","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","commasuperior","threequartersemdash","periodsuperior","questionsmall","asuperior","bsuperior","centsuperior","dsuperior","esuperior","isuperior","lsuperior","msuperior","nsuperior","osuperior","rsuperior","ssuperior","tsuperior","ff","ffi","ffl","parenleftinferior","parenrightinferior","Circumflexsmall","hyphensuperior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","exclamdownsmall","centoldstyle","Lslashsmall","Scaronsmall","Zcaronsmall","Dieresissmall","Brevesmall","Caronsmall","Dotaccentsmall","Macronsmall","figuredash","hypheninferior","Ogoneksmall","Ringsmall","Cedillasmall","questiondownsmall","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","zerosuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior","Agravesmall","Aacutesmall","Acircumflexsmall","Atildesmall","Adieresissmall","Aringsmall","AEsmall","Ccedillasmall","Egravesmall","Eacutesmall","Ecircumflexsmall","Edieresissmall","Igravesmall","Iacutesmall","Icircumflexsmall","Idieresissmall","Ethsmall","Ntildesmall","Ogravesmall","Oacutesmall","Ocircumflexsmall","Otildesmall","Odieresissmall","OEsmall","Oslashsmall","Ugravesmall","Uacutesmall","Ucircumflexsmall","Udieresissmall","Yacutesmall","Thornsmall","Ydieresissmall","001.000","001.001","001.002","001.003","Black","Bold","Book","Light","Medium","Regular","Roman","Semibold"],Ki=[null,{id:"hstem",min:2,stackClearing:!0,stem:!0},null,{id:"vstem",min:2,stackClearing:!0,stem:!0},{id:"vmoveto",min:1,stackClearing:!0},{id:"rlineto",min:2,resetStack:!0},{id:"hlineto",min:1,resetStack:!0},{id:"vlineto",min:1,resetStack:!0},{id:"rrcurveto",min:6,resetStack:!0},null,{id:"callsubr",min:1,undefStack:!0},{id:"return",min:0,undefStack:!0},null,null,{id:"endchar",min:0,stackClearing:!0},null,null,null,{id:"hstemhm",min:2,stackClearing:!0,stem:!0},{id:"hintmask",min:0,stackClearing:!0},{id:"cntrmask",min:0,stackClearing:!0},{id:"rmoveto",min:2,stackClearing:!0},{id:"hmoveto",min:1,stackClearing:!0},{id:"vstemhm",min:2,stackClearing:!0,stem:!0},{id:"rcurveline",min:8,resetStack:!0},{id:"rlinecurve",min:8,resetStack:!0},{id:"vvcurveto",min:4,resetStack:!0},{id:"hhcurveto",min:4,resetStack:!0},null,{id:"callgsubr",min:1,undefStack:!0},{id:"vhcurveto",min:4,resetStack:!0},{id:"hvcurveto",min:4,resetStack:!0}],qi=[null,null,null,{id:"and",min:2,stackDelta:-1},{id:"or",min:2,stackDelta:-1},{id:"not",min:1,stackDelta:0},null,null,null,{id:"abs",min:1,stackDelta:0},{id:"add",min:2,stackDelta:-1,stackFn(A,e){A[e-2]=A[e-2]+A[e-1]}},{id:"sub",min:2,stackDelta:-1,stackFn(A,e){A[e-2]=A[e-2]-A[e-1]}},{id:"div",min:2,stackDelta:-1,stackFn(A,e){A[e-2]=A[e-2]/A[e-1]}},null,{id:"neg",min:1,stackDelta:0,stackFn(A,e){A[e-1]=-A[e-1]}},{id:"eq",min:2,stackDelta:-1},null,null,{id:"drop",min:1,stackDelta:-1},null,{id:"put",min:2,stackDelta:-2},{id:"get",min:1,stackDelta:0},{id:"ifelse",min:4,stackDelta:-3},{id:"random",min:0,stackDelta:1},{id:"mul",min:2,stackDelta:-1,stackFn(A,e){A[e-2]=A[e-2]*A[e-1]}},null,{id:"sqrt",min:1,stackDelta:0},{id:"dup",min:1,stackDelta:1},{id:"exch",min:2,stackDelta:0},{id:"index",min:2,stackDelta:0},{id:"roll",min:3,stackDelta:-2},null,null,null,{id:"hflex",min:7,resetStack:!0},{id:"flex",min:13,resetStack:!0},{id:"hflex1",min:9,resetStack:!0},{id:"flex1",min:11,resetStack:!0}];class Ti{constructor(A,e,t){this.bytes=A.getBytes(),this.properties=e,this.seacAnalysisEnabled=!!t}parse(){const A=this.properties,e=new Pi;this.cff=e;const t=this.parseHeader(),i=this.parseIndex(t.endPos),a=this.parseIndex(i.endPos),s=this.parseIndex(a.endPos),n=this.parseIndex(s.endPos),g=this.parseDict(a.obj.get(0)),r=this.createDict(ji,g,e.strings);e.header=t.obj,e.names=this.parseNameIndex(i.obj),e.strings=this.parseStringIndex(s.obj),e.topDict=r,e.globalSubrIndex=n.obj,this.parsePrivateDict(e.topDict),e.isCIDFont=r.hasName("ROS");const o=r.getByName("CharStrings"),I=this.parseIndex(o).obj,c=r.getByName("FontMatrix");c&&(A.fontMatrix=c);const C=r.getByName("FontBBox");let B,h;if(C&&(A.ascent=Math.max(C[3],C[1]),A.descent=Math.min(C[1],C[3]),A.ascentScaled=!0),e.isCIDFont){const A=this.parseIndex(r.getByName("FDArray")).obj;for(let t=0,i=A.count;t=e)throw new T("Invalid CFF header");0!==t&&(G("cff data is shifted"),A=A.subarray(t),this.bytes=A);const i=A[0],a=A[1],s=A[2],n=A[3];return{obj:new Wi(i,a,s,n),endPos:s}}parseDict(A){let e=0;function t(){let t=A[e++];return 30===t?function(){let t="";const i=["0","1","2","3","4","5","6","7","8","9",".","E","E-",null,"-"],a=A.length;for(;e>4,n=15&a;if(15===s)break;if(t+=i[s],15===n)break;t+=i[n]}return parseFloat(t)}():28===t?(t=A[e++],t=(t<<24|A[e++]<<16)>>16,t):29===t?(t=A[e++],t=t<<8|A[e++],t=t<<8|A[e++],t=t<<8|A[e++],t):t>=32&&t<=246?t-139:t>=247&&t<=250?256*(t-247)+A[e++]+108:t>=251&&t<=254?-256*(t-251)-A[e++]-108:(N('CFFParser_parseDict: "'+t+'" is a reserved command.'),NaN)}let i=[];const a=[];e=0;const s=A.length;for(;e10)return!1;let a=A.stackSize;const s=A.stack;let n=e.length;for(let g=0;g>16,g+=2,a++;else if(14===r){if(a>=4&&(a-=4,this.seacAnalysisEnabled))return A.seac=s.slice(a,a+4),!1;o=Ki[r]}else if(r>=32&&r<=246)s[a]=r-139,a++;else if(r>=247&&r<=254)s[a]=r<251?(r-247<<8)+e[g]+108:-(r-251<<8)-e[g]-108,g++,a++;else if(255===r)s[a]=(e[g]<<24|e[g+1]<<16|e[g+2]<<8|e[g+3])/65536,g+=4,a++;else if(19===r||20===r){if(A.hints+=a>>1,0===A.hints){e.copyWithin(g-1,g,-1),g-=1,n-=1;continue}g+=A.hints+7>>3,a%=2,o=Ki[r]}else{if(10===r||29===r){const e=10===r?t:i;if(!e)return o=Ki[r],N("Missing subrsIndex for "+o.id),!1;let n=32768;e.count<1240?n=107:e.count<33900&&(n=1131);const g=s[--a]+n;if(g<0||g>=e.count||isNaN(g))return o=Ki[r],N("Out of bounds subrIndex for "+o.id),!1;if(A.stackSize=a,A.callDepth++,!this.parseCharString(A,e.get(g),t,i))return!1;A.callDepth--,a=A.stackSize;continue}if(11===r)return A.stackSize=a,!0;if(0===r&&g===e.length)e[g-1]=14,o=Ki[14];else{if(9===r){e.copyWithin(g-1,g,-1),g-=1,n-=1;continue}o=Ki[r]}}if(o){if(o.stem&&(A.hints+=a>>1,3===r||23===r?A.hasVStems=!0:!A.hasVStems||1!==r&&18!==r||(N("CFF stem hints are in wrong order"),e[g-1]=1===r?3:23)),"min"in o&&!A.undefStack&&a=2&&o.stem?a%=2:a>1&&N("Found too many parameters for stack-clearing command"),a>0&&(A.width=s[a-1])),"stackDelta"in o?("stackFn"in o&&o.stackFn(s,a),a+=o.stackDelta):o.stackClearing?a=0:o.resetStack?(a=0,A.undefStack=!1):o.undefStack&&(a=0,A.undefStack=!0,A.firstStackClearing=!1)}}return n=a.length&&(N("Invalid fd index for glyph index."),c=!1),c&&(B=a[A].privateDict,C=B.subrsIndex)}else e&&(C=e);if(c&&(c=this.parseCharString(I,r,C,t)),null!==I.width){const A=B.getByName("nominalWidthX");g[o]=A+I.width}else{const A=B.getByName("defaultWidthX");g[o]=A}null!==I.seac&&(n[o]=I.seac),c||A.set(o,new Uint8Array([14]))}return{charStrings:A,seacs:n,widths:g}}emptyPrivateDictionary(A){const e=this.createDict(_i,[],A.strings);A.setByKey(18,[0,0]),A.privateDict=e}parsePrivateDict(A){if(!A.hasName("Private"))return void this.emptyPrivateDictionary(A);const e=A.getByName("Private");if(!Array.isArray(e)||2!==e.length)return void A.removeByName("Private");const t=e[0],i=e[1];if(0===t||i>=this.bytes.length)return void this.emptyPrivateDictionary(A);const a=i+t,s=this.bytes.subarray(i,a),n=this.parseDict(s),g=this.createDict(_i,n,A.strings);if(A.privateDict=g,0===g.getByName("ExpansionFactor")&&g.setByName("ExpansionFactor",.06),!g.getByName("Subrs"))return;const r=g.getByName("Subrs"),o=i+r;if(0===r||o>=this.bytes.length)return void this.emptyPrivateDictionary(A);const I=this.parseIndex(o);g.subrsIndex=I.obj}parseCharsets(A,e,t,i){if(0===A)return new Aa(!0,$i.ISO_ADOBE,Si);if(1===A)return new Aa(!0,$i.EXPERT,Ri);if(2===A)return new Aa(!0,$i.EXPERT_SUBSET,Gi);const a=this.bytes,s=A,n=a[A++],g=[i?0:".notdef"];let r,o,I;switch(e-=1,n){case 0:for(I=0;I=65535)return void N("Not enough space in charstrings to duplicate first glyph.");const A=this.charStrings.get(0);this.charStrings.add(A),this.isCIDFont&&this.fdSelect.fdSelect.push(this.fdSelect.fdSelect[0])}hasGlyphId(A){return!(A<0||A>=this.charStrings.count)&&this.charStrings.get(A).length>0}}class Wi{constructor(A,e,t,i){this.major=A,this.minor=e,this.hdrSize=t,this.offSize=i}}class Zi{constructor(){this.strings=[]}get(A){return A>=0&&A<=390?vi[A]:A-391<=this.strings.length?this.strings[A-391]:vi[0]}getSID(A){let e=vi.indexOf(A);return-1!==e?e:(e=this.strings.indexOf(A),-1!==e?e+391:-1)}add(A){this.strings.push(A)}get count(){return this.strings.length}}class Oi{constructor(){this.objects=[],this.length=0}add(A){this.length+=A.length,this.objects.push(A)}set(A,e){this.length+=e.length-this.objects[A].length,this.objects[A]=e}get(A){return this.objects[A]}get count(){return this.objects.length}}class Xi{constructor(A,e){this.keyToNameMap=A.keyToNameMap,this.nameToKeyMap=A.nameToKeyMap,this.defaults=A.defaults,this.types=A.types,this.opcodes=A.opcodes,this.order=A.order,this.strings=e,this.values=Object.create(null)}setByKey(A,e){if(!(A in this.keyToNameMap))return!1;if(0===e.length)return!0;for(const t of e)if(isNaN(t))return N(`Invalid CFFDict value: "${e}" for key "${A}".`),!0;const t=this.types[A];return"num"!==t&&"sid"!==t&&"offset"!==t||(e=e[0]),this.values[A]=e,!0}setByName(A,e){if(!(A in this.nameToKeyMap))throw new T(`Invalid dictionary name "${A}"`);this.values[this.nameToKeyMap[A]]=e}hasName(A){return this.nameToKeyMap[A]in this.values}getByName(A){if(!(A in this.nameToKeyMap))throw new T(`Invalid dictionary name ${A}"`);const e=this.nameToKeyMap[A];return e in this.values?this.values[e]:this.defaults[e]}removeByName(A){delete this.values[this.nameToKeyMap[A]]}static createTables(A){const e={keyToNameMap:{},nameToKeyMap:{},defaults:{},types:{},opcodes:{},order:[]};for(const t of A){const A=Array.isArray(t[0])?(t[0][0]<<8)+t[0][1]:t[0];e.keyToNameMap[A]=t[1],e.nameToKeyMap[t[1]]=A,e.types[A]=t[2],e.defaults[A]=t[3],e.opcodes[A]=Array.isArray(t[0])?t[0]:[t[0]],e.order.push(A)}return e}}const Vi=[[[12,30],"ROS",["sid","sid","num"],null],[[12,20],"SyntheticBase","num",null],[0,"version","sid",null],[1,"Notice","sid",null],[[12,0],"Copyright","sid",null],[2,"FullName","sid",null],[3,"FamilyName","sid",null],[4,"Weight","sid",null],[[12,1],"isFixedPitch","num",0],[[12,2],"ItalicAngle","num",0],[[12,3],"UnderlinePosition","num",-100],[[12,4],"UnderlineThickness","num",50],[[12,5],"PaintType","num",0],[[12,6],"CharstringType","num",2],[[12,7],"FontMatrix",["num","num","num","num","num","num"],[.001,0,0,.001,0,0]],[13,"UniqueID","num",null],[5,"FontBBox",["num","num","num","num"],[0,0,0,0]],[[12,8],"StrokeWidth","num",0],[14,"XUID","array",null],[15,"charset","offset",0],[16,"Encoding","offset",0],[17,"CharStrings","offset",0],[18,"Private",["offset","offset"],null],[[12,21],"PostScript","sid",null],[[12,22],"BaseFontName","sid",null],[[12,23],"BaseFontBlend","delta",null],[[12,31],"CIDFontVersion","num",0],[[12,32],"CIDFontRevision","num",0],[[12,33],"CIDFontType","num",0],[[12,34],"CIDCount","num",8720],[[12,35],"UIDBase","num",null],[[12,37],"FDSelect","offset",null],[[12,36],"FDArray","offset",null],[[12,38],"FontName","sid",null]];class ji extends Xi{static get tables(){return L(this,"tables",this.createTables(Vi))}constructor(A){super(ji.tables,A),this.privateDict=null}}const zi=[[6,"BlueValues","delta",null],[7,"OtherBlues","delta",null],[8,"FamilyBlues","delta",null],[9,"FamilyOtherBlues","delta",null],[[12,9],"BlueScale","num",.039625],[[12,10],"BlueShift","num",7],[[12,11],"BlueFuzz","num",1],[10,"StdHW","num",null],[11,"StdVW","num",null],[[12,12],"StemSnapH","delta",null],[[12,13],"StemSnapV","delta",null],[[12,14],"ForceBold","num",0],[[12,17],"LanguageGroup","num",0],[[12,18],"ExpansionFactor","num",.06],[[12,19],"initialRandomSeed","num",0],[20,"defaultWidthX","num",0],[21,"nominalWidthX","num",0],[19,"Subrs","offset",null]];class _i extends Xi{static get tables(){return L(this,"tables",this.createTables(zi))}constructor(A){super(_i.tables,A),this.subrsIndex=null}}const $i={ISO_ADOBE:0,EXPERT:1,EXPERT_SUBSET:2};class Aa{constructor(A,e,t,i){this.predefined=A,this.format=e,this.charset=t,this.raw=i}}class ea{constructor(A,e,t,i){this.predefined=A,this.format=e,this.encoding=t,this.raw=i}}class ta{constructor(A,e){this.format=A,this.fdSelect=e}getFDIndex(A){return A<0||A>=this.fdSelect.length?-1:this.fdSelect[A]}}class ia{constructor(){this.offsets=Object.create(null)}isTracking(A){return A in this.offsets}track(A,e){if(A in this.offsets)throw new T(`Already tracking location of ${A}`);this.offsets[A]=e}offset(A){for(const e in this.offsets)this.offsets[e]+=A}setEntryLocation(A,e,t){if(!(A in this.offsets))throw new T(`Not tracking location of ${A}`);const i=t.data,a=this.offsets[A];for(let A=0,t=e.length;A>24&255,i[n]=o>>16&255,i[g]=o>>8&255,i[r]=255&o}}}class aa{constructor(A){this.cff=A}compile(){const A=this.cff,e={data:[],length:0,add(A){try{this.data.push(...A)}catch{this.data=this.data.concat(A)}this.length=this.data.length}},t=this.compileHeader(A.header);e.add(t);const i=this.compileNameIndex(A.names);if(e.add(i),A.isCIDFont&&A.topDict.hasName("FontMatrix")){const e=A.topDict.getByName("FontMatrix");A.topDict.removeByName("FontMatrix");for(const t of A.fdArray){let A=e.slice(0);t.hasName("FontMatrix")&&(A=z.transform(A,t.getByName("FontMatrix"))),t.setByName("FontMatrix",A)}}const a=A.topDict.getByName("XUID");a?.length>16&&A.topDict.removeByName("XUID"),A.topDict.setByName("charset",0);let s=this.compileTopDicts([A.topDict],e.length,A.isCIDFont);e.add(s.output);const n=s.trackers[0],g=this.compileStringIndex(A.strings.strings);e.add(g);const r=this.compileIndex(A.globalSubrIndex);if(e.add(r),A.encoding&&A.topDict.hasName("Encoding"))if(A.encoding.predefined)n.setEntryLocation("Encoding",[A.encoding.format],e);else{const t=this.compileEncoding(A.encoding);n.setEntryLocation("Encoding",[e.length],e),e.add(t)}const o=this.compileCharset(A.charset,A.charStrings.count,A.strings,A.isCIDFont);n.setEntryLocation("charset",[e.length],e),e.add(o);const I=this.compileCharStrings(A.charStrings);if(n.setEntryLocation("CharStrings",[e.length],e),e.add(I),A.isCIDFont){n.setEntryLocation("FDSelect",[e.length],e);const t=this.compileFDSelect(A.fdSelect);e.add(t),s=this.compileTopDicts(A.fdArray,e.length,!0),n.setEntryLocation("FDArray",[e.length],e),e.add(s.output);const i=s.trackers;this.compilePrivateDicts(A.fdArray,i,e)}return this.compilePrivateDicts([A.topDict],[n],e),e.add([0]),e.data}encodeNumber(A){return Number.isInteger(A)?this.encodeInteger(A):this.encodeFloat(A)}static get EncodeFloatRegExp(){return L(this,"EncodeFloatRegExp",/\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/)}encodeFloat(A){let e=A.toString();const t=aa.EncodeFloatRegExp.exec(e);if(t){const i=parseFloat("1e"+((t[2]?+t[2]:0)+t[1].length));e=(Math.round(A*i)/i).toString()}let i,a,s="";for(i=0,a=e.length;i=-107&&A<=107?[A+139]:A>=108&&A<=1131?[247+((A-=108)>>8),255&A]:A>=-1131&&A<=-108?[251+((A=-A-108)>>8),255&A]:A>=-32768&&A<=32767?[28,A>>8&255,255&A]:[29,A>>24&255,A>>16&255,A>>8&255,255&A],e}compileHeader(A){return[A.major,A.minor,4,A.offSize]}compileNameIndex(A){const e=new Oi;for(const t of A){const A=Math.min(t.length,127);let i=new Array(A);for(let e=0;e"~"||"["===A||"]"===A||"("===A||")"===A||"{"===A||"}"===A||"<"===A||">"===A||"/"===A||"%"===A)&&(A="_"),i[e]=A}i=i.join(""),""===i&&(i="Bad_Font_Name"),e.add(Z(i))}return this.compileIndex(e)}compileTopDicts(A,e,t){const i=[];let a=new Oi;for(const s of A){t&&(s.removeByName("CIDFontVersion"),s.removeByName("CIDFontRevision"),s.removeByName("CIDFontType"),s.removeByName("CIDCount"),s.removeByName("UIDBase"));const A=new ia,n=this.compileDict(s,A);i.push(A),a.add(n),A.offset(e)}return a=this.compileIndex(a,i),{trackers:i,output:a}}compilePrivateDicts(A,e,t){for(let i=0,a=A.length;i>8&255,255&s]);else{a=new Uint8Array(1+2*s),a[0]=0;let e=0;const i=A.charset.length;let n=!1;for(let s=1;s>8&255,a[s+1]=255&g}}return this.compileTypedArray(a)}compileEncoding(A){return this.compileTypedArray(A.raw)}compileFDSelect(A){const e=A.format;let t,i;switch(e){case 0:for(t=new Uint8Array(1+A.fdSelect.length),t[0]=e,i=0;i>8&255,255&a,s];for(i=1;i>8&255,255&i,e),s=e)}const g=(n.length-3)/3;n[1]=g>>8&255,n[2]=255&g,n.push(i>>8&255,255&i),t=new Uint8Array(n)}return this.compileTypedArray(t)}compileTypedArray(A){return Array.from(A)}compileIndex(A,e=[]){const t=A.objects,i=t.length;if(0===i)return[0,0];const a=[i>>8&255,255&i];let s,n,g=1;for(s=0;s>8&255,255&r):3===n?a.push(r>>16&255,r>>8&255,255&r):a.push(r>>>24&255,r>>16&255,r>>8&255,255&r),t[s]&&(r+=t[s].length);for(s=0;s=5&&e<=7))return-1;i=A.substring(1)}if(i===i.toUpperCase()&&(t=parseInt(i,16),t>=0))return t}return-1}const oa=[[0,127],[128,255],[256,383],[384,591],[592,687,7424,7551,7552,7615],[688,767,42752,42783],[768,879,7616,7679],[880,1023],[11392,11519],[1024,1279,1280,1327,11744,11775,42560,42655],[1328,1423],[1424,1535],[42240,42559],[1536,1791,1872,1919],[1984,2047],[2304,2431],[2432,2559],[2560,2687],[2688,2815],[2816,2943],[2944,3071],[3072,3199],[3200,3327],[3328,3455],[3584,3711],[3712,3839],[4256,4351,11520,11567],[6912,7039],[4352,4607],[7680,7935,11360,11391,42784,43007],[7936,8191],[8192,8303,11776,11903],[8304,8351],[8352,8399],[8400,8447],[8448,8527],[8528,8591],[8592,8703,10224,10239,10496,10623,11008,11263],[8704,8959,10752,11007,10176,10223,10624,10751],[8960,9215],[9216,9279],[9280,9311],[9312,9471],[9472,9599],[9600,9631],[9632,9727],[9728,9983],[9984,10175],[12288,12351],[12352,12447],[12448,12543,12784,12799],[12544,12591,12704,12735],[12592,12687],[43072,43135],[12800,13055],[13056,13311],[44032,55215],[55296,57343],[67840,67871],[19968,40959,11904,12031,12032,12255,12272,12287,13312,19903,131072,173791,12688,12703],[57344,63743],[12736,12783,63744,64255,194560,195103],[64256,64335],[64336,65023],[65056,65071],[65040,65055],[65104,65135],[65136,65279],[65280,65519],[65520,65535],[3840,4095],[1792,1871],[1920,1983],[3456,3583],[4096,4255],[4608,4991,4992,5023,11648,11743],[5024,5119],[5120,5759],[5760,5791],[5792,5887],[6016,6143],[6144,6319],[10240,10495],[40960,42127],[5888,5919,5920,5951,5952,5983,5984,6015],[66304,66351],[66352,66383],[66560,66639],[118784,119039,119040,119295,119296,119375],[119808,120831],[1044480,1048573],[65024,65039,917760,917999],[917504,917631],[6400,6479],[6480,6527],[6528,6623],[6656,6687],[11264,11359],[11568,11647],[19904,19967],[43008,43055],[65536,65663,65664,65791,65792,65855],[65856,65935],[66432,66463],[66464,66527],[66640,66687],[66688,66735],[67584,67647],[68096,68191],[119552,119647],[73728,74751,74752,74879],[119648,119679],[7040,7103],[7168,7247],[7248,7295],[43136,43231],[43264,43311],[43312,43359],[43520,43615],[65936,65999],[66e3,66047],[66208,66271,66176,66207,67872,67903],[127024,127135,126976,127023]];function Ia(A,e=-1){if(-1!==e){const t=oa[e];for(let i=0,a=t.length;i=t[i]&&A<=t[i+1])return e}for(let e=0,t=oa.length;e=t[i]&&A<=t[i+1])return e}return-1}const ca=new RegExp("^(\\s)|(\\p{Mn})|(\\p{Cf})$","u"),Ca=new Map,Ba=!0,ha=[".notdef",".null","nonmarkingreturn","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quotesingle","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","grave","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","Adieresis","Aring","Ccedilla","Eacute","Ntilde","Odieresis","Udieresis","aacute","agrave","acircumflex","adieresis","atilde","aring","ccedilla","eacute","egrave","ecircumflex","edieresis","iacute","igrave","icircumflex","idieresis","ntilde","oacute","ograve","ocircumflex","odieresis","otilde","uacute","ugrave","ucircumflex","udieresis","dagger","degree","cent","sterling","section","bullet","paragraph","germandbls","registered","copyright","trademark","acute","dieresis","notequal","AE","Oslash","infinity","plusminus","lessequal","greaterequal","yen","mu","partialdiff","summation","product","pi","integral","ordfeminine","ordmasculine","Omega","ae","oslash","questiondown","exclamdown","logicalnot","radical","florin","approxequal","Delta","guillemotleft","guillemotright","ellipsis","nonbreakingspace","Agrave","Atilde","Otilde","OE","oe","endash","emdash","quotedblleft","quotedblright","quoteleft","quoteright","divide","lozenge","ydieresis","Ydieresis","fraction","currency","guilsinglleft","guilsinglright","fi","fl","daggerdbl","periodcentered","quotesinglbase","quotedblbase","perthousand","Acircumflex","Ecircumflex","Aacute","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Oacute","Ocircumflex","apple","Ograve","Uacute","Ucircumflex","Ugrave","dotlessi","circumflex","tilde","macron","breve","dotaccent","ring","cedilla","hungarumlaut","ogonek","caron","Lslash","lslash","Scaron","scaron","Zcaron","zcaron","brokenbar","Eth","eth","Yacute","yacute","Thorn","thorn","minus","multiply","onesuperior","twosuperior","threesuperior","onehalf","onequarter","threequarters","franc","Gbreve","gbreve","Idotaccent","Scedilla","scedilla","Cacute","cacute","Ccaron","ccaron","dcroat"];function Qa(A,e){if(void 0!==e[A])return A;const t=ra(A,e);if(-1!==t)for(const A in e)if(e[A]===t)return A;return G("Unable to recover a standard glyph name for: "+A),A}function la(A,e,t){const i=Object.create(null);let a,s,n;const g=!!(4&A.flags);if(A.isInternalFont)for(n=e,s=0;s=0?a:0;else if(A.baseEncodingName)for(n=Yi(A.baseEncodingName),s=0;s=0?a:0;else if(g)for(s in e)i[s]=e[s];else for(n=Mi,s=0;s=0?a:0;const r=A.differences;let o;if(r)for(s in r){const A=r[s];if(a=t.indexOf(A),-1===a){o||(o=sa());const e=Qa(A,o);e!==A&&(a=t.indexOf(e))}i[s]=a>=0?a:0}return i}function Ea(A){return A.replaceAll(/[,_]/g,"-").replaceAll(/\s/g,"")}const ua=wA((A=>{A[8211]=65074,A[8212]=65073,A[8229]=65072,A[8230]=65049,A[12289]=65041,A[12290]=65042,A[12296]=65087,A[12297]=65088,A[12298]=65085,A[12299]=65086,A[12300]=65089,A[12301]=65090,A[12302]=65091,A[12303]=65092,A[12304]=65083,A[12305]=65084,A[12308]=65081,A[12309]=65082,A[12310]=65047,A[12311]=65048,A[65103]=65076,A[65281]=65045,A[65288]=65077,A[65289]=65078,A[65292]=65040,A[65306]=65043,A[65307]=65044,A[65311]=65046,A[65339]=65095,A[65341]=65096,A[65343]=65075,A[65371]=65079,A[65373]=65080})),da=wA((function(A){A["Times-Roman"]="Times-Roman",A.Helvetica="Helvetica",A.Courier="Courier",A.Symbol="Symbol",A["Times-Bold"]="Times-Bold",A["Helvetica-Bold"]="Helvetica-Bold",A["Courier-Bold"]="Courier-Bold",A.ZapfDingbats="ZapfDingbats",A["Times-Italic"]="Times-Italic",A["Helvetica-Oblique"]="Helvetica-Oblique",A["Courier-Oblique"]="Courier-Oblique",A["Times-BoldItalic"]="Times-BoldItalic",A["Helvetica-BoldOblique"]="Helvetica-BoldOblique",A["Courier-BoldOblique"]="Courier-BoldOblique",A.ArialNarrow="Helvetica",A["ArialNarrow-Bold"]="Helvetica-Bold",A["ArialNarrow-BoldItalic"]="Helvetica-BoldOblique",A["ArialNarrow-Italic"]="Helvetica-Oblique",A.ArialBlack="Helvetica",A["ArialBlack-Bold"]="Helvetica-Bold",A["ArialBlack-BoldItalic"]="Helvetica-BoldOblique",A["ArialBlack-Italic"]="Helvetica-Oblique",A["Arial-Black"]="Helvetica",A["Arial-Black-Bold"]="Helvetica-Bold",A["Arial-Black-BoldItalic"]="Helvetica-BoldOblique",A["Arial-Black-Italic"]="Helvetica-Oblique",A.Arial="Helvetica",A["Arial-Bold"]="Helvetica-Bold",A["Arial-BoldItalic"]="Helvetica-BoldOblique",A["Arial-Italic"]="Helvetica-Oblique",A.ArialMT="Helvetica",A["Arial-BoldItalicMT"]="Helvetica-BoldOblique",A["Arial-BoldMT"]="Helvetica-Bold",A["Arial-ItalicMT"]="Helvetica-Oblique",A["Arial-BoldItalicMT-BoldItalic"]="Helvetica-BoldOblique",A["Arial-BoldMT-Bold"]="Helvetica-Bold",A["Arial-ItalicMT-Italic"]="Helvetica-Oblique",A.ArialUnicodeMS="Helvetica",A["ArialUnicodeMS-Bold"]="Helvetica-Bold",A["ArialUnicodeMS-BoldItalic"]="Helvetica-BoldOblique",A["ArialUnicodeMS-Italic"]="Helvetica-Oblique",A["Courier-BoldItalic"]="Courier-BoldOblique",A["Courier-Italic"]="Courier-Oblique",A.CourierNew="Courier",A["CourierNew-Bold"]="Courier-Bold",A["CourierNew-BoldItalic"]="Courier-BoldOblique",A["CourierNew-Italic"]="Courier-Oblique",A["CourierNewPS-BoldItalicMT"]="Courier-BoldOblique",A["CourierNewPS-BoldMT"]="Courier-Bold",A["CourierNewPS-ItalicMT"]="Courier-Oblique",A.CourierNewPSMT="Courier",A["Helvetica-BoldItalic"]="Helvetica-BoldOblique",A["Helvetica-Italic"]="Helvetica-Oblique",A["Symbol-Bold"]="Symbol",A["Symbol-BoldItalic"]="Symbol",A["Symbol-Italic"]="Symbol",A.TimesNewRoman="Times-Roman",A["TimesNewRoman-Bold"]="Times-Bold",A["TimesNewRoman-BoldItalic"]="Times-BoldItalic",A["TimesNewRoman-Italic"]="Times-Italic",A.TimesNewRomanPS="Times-Roman",A["TimesNewRomanPS-Bold"]="Times-Bold",A["TimesNewRomanPS-BoldItalic"]="Times-BoldItalic",A["TimesNewRomanPS-BoldItalicMT"]="Times-BoldItalic",A["TimesNewRomanPS-BoldMT"]="Times-Bold",A["TimesNewRomanPS-Italic"]="Times-Italic",A["TimesNewRomanPS-ItalicMT"]="Times-Italic",A.TimesNewRomanPSMT="Times-Roman",A["TimesNewRomanPSMT-Bold"]="Times-Bold",A["TimesNewRomanPSMT-BoldItalic"]="Times-BoldItalic",A["TimesNewRomanPSMT-Italic"]="Times-Italic"})),fa=wA((function(A){A.Courier="FoxitFixed.pfb",A["Courier-Bold"]="FoxitFixedBold.pfb",A["Courier-BoldOblique"]="FoxitFixedBoldItalic.pfb",A["Courier-Oblique"]="FoxitFixedItalic.pfb",A.Helvetica="LiberationSans-Regular.ttf",A["Helvetica-Bold"]="LiberationSans-Bold.ttf",A["Helvetica-BoldOblique"]="LiberationSans-BoldItalic.ttf",A["Helvetica-Oblique"]="LiberationSans-Italic.ttf",A["Times-Roman"]="FoxitSerif.pfb",A["Times-Bold"]="FoxitSerifBold.pfb",A["Times-BoldItalic"]="FoxitSerifBoldItalic.pfb",A["Times-Italic"]="FoxitSerifItalic.pfb",A.Symbol="FoxitSymbol.pfb",A.ZapfDingbats="FoxitDingbats.pfb",A["LiberationSans-Regular"]="LiberationSans-Regular.ttf",A["LiberationSans-Bold"]="LiberationSans-Bold.ttf",A["LiberationSans-Italic"]="LiberationSans-Italic.ttf",A["LiberationSans-BoldItalic"]="LiberationSans-BoldItalic.ttf"})),pa=wA((function(A){A.Calibri="Helvetica",A["Calibri-Bold"]="Helvetica-Bold",A["Calibri-BoldItalic"]="Helvetica-BoldOblique",A["Calibri-Italic"]="Helvetica-Oblique",A.CenturyGothic="Helvetica",A["CenturyGothic-Bold"]="Helvetica-Bold",A["CenturyGothic-BoldItalic"]="Helvetica-BoldOblique",A["CenturyGothic-Italic"]="Helvetica-Oblique",A.ComicSansMS="Comic Sans MS",A["ComicSansMS-Bold"]="Comic Sans MS-Bold",A["ComicSansMS-BoldItalic"]="Comic Sans MS-BoldItalic",A["ComicSansMS-Italic"]="Comic Sans MS-Italic",A.GillSansMT="Helvetica",A["GillSansMT-Bold"]="Helvetica-Bold",A["GillSansMT-BoldItalic"]="Helvetica-BoldOblique",A["GillSansMT-Italic"]="Helvetica-Oblique",A.Impact="Helvetica",A["ItcSymbol-Bold"]="Helvetica-Bold",A["ItcSymbol-BoldItalic"]="Helvetica-BoldOblique",A["ItcSymbol-Book"]="Helvetica",A["ItcSymbol-BookItalic"]="Helvetica-Oblique",A["ItcSymbol-Medium"]="Helvetica",A["ItcSymbol-MediumItalic"]="Helvetica-Oblique",A.LucidaConsole="Courier",A["LucidaConsole-Bold"]="Courier-Bold",A["LucidaConsole-BoldItalic"]="Courier-BoldOblique",A["LucidaConsole-Italic"]="Courier-Oblique",A["LucidaSans-Demi"]="Helvetica-Bold",A["MS-Gothic"]="MS Gothic",A["MS-Gothic-Bold"]="MS Gothic-Bold",A["MS-Gothic-BoldItalic"]="MS Gothic-BoldItalic",A["MS-Gothic-Italic"]="MS Gothic-Italic",A["MS-Mincho"]="MS Mincho",A["MS-Mincho-Bold"]="MS Mincho-Bold",A["MS-Mincho-BoldItalic"]="MS Mincho-BoldItalic",A["MS-Mincho-Italic"]="MS Mincho-Italic",A["MS-PGothic"]="MS PGothic",A["MS-PGothic-Bold"]="MS PGothic-Bold",A["MS-PGothic-BoldItalic"]="MS PGothic-BoldItalic",A["MS-PGothic-Italic"]="MS PGothic-Italic",A["MS-PMincho"]="MS PMincho",A["MS-PMincho-Bold"]="MS PMincho-Bold",A["MS-PMincho-BoldItalic"]="MS PMincho-BoldItalic",A["MS-PMincho-Italic"]="MS PMincho-Italic",A.NuptialScript="Times-Italic",A.SegoeUISymbol="Helvetica"})),ma=wA((function(A){A["Adobe Jenson"]=!0,A["Adobe Text"]=!0,A.Albertus=!0,A.Aldus=!0,A.Alexandria=!0,A.Algerian=!0,A["American Typewriter"]=!0,A.Antiqua=!0,A.Apex=!0,A.Arno=!0,A.Aster=!0,A.Aurora=!0,A.Baskerville=!0,A.Bell=!0,A.Bembo=!0,A["Bembo Schoolbook"]=!0,A.Benguiat=!0,A["Berkeley Old Style"]=!0,A["Bernhard Modern"]=!0,A["Berthold City"]=!0,A.Bodoni=!0,A["Bauer Bodoni"]=!0,A["Book Antiqua"]=!0,A.Bookman=!0,A["Bordeaux Roman"]=!0,A["Californian FB"]=!0,A.Calisto=!0,A.Calvert=!0,A.Capitals=!0,A.Cambria=!0,A.Cartier=!0,A.Caslon=!0,A.Catull=!0,A.Centaur=!0,A["Century Old Style"]=!0,A["Century Schoolbook"]=!0,A.Chaparral=!0,A["Charis SIL"]=!0,A.Cheltenham=!0,A["Cholla Slab"]=!0,A.Clarendon=!0,A.Clearface=!0,A.Cochin=!0,A.Colonna=!0,A["Computer Modern"]=!0,A["Concrete Roman"]=!0,A.Constantia=!0,A["Cooper Black"]=!0,A.Corona=!0,A.Ecotype=!0,A.Egyptienne=!0,A.Elephant=!0,A.Excelsior=!0,A.Fairfield=!0,A["FF Scala"]=!0,A.Folkard=!0,A.Footlight=!0,A.FreeSerif=!0,A["Friz Quadrata"]=!0,A.Garamond=!0,A.Gentium=!0,A.Georgia=!0,A.Gloucester=!0,A["Goudy Old Style"]=!0,A["Goudy Schoolbook"]=!0,A["Goudy Pro Font"]=!0,A.Granjon=!0,A["Guardian Egyptian"]=!0,A.Heather=!0,A.Hercules=!0,A["High Tower Text"]=!0,A.Hiroshige=!0,A["Hoefler Text"]=!0,A["Humana Serif"]=!0,A.Imprint=!0,A["Ionic No. 5"]=!0,A.Janson=!0,A.Joanna=!0,A.Korinna=!0,A.Lexicon=!0,A.LiberationSerif=!0,A["Liberation Serif"]=!0,A["Linux Libertine"]=!0,A.Literaturnaya=!0,A.Lucida=!0,A["Lucida Bright"]=!0,A.Melior=!0,A.Memphis=!0,A.Miller=!0,A.Minion=!0,A.Modern=!0,A["Mona Lisa"]=!0,A["Mrs Eaves"]=!0,A["MS Serif"]=!0,A["Museo Slab"]=!0,A["New York"]=!0,A["Nimbus Roman"]=!0,A["NPS Rawlinson Roadway"]=!0,A.NuptialScript=!0,A.Palatino=!0,A.Perpetua=!0,A.Plantin=!0,A["Plantin Schoolbook"]=!0,A.Playbill=!0,A["Poor Richard"]=!0,A["Rawlinson Roadway"]=!0,A.Renault=!0,A.Requiem=!0,A.Rockwell=!0,A.Roman=!0,A["Rotis Serif"]=!0,A.Sabon=!0,A.Scala=!0,A.Seagull=!0,A.Sistina=!0,A.Souvenir=!0,A.STIX=!0,A["Stone Informal"]=!0,A["Stone Serif"]=!0,A.Sylfaen=!0,A.Times=!0,A.Trajan=!0,A["Trinité"]=!0,A["Trump Mediaeval"]=!0,A.Utopia=!0,A["Vale Type"]=!0,A["Bitstream Vera"]=!0,A["Vera Serif"]=!0,A.Versailles=!0,A.Wanted=!0,A.Weiss=!0,A["Wide Latin"]=!0,A.Windsor=!0,A.XITS=!0})),ya=wA((function(A){A.Dingbats=!0,A.Symbol=!0,A.ZapfDingbats=!0,A.Wingdings=!0,A["Wingdings-Bold"]=!0,A["Wingdings-Regular"]=!0})),wa=wA((function(A){A[2]=10,A[3]=32,A[4]=33,A[5]=34,A[6]=35,A[7]=36,A[8]=37,A[9]=38,A[10]=39,A[11]=40,A[12]=41,A[13]=42,A[14]=43,A[15]=44,A[16]=45,A[17]=46,A[18]=47,A[19]=48,A[20]=49,A[21]=50,A[22]=51,A[23]=52,A[24]=53,A[25]=54,A[26]=55,A[27]=56,A[28]=57,A[29]=58,A[30]=894,A[31]=60,A[32]=61,A[33]=62,A[34]=63,A[35]=64,A[36]=65,A[37]=66,A[38]=67,A[39]=68,A[40]=69,A[41]=70,A[42]=71,A[43]=72,A[44]=73,A[45]=74,A[46]=75,A[47]=76,A[48]=77,A[49]=78,A[50]=79,A[51]=80,A[52]=81,A[53]=82,A[54]=83,A[55]=84,A[56]=85,A[57]=86,A[58]=87,A[59]=88,A[60]=89,A[61]=90,A[62]=91,A[63]=92,A[64]=93,A[65]=94,A[66]=95,A[67]=96,A[68]=97,A[69]=98,A[70]=99,A[71]=100,A[72]=101,A[73]=102,A[74]=103,A[75]=104,A[76]=105,A[77]=106,A[78]=107,A[79]=108,A[80]=109,A[81]=110,A[82]=111,A[83]=112,A[84]=113,A[85]=114,A[86]=115,A[87]=116,A[88]=117,A[89]=118,A[90]=119,A[91]=120,A[92]=121,A[93]=122,A[94]=123,A[95]=124,A[96]=125,A[97]=126,A[98]=196,A[99]=197,A[100]=199,A[101]=201,A[102]=209,A[103]=214,A[104]=220,A[105]=225,A[106]=224,A[107]=226,A[108]=228,A[109]=227,A[110]=229,A[111]=231,A[112]=233,A[113]=232,A[114]=234,A[115]=235,A[116]=237,A[117]=236,A[118]=238,A[119]=239,A[120]=241,A[121]=243,A[122]=242,A[123]=244,A[124]=246,A[125]=245,A[126]=250,A[127]=249,A[128]=251,A[129]=252,A[130]=8224,A[131]=176,A[132]=162,A[133]=163,A[134]=167,A[135]=8226,A[136]=182,A[137]=223,A[138]=174,A[139]=169,A[140]=8482,A[141]=180,A[142]=168,A[143]=8800,A[144]=198,A[145]=216,A[146]=8734,A[147]=177,A[148]=8804,A[149]=8805,A[150]=165,A[151]=181,A[152]=8706,A[153]=8721,A[154]=8719,A[156]=8747,A[157]=170,A[158]=186,A[159]=8486,A[160]=230,A[161]=248,A[162]=191,A[163]=161,A[164]=172,A[165]=8730,A[166]=402,A[167]=8776,A[168]=8710,A[169]=171,A[170]=187,A[171]=8230,A[179]=8220,A[180]=8221,A[181]=8216,A[182]=8217,A[200]=193,A[203]=205,A[207]=211,A[210]=218,A[223]=711,A[224]=321,A[225]=322,A[226]=352,A[227]=353,A[228]=381,A[229]=382,A[233]=221,A[234]=253,A[252]=263,A[253]=268,A[254]=269,A[258]=258,A[260]=260,A[261]=261,A[265]=280,A[266]=281,A[267]=282,A[268]=283,A[269]=313,A[275]=323,A[276]=324,A[278]=328,A[283]=344,A[284]=345,A[285]=346,A[286]=347,A[292]=367,A[295]=377,A[296]=378,A[298]=380,A[305]=963,A[306]=964,A[307]=966,A[308]=8215,A[309]=8252,A[310]=8319,A[311]=8359,A[312]=8592,A[313]=8593,A[337]=9552,A[493]=1039,A[494]=1040,A[672]=1488,A[673]=1489,A[674]=1490,A[675]=1491,A[676]=1492,A[677]=1493,A[678]=1494,A[679]=1495,A[680]=1496,A[681]=1497,A[682]=1498,A[683]=1499,A[684]=1500,A[685]=1501,A[686]=1502,A[687]=1503,A[688]=1504,A[689]=1505,A[690]=1506,A[691]=1507,A[692]=1508,A[693]=1509,A[694]=1510,A[695]=1511,A[696]=1512,A[697]=1513,A[698]=1514,A[705]=1524,A[706]=8362,A[710]=64288,A[711]=64298,A[759]=1617,A[761]=1776,A[763]=1778,A[775]=1652,A[777]=1764,A[778]=1780,A[779]=1781,A[780]=1782,A[782]=771,A[783]=64726,A[786]=8363,A[788]=8532,A[790]=768,A[791]=769,A[792]=768,A[795]=803,A[797]=64336,A[798]=64337,A[799]=64342,A[800]=64343,A[801]=64344,A[802]=64345,A[803]=64362,A[804]=64363,A[805]=64364,A[2424]=7821,A[2425]=7822,A[2426]=7823,A[2427]=7824,A[2428]=7825,A[2429]=7826,A[2430]=7827,A[2433]=7682,A[2678]=8045,A[2679]=8046,A[2830]=1552,A[2838]=686,A[2840]=751,A[2842]=753,A[2843]=754,A[2844]=755,A[2846]=757,A[2856]=767,A[2857]=848,A[2858]=849,A[2862]=853,A[2863]=854,A[2864]=855,A[2865]=861,A[2866]=862,A[2906]=7460,A[2908]=7462,A[2909]=7463,A[2910]=7464,A[2912]=7466,A[2913]=7467,A[2914]=7468,A[2916]=7470,A[2917]=7471,A[2918]=7472,A[2920]=7474,A[2921]=7475,A[2922]=7476,A[2924]=7478,A[2925]=7479,A[2926]=7480,A[2928]=7482,A[2929]=7483,A[2930]=7484,A[2932]=7486,A[2933]=7487,A[2934]=7488,A[2936]=7490,A[2937]=7491,A[2938]=7492,A[2940]=7494,A[2941]=7495,A[2942]=7496,A[2944]=7498,A[2946]=7500,A[2948]=7502,A[2950]=7504,A[2951]=7505,A[2952]=7506,A[2954]=7508,A[2955]=7509,A[2956]=7510,A[2958]=7512,A[2959]=7513,A[2960]=7514,A[2962]=7516,A[2963]=7517,A[2964]=7518,A[2966]=7520,A[2967]=7521,A[2968]=7522,A[2970]=7524,A[2971]=7525,A[2972]=7526,A[2974]=7528,A[2975]=7529,A[2976]=7530,A[2978]=1537,A[2979]=1538,A[2980]=1539,A[2982]=1549,A[2983]=1551,A[2984]=1552,A[2986]=1554,A[2987]=1555,A[2988]=1556,A[2990]=1623,A[2991]=1624,A[2995]=1775,A[2999]=1791,A[3002]=64290,A[3003]=64291,A[3004]=64292,A[3006]=64294,A[3007]=64295,A[3008]=64296,A[3011]=1900,A[3014]=8223,A[3015]=8244,A[3017]=7532,A[3018]=7533,A[3019]=7534,A[3075]=7590,A[3076]=7591,A[3079]=7594,A[3080]=7595,A[3083]=7598,A[3084]=7599,A[3087]=7602,A[3088]=7603,A[3091]=7606,A[3092]=7607,A[3095]=7610,A[3096]=7611,A[3099]=7614,A[3100]=7615,A[3103]=7618,A[3104]=7619,A[3107]=8337,A[3108]=8338,A[3116]=1884,A[3119]=1885,A[3120]=1885,A[3123]=1886,A[3124]=1886,A[3127]=1887,A[3128]=1887,A[3131]=1888,A[3132]=1888,A[3135]=1889,A[3136]=1889,A[3139]=1890,A[3140]=1890,A[3143]=1891,A[3144]=1891,A[3147]=1892,A[3148]=1892,A[3153]=580,A[3154]=581,A[3157]=584,A[3158]=585,A[3161]=588,A[3162]=589,A[3165]=891,A[3166]=892,A[3169]=1274,A[3170]=1275,A[3173]=1278,A[3174]=1279,A[3181]=7622,A[3182]=7623,A[3282]=11799,A[3316]=578,A[3379]=42785,A[3393]=1159,A[3416]=8377})),Da=wA((function(A){A[227]=322,A[264]=261,A[291]=346})),ba=wA((function(A){A[1]=32,A[4]=65,A[5]=192,A[6]=193,A[9]=196,A[17]=66,A[18]=67,A[21]=268,A[24]=68,A[28]=69,A[29]=200,A[30]=201,A[32]=282,A[38]=70,A[39]=71,A[44]=72,A[47]=73,A[48]=204,A[49]=205,A[58]=74,A[60]=75,A[62]=76,A[68]=77,A[69]=78,A[75]=79,A[76]=210,A[80]=214,A[87]=80,A[89]=81,A[90]=82,A[92]=344,A[94]=83,A[97]=352,A[100]=84,A[104]=85,A[109]=220,A[115]=86,A[116]=87,A[121]=88,A[122]=89,A[124]=221,A[127]=90,A[129]=381,A[258]=97,A[259]=224,A[260]=225,A[263]=228,A[268]=261,A[271]=98,A[272]=99,A[273]=263,A[275]=269,A[282]=100,A[286]=101,A[287]=232,A[288]=233,A[290]=283,A[295]=281,A[296]=102,A[336]=103,A[346]=104,A[349]=105,A[350]=236,A[351]=237,A[361]=106,A[364]=107,A[367]=108,A[371]=322,A[373]=109,A[374]=110,A[381]=111,A[382]=242,A[383]=243,A[386]=246,A[393]=112,A[395]=113,A[396]=114,A[398]=345,A[400]=115,A[401]=347,A[403]=353,A[410]=116,A[437]=117,A[442]=252,A[448]=118,A[449]=119,A[454]=120,A[455]=121,A[457]=253,A[460]=122,A[462]=382,A[463]=380,A[853]=44,A[855]=58,A[856]=46,A[876]=47,A[878]=45,A[882]=45,A[894]=40,A[895]=41,A[896]=91,A[897]=93,A[923]=64,A[1004]=48,A[1005]=49,A[1006]=50,A[1007]=51,A[1008]=52,A[1009]=53,A[1010]=54,A[1011]=55,A[1012]=56,A[1013]=57,A[1081]=37,A[1085]=43,A[1086]=45}));function ka(A){const e=Ea(A);return da()[e]}function Fa(A){const e=Ea(A);return!!(da()[e]||pa()[e]||ma()[e]||ya()[e])}class Sa{constructor(A=[]){this._map=A}get length(){return this._map.length}forEach(A){for(const e in this._map)A(e,this._map[e].charCodeAt(0))}has(A){return void 0!==this._map[A]}get(A){return this._map[A]}charCodeOf(A){const e=this._map;if(e.length<=65536)return e.indexOf(A);for(const t in e)if(e[t]===A)return 0|t;return-1}amend(A){for(const e in A)this._map[e]=A[e]}}class Ra{constructor(A,e){this.firstChar=A,this.lastChar=e}get length(){return this.lastChar+1-this.firstChar}forEach(A){for(let e=this.firstChar,t=this.lastChar;e<=t;e++)A(e,e)}has(A){return this.firstChar<=A&&A<=this.lastChar}get(A){if(this.firstChar<=A&&A<=this.lastChar)return String.fromCharCode(A)}charCodeOf(A){return Number.isInteger(A)&&A>=this.firstChar&&A<=this.lastChar?A:-1}amend(A){x("Should not call amend()")}}class Ga{constructor(A,e){this.properties=e;const t=new Ti(A,e,Ba);this.cff=t.parse(),this.cff.duplicateFirstGlyph();const i=new aa(this.cff);this.seacs=this.cff.seacs;try{this.data=i.compile()}catch{N("Failed to compile font "+e.loadedName),this.data=A}this._createBuiltInEncoding()}get numGlyphs(){return this.cff.charStrings.count}getCharset(){return this.cff.charset.charset}getGlyphMapping(){const A=this.cff,e=this.properties,{cidToGidMap:t,cMap:i}=e,a=A.charset.charset;let s,n;if(e.composite){let e,g;if(t?.length>0){e=Object.create(null);for(let A=0,i=t.length;A=0){const i=t[e];i&&(a[A]=i)}}a.length>0&&(this.properties.builtInEncoding=a)}}function Na(A,e){return(A[e]<<24|A[e+1]<<16|A[e+2]<<8|A[e+3])>>>0}function xa(A,e){return A[e]<<8|A[e+1]}function Ua(A,e){return(A[e]<<24|A[e+1]<<16)>>16}function Ma(A,e){return A[e]<<24>>24}function La(A,e){return Ua(A,e)/16384}function Ja(A){const e=A.length;let t=32768;return e<1240?t=107:e<33900&&(t=1131),t}function Ha(A,e,t){const i=1===xa(A,e+2)?Na(A,e+8):Na(A,e+16),a=xa(A,e+i);let s,n,g;if(4===a){xa(A,e+i+2);const t=xa(A,e+i+6)>>1;for(n=e+i+14,s=[],g=0;g>1;t0;)B.push({flags:r})}for(t=0;t>1,m=!0;break;case 4:o+=g.pop(),a(r,o),m=!0;break;case 5:for(;g.length>0;)r+=g.shift(),o+=g.shift(),s(r,o);break;case 6:for(;g.length>0&&(r+=g.shift(),s(r,o),0!==g.length);)o+=g.shift(),s(r,o);break;case 7:for(;g.length>0&&(o+=g.shift(),s(r,o),0!==g.length);)r+=g.shift(),s(r,o);break;case 8:for(;g.length>0;)B=r+g.shift(),Q=o+g.shift(),h=B+g.shift(),l=Q+g.shift(),r=h+g.shift(),o=l+g.shift(),n(B,Q,h,l,r,o);break;case 10:if(f=g.pop(),p=null,t.isCFFCIDFont){const A=t.fdSelect.getFDIndex(i);if(A>=0&&AMath.abs(o-e)?r+=g.shift():o+=g.shift(),n(B,Q,h,l,r,o);break;default:throw new T(`unknown operator: 12 ${y}`)}break;case 14:if(g.length>=4){const A=g.pop(),i=g.pop();o=g.pop(),r=g.pop(),e.add(5),e.add(8,[r,o]);let a=va(t.cmap,String.fromCharCode(t.glyphNameMap[Mi[A]]));qa(t.glyphs[a.glyphId],e,t,a.glyphId),e.add(4),a=va(t.cmap,String.fromCharCode(t.glyphNameMap[Mi[i]])),qa(t.glyphs[a.glyphId],e,t,a.glyphId)}return;case 19:case 20:I+=g.length>>1,C+=I+7>>3,m=!0;break;case 21:o+=g.pop(),r+=g.pop(),a(r,o),m=!0;break;case 22:r+=g.pop(),a(r,o),m=!0;break;case 24:for(;g.length>2;)B=r+g.shift(),Q=o+g.shift(),h=B+g.shift(),l=Q+g.shift(),r=h+g.shift(),o=l+g.shift(),n(B,Q,h,l,r,o);r+=g.shift(),o+=g.shift(),s(r,o);break;case 25:for(;g.length>6;)r+=g.shift(),o+=g.shift(),s(r,o);B=r+g.shift(),Q=o+g.shift(),h=B+g.shift(),l=Q+g.shift(),r=h+g.shift(),o=l+g.shift(),n(B,Q,h,l,r,o);break;case 26:for(g.length%2&&(r+=g.shift());g.length>0;)B=r,Q=o+g.shift(),h=B+g.shift(),l=Q+g.shift(),r=h,o=l+g.shift(),n(B,Q,h,l,r,o);break;case 27:for(g.length%2&&(o+=g.shift());g.length>0;)B=r+g.shift(),Q=o,h=B+g.shift(),l=Q+g.shift(),r=h+g.shift(),o=l,n(B,Q,h,l,r,o);break;case 28:g.push((c[C]<<24|c[C+1]<<16)>>16),C+=2;break;case 29:f=g.pop()+t.gsubrsBias,p=t.gsubrs[f],p&&A(p);break;case 30:for(;g.length>0&&(B=r,Q=o+g.shift(),h=B+g.shift(),l=Q+g.shift(),r=h+g.shift(),o=l+(1===g.length?g.shift():0),n(B,Q,h,l,r,o),0!==g.length);)B=r+g.shift(),Q=o,h=B+g.shift(),l=Q+g.shift(),o=l+g.shift(),r=h+(1===g.length?g.shift():0),n(B,Q,h,l,r,o);break;case 31:for(;g.length>0&&(B=r+g.shift(),Q=o,h=B+g.shift(),l=Q+g.shift(),o=l+g.shift(),r=h+(1===g.length?g.shift():0),n(B,Q,h,l,r,o),0!==g.length);)B=r,Q=o+g.shift(),h=B+g.shift(),l=Q+g.shift(),r=h+g.shift(),o=l+(1===g.length?g.shift():0),n(B,Q,h,l,r,o);break;default:if(y<32)throw new T(`unknown operator: ${y}`);y<247?g.push(y-139):y<251?g.push(256*(y-247)+c[C++]+108):y<255?g.push(256*-(y-251)-c[C++]-108):(g.push((c[C]<<24|c[C+1]<<16|c[C+2]<<8|c[C+3])/65536),C+=4)}m&&(g.length=0)}}(A)}const Ta=[];class Pa{cmds=[];add(A,e){if(e)if(HA(e,null))this.cmds.push(A,...e);else{N(`Commands.add - "${A}" has at least one non-number arg: "${e}".`);const t=e.map((A=>"number"==typeof A?A:0));this.cmds.push(A,...t)}else this.cmds.push(A)}}class Wa{constructor(A){this.fontMatrix=A,this.compiledGlyphs=Object.create(null),this.compiledCharCodeToGlyphId=Object.create(null)}getPathJs(A){const{charCode:e,glyphId:t}=va(this.cmap,A);let i,a=this.compiledGlyphs[t];if(!a){try{a=this.compileGlyph(this.glyphs[t],t)}catch(A){a=Ta,i=A}this.compiledGlyphs[t]=a}if(this.compiledCharCodeToGlyphId[e]??=t,i)throw i;return a}compileGlyph(A,e){if(!A||0===A.length||14===A[0])return Ta;let t=this.fontMatrix;if(this.isCFFCIDFont){const A=this.fdSelect.getFDIndex(e);A>=0&&A2*xa(A,e));const s=[];let n=a(e,0);for(let t=i;tA+(e.getSize()+3&-4)),0)}write(){const A=this.getSize(),e=new DataView(new ArrayBuffer(A)),t=A>131070,i=t?4:2,a=new DataView(new ArrayBuffer((this.glyphs.length+1)*i));t?a.setUint32(0,0):a.setUint16(0,0);let s=0,n=0;for(const A of this.glyphs)s+=A.write(s,e),s=s+3&-4,n+=i,t?a.setUint32(n,s):a.setUint16(n,s>>1);return{isLocationLong:t,loca:new Uint8Array(a.buffer),glyf:new Uint8Array(e.buffer)}}scale(A){for(let e=0,t=this.glyphs.length;eA+e.getSize()),0);return this.header.getSize()+A}write(A,e){if(!this.header)return 0;const t=A;if(A+=this.header.write(A,e),this.simple)A+=this.simple.write(A,e);else for(const t of this.composites)A+=t.write(A,e);return A-t}scale(A){if(!this.header)return;const e=(this.header.xMin+this.header.xMax)/2;if(this.header.scale(e,A),this.simple)this.simple.scale(e,A);else for(const t of this.composites)t.scale(e,A)}}class $a{constructor({numberOfContours:A,xMin:e,yMin:t,xMax:i,yMax:a}){this.numberOfContours=A,this.xMin=e,this.yMin=t,this.xMax=i,this.yMax=a}static parse(A,e){return[10,new $a({numberOfContours:e.getInt16(A),xMin:e.getInt16(A+2),yMin:e.getInt16(A+4),xMax:e.getInt16(A+6),yMax:e.getInt16(A+8)})]}getSize(){return 10}write(A,e){return e.setInt16(A,this.numberOfContours),e.setInt16(A+2,this.xMin),e.setInt16(A+4,this.yMin),e.setInt16(A+6,this.xMax),e.setInt16(A+8,this.yMax),10}scale(A,e){this.xMin=Math.round(A+(this.xMin-A)*e),this.xMax=Math.round(A+(this.xMax-A)*e)}}class As{constructor({flags:A,xCoordinates:e,yCoordinates:t}){this.xCoordinates=e,this.yCoordinates=t,this.flags=A}}class es{constructor({contours:A,instructions:e}){this.contours=A,this.instructions=e}static parse(A,e,t){const i=[];for(let a=0;a255?A+=2:g>0&&(A+=1),e=s,g=Math.abs(n-t),g>255?A+=2:g>0&&(A+=1),t=n}}return A}write(A,e){const t=A,i=[],a=[],s=[];let n=0,g=0;for(const t of this.contours){for(let A=0,e=t.xCoordinates.length;A=0?18:2,i.push(A)):i.push(o)}n=r;const I=t.yCoordinates[A];if(o=I-g,0===o)e|=32,a.push(0);else{const A=Math.abs(o);A<=255?(e|=o>=0?36:4,a.push(A)):a.push(o)}g=I,s.push(e)}e.setUint16(A,i.length-1),A+=2}e.setUint16(A,this.instructions.length),A+=2,this.instructions.length&&(new Uint8Array(e.buffer,0,e.buffer.byteLength).set(this.instructions,A),A+=this.instructions.length);for(const t of s)e.setUint8(A++,t);for(let t=0,a=i.length;t=-128&&this.argument1<=127&&this.argument2>=-128&&this.argument2<=127||(A+=2):this.argument1>=0&&this.argument1<=255&&this.argument2>=0&&this.argument2<=255||(A+=2),A}write(A,e){const t=A;return 2&this.flags?this.argument1>=-128&&this.argument1<=127&&this.argument2>=-128&&this.argument2<=127||(this.flags|=1):this.argument1>=0&&this.argument1<=255&&this.argument2>=0&&this.argument2<=255||(this.flags|=1),e.setUint16(A,this.flags),e.setUint16(A+2,this.glyphIndex),A+=4,1&this.flags?(2&this.flags?(e.setInt16(A,this.argument1),e.setInt16(A+2,this.argument2)):(e.setUint16(A,this.argument1),e.setUint16(A+2,this.argument2)),A+=4):(e.setUint8(A,this.argument1),e.setUint8(A+1,this.argument2),A+=2),256&this.flags&&(e.setUint16(A,this.instructions.length),A+=2,this.instructions.length&&(new Uint8Array(e.buffer,0,e.buffer.byteLength).set(this.instructions,A),A+=this.instructions.length)),A-t}scale(A,e){}}function is(A,e,t){A[e]=t>>8&255,A[e+1]=255&t}function as(A,e,t){A[e]=t>>24&255,A[e+1]=t>>16&255,A[e+2]=t>>8&255,A[e+3]=255&t}function ss(A,e,t){if(t instanceof Uint8Array)A.set(t,e);else if("string"==typeof t)for(let i=0,a=t.length;it;)t<<=1,i++;const a=t*e;return{range:a,entry:i,rangeShift:e*A-a}}toArray(){let A=this.sfnt;const e=this.tables,t=Object.keys(e);t.sort();const i=t.length;let a,s,n,g,r,o=12+16*i;const I=[o];for(a=0;a>>0,I.push(o);const c=new Uint8Array(o);for(a=0;a>>0;as(c,o+4,A),as(c,o+8,I[a]),as(c,o+12,e[r].length),o+=16}return c}addTable(A,e){if(A in this.tables)throw new Error("Table "+A+" already exists");this.tables[A]=e}}const gs=[4],rs=[5],os=[6],Is=[7],cs=[8],Cs=[12,35],Bs=[14],hs=[21],Qs=[22],ls=[30],Es=[31];class us{constructor(){this.width=0,this.lsb=0,this.flexing=!1,this.output=[],this.stack=[]}convert(A,e,t){const i=A.length;let a,s,n,g=!1;for(let r=0;ri)return!0;const a=i-A;for(let A=a;A>8&255,255&e):(e=65536*e|0,this.output.push(255,e>>24&255,e>>16&255,e>>8&255,255&e))}return this.output.push(...e),t?this.stack.splice(a,A):this.stack.length=0,!1}}function ds(A){return A>=48&&A<=57||A>=65&&A<=70||A>=97&&A<=102}function fs(A,e,t){if(t>=A.length)return new Uint8Array(0);let i,a,s=0|e;for(i=0;i>8,s=52845*(e+s)+22719&65535}return g}function ps(A){return 47===A||91===A||93===A||123===A||125===A||40===A||41===A}class ms{constructor(A,e,t){if(e){const e=A.getBytes(),t=!((ds(e[0])||JA(e[0]))&&ds(e[1])&&ds(e[2])&&ds(e[3])&&ds(e[4])&&ds(e[5])&&ds(e[6])&&ds(e[7]));A=new ne(t?fs(e,55665,4):function(A,e,t){let i=55665;const a=A.length,s=new Uint8Array(a>>>1);let n,g;for(n=0,g=0;n>8,i=52845*(A+i)+22719&65535}}return s.slice(4,g)}(e))}this.seacAnalysisEnabled=!!t,this.stream=A,this.nextChar()}readNumberArray(){this.getToken();const A=[];for(;;){const e=this.getToken();if(null===e||"]"===e||"}"===e)break;A.push(parseFloat(e||0))}return A}readNumber(){const A=this.getToken();return parseFloat(A||0)}readInt(){const A=this.getToken();return 0|parseInt(A||0,10)}readBoolean(){return"true"===this.getToken()?1:0}nextChar(){return this.currentChar=this.stream.getByte()}prevChar(){return this.stream.skip(-2),this.currentChar=this.stream.getByte()}getToken(){let A=!1,e=this.currentChar;for(;;){if(-1===e)return null;if(A)10!==e&&13!==e||(A=!1);else if(37===e)A=!0;else if(!JA(e))break;e=this.nextChar()}if(ps(e))return this.nextChar(),String.fromCharCode(e);let t="";do{t+=String.fromCharCode(e),e=this.nextChar()}while(e>=0&&!JA(e)&&!ps(e));return t}readCharStrings(A,e){return-1===e?A:fs(A,4330,e)}extractFontProgram(A){const e=this.stream,t=[],i=[],a=Object.create(null);a.lenIV=4;const s={subrs:[],charstrings:[],properties:{privateData:a}};let n,g,r,o;for(;null!==(n=this.getToken());)if("/"===n)switch(n=this.getToken(),n){case"CharStrings":for(this.getToken(),this.getToken(),this.getToken(),this.getToken();n=this.getToken(),null!==n&&"end"!==n;){if("/"!==n)continue;const A=this.getToken();g=this.readInt(),this.getToken(),r=g>0?e.getBytes(g):new Uint8Array(0),o=s.properties.privateData.lenIV;const t=this.readCharStrings(r,o);this.nextChar(),n=this.getToken(),"noaccess"===n?this.getToken():"/"===n&&this.prevChar(),i.push({glyph:A,encoded:t})}break;case"Subrs":for(this.readInt(),this.getToken();"dup"===this.getToken();){const A=this.readInt();g=this.readInt(),this.getToken(),r=g>0?e.getBytes(g):new Uint8Array(0),o=s.properties.privateData.lenIV;const i=this.readCharStrings(r,o);this.nextChar(),n=this.getToken(),"noaccess"===n&&this.getToken(),t[A]=i}break;case"BlueValues":case"OtherBlues":case"FamilyBlues":case"FamilyOtherBlues":const A=this.readNumberArray();A.length>0&&A.length;break;case"StemSnapH":case"StemSnapV":s.properties.privateData[n]=this.readNumberArray();break;case"StdHW":case"StdVW":s.properties.privateData[n]=this.readNumberArray()[0];break;case"BlueShift":case"lenIV":case"BlueFuzz":case"BlueScale":case"LanguageGroup":s.properties.privateData[n]=this.readNumber();break;case"ExpansionFactor":s.properties.privateData[n]=this.readNumber()||.06;break;case"ForceBold":s.properties.privateData[n]=this.readBoolean()}for(const{encoded:e,glyph:a}of i){const i=new us,n=i.convert(e,t,this.seacAnalysisEnabled);let g=i.output;n&&(g=[14]);const r={glyphName:a,charstring:g,width:i.width,lsb:i.lsb,seac:i.seac};if(".notdef"===a?s.charstrings.unshift(r):s.charstrings.push(r),A.builtInEncoding){const e=A.builtInEncoding.indexOf(a);e>-1&&void 0===A.widths[e]&&e>=A.firstChar&&e<=A.lastChar&&(A.widths[e]=i.width)}}return s}extractFontHeader(A){let e;for(;null!==(e=this.getToken());)if("/"===e)switch(e=this.getToken(),e){case"FontMatrix":const t=this.readNumberArray();A.fontMatrix=t;break;case"Encoding":const i=this.getToken();let a;if(/^\d+$/.test(i)){a=[];const A=0|parseInt(i,10);this.getToken();for(let t=0;t=a){for(n+=t;n=0&&(i[A]=a)}return la(A,i,t)}hasGlyphId(A){return!(A<0||A>=this.numGlyphs)&&(0===A||this.charstrings[A-1].charstring.length>0)}getSeacs(A){const e=[];for(let t=0,i=A.length;t0;A--)e[A]-=e[A-1];B.setByName(A,e)}s.topDict.privateDict=B;const Q=new Oi;for(I=0,c=i.length;I0&&A.toUnicode.amend(e)}class Gs{constructor(A,e,t,i,a,s,n,g,r){this.originalCharCode=A,this.fontChar=e,this.unicode=t,this.accent=i,this.width=a,this.vmetric=s,this.operatorListId=n,this.isSpace=g,this.isInFont=r}get category(){return L(this,"category",function(A){const e=Ca.get(A);if(e)return e;const t=A.match(ca),i={isWhitespace:!!t?.[1],isZeroWidthDiacritic:!!t?.[2],isInvisibleFormatMark:!!t?.[3]};return Ca.set(A,i),i}(this.unicode),!0)}}function Ns(A,e){return(A<<8)+e}function xs(A,e,t){A[e+1]=t,A[e]=t>>>8}function Us(A,e){const t=(A<<8)+e;return 32768&t?t-65536:t}function Ms(A){return String.fromCharCode(A>>8&255,255&A)}function Ls(A){return A>32767?A=32767:A<-32768&&(A=-32768),String.fromCharCode(A>>8&255,255&A)}function Js(A){return"ttcf"===W(A.peekBytes(4))}function Hs(A,e){for(const t in e)A[+t]=e[t]}function Ys(A,e,t){const i=[];let a;for(let t=0,s=A.length;tI){if(r++,r>=Ds.length){N("Ran out of space in font private use area.");break}o=Ds[r][0],I=Ds[r][1]}const h=o++;0===B&&(B=t);let Q=i.get(C);"string"==typeof Q&&(Q=Q.codePointAt(0)),!Q||(c=Q,Ds[0][0]<=c&&c<=Ds[0][1]||Ds[1][0]<=c&&c<=Ds[1][1])||g.has(B)||(s.set(Q,B),g.add(B)),a[h]=B,n[C]=h}var c;return{toFontChar:n,charCodeToGlyphId:a,toUnicodeExtraMap:s,nextAvailableFontCharCode:o}}function Ps(A,e,t){const i=function(A,e,t){const i=[];for(const e in A)A[e]>=t||i.push({fontCharCode:0|e,glyphId:A[e]});if(e)for(const[A,a]of e)a>=t||i.push({fontCharCode:A,glyphId:a});0===i.length&&i.push({fontCharCode:0,glyphId:0}),i.sort((function(A,e){return A.fontCharCode-e.fontCharCode}));const a=[],s=i.length;for(let A=0;A65535?2:1;let s,n,g,r,o="\0\0"+Ms(a)+"\0\0"+O(4+8*a);for(s=i.length-1;s>=0&&!(i[s][0]<=65535);--s);const I=s+1;i[s][0]<65535&&65535===i[s][1]&&(i[s][1]=65534);const c=i[s][1]<65535?1:0,C=I+c,B=ns.getSearchParams(C,2);let h,Q,l,E,u="",d="",f="",p="",m="",y=0;for(s=0,n=I;s0&&(d+="ÿÿ",u+="ÿÿ",f+="\0",p+="\0\0");const w="\0\0"+Ms(2*C)+Ms(B.range)+Ms(B.entry)+Ms(B.rangeShift)+d+"\0\0"+u+f+p+m;let D="",b="";if(a>1){for(o+="\0\0\n"+O(4+8*a+4+w.length),D="",s=0,n=i.length;sA||!g)&&(g=A),r 123 are reserved for internal usage");n|=1<65535&&(r=65535)}else g=0,r=255;const I=A.bbox||[0,0,0,0],c=t.unitsPerEm||(A.fontMatrix?1/Math.max(...A.fontMatrix.slice(0,4).map(Math.abs)):1e3),C=A.ascentScaled?1:c/bs,B=t.ascent||Math.round(C*(A.ascent||I[3]));let h=t.descent||Math.round(C*(A.descent||I[1]));h>0&&A.descent>0&&I[1]<0&&(h=-h);const Q=t.yMax||B,l=-t.yMin||-h;return"\0$ô\0\0\0Š»\0\0\0ŒŠ»\0\0ß\x001\0\0\0\0"+String.fromCharCode(A.fixedPitch?9:0)+"\0\0\0\0\0\0"+O(i)+O(a)+O(s)+O(n)+"*21*"+Ms(A.italicAngle?1:0)+Ms(g||A.firstChar)+Ms(r||A.lastChar)+Ms(B)+Ms(h)+"\0d"+Ms(Q)+Ms(l)+"\0\0\0\0\0\0\0\0"+Ms(A.xHeight)+Ms(A.capHeight)+Ms(0)+Ms(g||A.firstChar)+"\0"}function Zs(A){return"\0\0\0"+O(Math.floor(65536*A.italicAngle))+"\0\0\0\0"+O(A.fixedPitch?1:0)+"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"}function Os(A){return A.replaceAll(/[^\x21-\x7E]|[[\](){}<>/%]/g,"").slice(0,63)}function Xs(A,e){e||(e=[[],[]]);const t=[e[0][0]||"Original licence",e[0][1]||A,e[0][2]||"Unknown",e[0][3]||"uniqueID",e[0][4]||A,e[0][5]||"Version 0.11",e[0][6]||Os(A),e[0][7]||"Unknown",e[0][8]||"Unknown",e[0][9]||"Unknown"],i=[];let a,s,n,g,r;for(a=0,s=t.length;a=1&&e[3]>=1&&e[3]<=4}(A)?i?(a="CIDFontType0",s="CIDFontType0C"):(a="MMType1"===e?"MMType1":"Type1",s="Type1C"):(N("getFontFileType: Unable to detect correct font file Type/Subtype."),a=e,s=t),[a,s]}(e,t),a===this.type&&s===this.subtype||G(`Inconsistent font file Type/SubType, expected: ${this.type}/${this.subtype} but found: ${a}/${s}.`);try{switch(a){case"MMType1":G("MMType1 font ("+A+"), falling back to Type1.");case"Type1":case"CIDFontType0":this.mimetype="font/opentype";const i="Type1C"===s||"CIDFontType0C"===s?new Ga(e,t):new ws(A,e,t);Ss(t),g=this.convert(A,i,t);break;case"OpenType":case"TrueType":case"CIDFontType2":this.mimetype="font/opentype",g=this.checkAndRepair(A,e,t),this.isOpenType&&(Ss(t),a="OpenType");break;default:throw new T(`Font ${a} is not supported`)}}catch(A){return N(A),void this.fallbackToSystemFont(t)}Rs(t),this.data=g,this.type=a,this.subtype=s,this.fontMatrix=t.fontMatrix,this.widths=t.widths,this.defaultWidth=t.defaultWidth,this.toUnicode=t.toUnicode,this.seacMap=t.seacMap}get renderer(){return L(this,"renderer",Xa.create(this,Ba))}exportData(A=!1){const e=A?[...ks,...Fs]:ks,t=Object.create(null);let i,a;for(i of e)a=this[i],void 0!==a&&(t[i]=a);return t}fallbackToSystemFont(A){this.missingFile=!0;const{name:e,type:t}=this;let i=Ea(e);const a=da(),s=pa(),n=!!a[i],g=!(!s[i]||!a[s[i]]);i=a[i]||s[i]||i;const r=ja()[i];r&&(isNaN(this.ascent)&&(this.ascent=r.ascent/bs),isNaN(this.descent)&&(this.descent=r.descent/bs),isNaN(this.capHeight)&&(this.capHeight=r.capHeight/bs)),this.bold=/bold/gi.test(i),this.italic=/oblique|italic/gi.test(i),this.black=/Black/g.test(e);const o=/Narrow/g.test(e);if(this.remeasure=(!n||o)&&Object.keys(this.widths).length>0,(n||g)&&"CIDFontType2"===t&&this.cidEncoding.startsWith("Identity-")){const t=A.cidToGidMap,i=[];if(Hs(i,wa()),/Arial-?Black/i.test(e)?Hs(i,Da()):/Calibri/i.test(e)&&Hs(i,ba()),t){for(const A in i){const e=i[A];void 0!==t[e]&&(i[+A]=t[e])}t.length!==this.toUnicode.length&&A.hasIncludedToUnicodeMap&&this.toUnicode instanceof Ra&&this.toUnicode.forEach((function(A,e){const a=i[A];void 0===t[a]&&(i[+A]=e)}))}this.toUnicode instanceof Ra||this.toUnicode.forEach((function(A,e){i[+A]=e})),this.toFontChar=i,this.toUnicode=new Sa(i)}else if(/Symbol/i.test(i))this.toFontChar=Ys(Ji,sa(),this.differences);else if(/Dingbats/i.test(i))this.toFontChar=Ys(Hi,na(),this.differences);else if(n||g){const A=Ys(this.defaultEncoding,sa(),this.differences);"CIDFontType2"!==t||this.cidEncoding.startsWith("Identity-")||this.toUnicode instanceof Ra||this.toUnicode.forEach((function(e,t){A[+e]=t})),this.toFontChar=A}else{const A=sa(),t=[];this.toUnicode.forEach(((e,i)=>{if(!this.composite){const t=ra(this.differences[e]||this.defaultEncoding[e],A);-1!==t&&(i=t)}t[+e]=i})),this.composite&&this.toUnicode instanceof Ra&&/Tahoma|Verdana/i.test(e)&&Hs(t,wa()),this.toFontChar=t}Rs(A),this.loadedName=i.split("-",1)[0]}checkAndRepair(A,e,t){const i=["OS/2","cmap","head","hhea","hmtx","maxp","name","post","loca","glyf","fpgm","prep","cvt ","CFF "];function a(A,e){const t=Object.create(null);t["OS/2"]=null,t.cmap=null,t.head=null,t.hhea=null,t.hmtx=null,t.maxp=null,t.name=null,t.post=null;for(let a=0;a>>0,i=A.getInt32()>>>0,a=A.getInt32()>>>0,s=A.pos;A.pos=A.start||0,A.skip(i);const n=A.getBytes(a);return A.pos=s,"head"===e&&(n[8]=n[9]=n[10]=n[11]=0,n[17]|=32),{tag:e,checksum:t,length:a,offset:i,data:n}}function n(A){return{version:A.getString(4),numTables:A.getUint16(),searchRange:A.getUint16(),entrySelector:A.getUint16(),rangeShift:A.getUint16()}}function g(A,e,t,i,a,s){const n={length:0,sizeOfInstructions:0};if(e<0||e>=A.length||t>A.length||t-e<=12)return n;const g=A.subarray(e,t),r=Us(g[2],g[3]),o=Us(g[4],g[5]),I=Us(g[6],g[7]),c=Us(g[8],g[9]);r>I&&(xs(g,2,I),xs(g,6,r)),o>c&&(xs(g,4,c),xs(g,8,o));const C=Us(g[0],g[1]);if(C<0)return C<-1||(i.set(g,a),n.length=g.length),n;let B,h=10,Q=0;for(B=0;Bg.length?n:!s&&E>0?(i.set(g.subarray(0,l),a),i.set([0,0],a+l),i.set(g.subarray(u,f),a+l+2),f-=E,g.length-f>3&&(f=f+3&-4),n.length=f,n):g.length-f>3?(f=f+3&-4,i.set(g.subarray(0,f),a),n.length=f,n):(i.set(g,a),n.length=g.length,n)}function r(A){const t=(e.start||0)+A.offset;e.pos=t;const i=[[],[]],a=[],s=A.length,n=t+s;if(0!==e.getUint16()||s<6)return[i,a];const g=e.getUint16(),r=e.getUint16();let o,I;for(o=0;on)continue;e.pos=s;const g=A.name;if(A.encoding){let t="";for(let i=0,a=A.length;i0&&(r+=A-1)}}else(l||u)&&(N("TT: nested FDEFs not allowed"),Q=!0),l=!0,c=r,s=C.pop(),e.functionsDefined[s]={data:g,i:r};else if(!l&&!u)if(s=C.at(-1),isNaN(s))G("TT: CALL empty stack (or invalid entry).");else if(e.functionsUsed[s]=!0,s in e.functionsStackDeltas){const A=C.length+e.functionsStackDeltas[s];if(A<0)return N("TT: CALL invalid functions stack delta."),void(e.hintsValid=!1);C.length=A}else if(s in e.functionsDefined&&!h.includes(s)){if(B.push({data:g,i:r,stackTop:C.length-1}),h.push(s),n=e.functionsDefined[s],!n)return N("TT: CALL non-existent function"),void(e.hintsValid=!1);g=n.data,r=n.i}if(!l&&!u){let e=0;for(A<=142?e=o[A]:A>=192&&A<=223?e=-1:A>=224&&(e=-2),A>=113&&A<=117&&(i=C.pop(),isNaN(i)||(e=2*-i));e<0&&C.length>0;)C.pop(),e++;for(;e>0;)C.push(NaN),e--}}e.tooComplexToFollowFunctions=Q;const d=[g];r>g.length&&d.push(new Uint8Array(r-g.length)),c>I&&(N("TT: complementing a missing function tail"),d.push(new Uint8Array([34,45]))),function(A,e){if(e.length>1){let t,i,a=0;for(t=0,i=e.length;t>>0,s=[];for(let e=0;e>>0);const n={ttcTag:e,majorVersion:t,minorVersion:i,numFonts:a,offsetTable:s};switch(t){case 1:return n;case 2:return n.dsigTag=A.getInt32()>>>0,n.dsigLength=A.getInt32()>>>0,n.dsigOffset=A.getInt32()>>>0,n}throw new T(`Invalid TrueType Collection majorVersion: ${t}.`)}(A),s=e.split("+");let g;for(let o=0;o0||!(t.cMap instanceof hi));if("OTTO"===c.version&&!e||!C.head||!C.hhea||!C.maxp||!C.post)return h=new ne(C["CFF "].data),B=new Ga(h,t),Ss(t),this.convert(A,B,t);delete C.glyf,delete C.loca,delete C.fpgm,delete C.prep,delete C["cvt "],this.isOpenType=!0}if(!C.maxp)throw new T('Required "maxp" table is not found');e.pos=(e.start||0)+C.maxp.offset;let l=e.getInt32();const E=e.getUint16();if(65536!==l&&20480!==l){if(6===C.maxp.length)l=20480;else{if(!(C.maxp.length>=32))throw new T('"maxp" table has a wrong version number');l=65536}d=l,(u=C.maxp.data)[3+0]=255&d,u[2]=d>>>8,u[1]=d>>>16,u[0]=d>>>24}var u,d;if(t.scaleFactors?.length===E&&Q){const{scaleFactors:A}=t,e=Ns(C.head.data[50],C.head.data[51]),i=new za({glyfTable:C.glyf.data,isGlyphLocationsLong:e,locaTable:C.loca.data,numGlyphs:E});i.scale(A);const{glyf:a,loca:s,isLocationLong:n}=i.write();C.glyf.data=a,C.loca.data=s,n!==!!e&&(C.head.data[50]=0,C.head.data[51]=n?1:0);const g=C.hmtx.data;for(let e=0;e>8&255,g[t+1]=255&i,xs(g,t+2,Math.round(A[e]*Us(g[t+2],g[t+3])))}}let f=E+1,p=!0;f>65535&&(p=!1,f=E,N("Not enough space in glyfs to duplicate first glyph."));let m=0,y=0;l>=65536&&C.maxp.length>=32&&(e.pos+=8,e.getUint16()>2&&(C.maxp.data[14]=0,C.maxp.data[15]=2),e.pos+=4,m=e.getUint16(),e.pos+=4,y=e.getUint16()),C.maxp.data[4]=f>>8,C.maxp.data[5]=255&f;const w=function(A,e,t,i){const a={functionsDefined:[],functionsUsed:[],functionsStackDeltas:[],tooComplexToFollowFunctions:!1,hintsValid:!0};if(A&&I(A,a),e&&I(e,a),A&&function(A,e){if(!A.tooComplexToFollowFunctions){if(A.functionsDefined.length>e)return N("TT: more functions defined than expected"),void(A.hintsValid=!1);for(let t=0,i=A.functionsUsed.length;te)return N("TT: invalid function id: "+t),void(A.hintsValid=!1);if(A.functionsUsed[t]&&!A.functionsDefined[t])return N("TT: undefined function: "+t),void(A.hintsValid=!1)}}}(a,i),t&&1&t.length){const A=new Uint8Array(t.length+1);A.set(t.data),t.data=A}return a.hintsValid}(C.fpgm,C.prep,C["cvt "],m);if(w||(delete C.fpgm,delete C.prep,delete C["cvt "]),function(A,e,t,i,a,s){if(!e)return void(t&&(t.data=null));A.pos=(A.start||0)+e.offset,A.pos+=4,A.pos+=2,A.pos+=2,A.pos+=2,A.pos+=2,A.pos+=2,A.pos+=2,A.pos+=2,A.pos+=2,A.pos+=2;const n=A.getUint16();A.pos+=8,A.pos+=2;let g=A.getUint16();0!==n&&(2&Ns(i.data[44],i.data[45])||(e.data[22]=0,e.data[23]=0)),g>a&&(G(`The numOfMetrics (${g}) should not be greater than the numGlyphs (${a}).`),g=a,e.data[34]=(65280&g)>>8,e.data[35]=255&g);const r=a-g-(t.length-4*g>>1);if(r>0){const A=new Uint8Array(t.length+2*r);A.set(t.data),s&&(A[t.length]=t.data[2],A[t.length+1]=t.data[3]),t.data=A}}(e,C.hhea,C.hmtx,C.head,f,p),!C.head)throw new T('Required "head" table is not found');!function(A,e,t){const i=A.data,a=(i[0]<<24)+(i[1]<<16)+(i[2]<<8)+i[3];a>>16!=1&&(G("Attempting to fix invalid version in head table: "+a),i[0]=0,i[1]=1,i[2]=0,i[3]=0);const s=Ns(i[50],i[51]);if(s<0||s>1){G("Attempting to fix invalid indexToLocFormat in head table: "+s);const A=e+1;if(t===A<<1)i[50]=0,i[51]=0;else{if(t!==A<<2)throw new T("Could not fix indexToLocFormat: "+s);i[50]=0,i[51]=1}}}(C.head,E,Q?C.loca.length:0);let D=Object.create(null);if(Q){const A=Ns(C.head.data[50],C.head.data[51]),e=function(A,e,t,i,a,s,n){let r,o,I;i?(r=4,o=function(A,e){return A[e]<<24|A[e+1]<<16|A[e+2]<<8|A[e+3]},I=function(A,e,t){A[e]=t>>>24&255,A[e+1]=t>>16&255,A[e+2]=t>>8&255,A[e+3]=255&t}):(r=2,o=function(A,e){return A[e]<<9|A[e+1]<<1},I=function(A,e,t){A[e]=t>>9&255,A[e+1]=t>>1&255});const c=s?t+1:t,C=r*(1+c),B=new Uint8Array(C);B.set(A.data.subarray(0,C)),A.data=B;const h=e.data,Q=h.length,l=new Uint8Array(Q);let E,u;const d=[];for(E=0,u=0;EQ&&(A=Q),d.push({index:E,offset:A,endOffset:0})}for(d.sort(((A,e)=>A.offset-e.offset)),E=0;EA.index-e.index)),E=0;En&&(n=A.sizeOfInstructions),m+=e,I(B,u,m)}if(0===m){const A=new Uint8Array([0,1,0,0,0,0,0,0,0,0,0,0,0,0,49,0]);for(E=0,u=r;Et+m?e.data=l.subarray(0,t+m):(e.data=new Uint8Array(t+m),e.data.set(l.subarray(0,m))),e.data.set(l.subarray(0,t),m),I(A.data,B.length-r,m+t)}else e.data=l.subarray(0,m);return{missingGlyphs:p,maxSizeOfInstructions:n}}(C.loca,C.glyf,E,A,w,p,y);D=e.missingGlyphs,l>=65536&&C.maxp.length>=32&&(C.maxp.data[26]=e.maxSizeOfInstructions>>8,C.maxp.data[27]=255&e.maxSizeOfInstructions)}if(!C.hhea)throw new T('Required "hhea" table is not found');0===C.hhea.data[10]&&0===C.hhea.data[11]&&(C.hhea.data[10]=255,C.hhea.data[11]=255);const b={unitsPerEm:Ns(C.head.data[18],C.head.data[19]),yMax:Us(C.head.data[42],C.head.data[43]),yMin:Us(C.head.data[38],C.head.data[39]),ascent:Us(C.hhea.data[4],C.hhea.data[5]),descent:Us(C.hhea.data[6],C.hhea.data[7]),lineGap:Us(C.hhea.data[8],C.hhea.data[9])};this.ascent=b.ascent/b.unitsPerEm,this.descent=b.descent/b.unitsPerEm,this.lineGap=b.lineGap/b.unitsPerEm,this.cssFontInfo?.lineHeight?(this.lineHeight=this.cssFontInfo.metrics.lineHeight,this.lineGap=this.cssFontInfo.metrics.lineGap):this.lineHeight=this.ascent-this.descent+this.lineGap,C.post&&function(A,t,i){const a=(e.start||0)+A.offset;e.pos=a;const s=a+A.length,n=e.getInt32();let g;e.skip(28);let r,o=!0;switch(n){case 65536:g=ha;break;case 131072:const A=e.getUint16();if(A!==i){o=!1;break}const a=[];for(r=0;r=32768){o=!1;break}a.push(A)}if(!o)break;const I=[],c=[];for(;e.pos65535)throw new T("Max size of CID is 65,535");let a=-1;e?a=i:void 0!==A[i]&&(a=A[i]),a>=0&&a>>0;let I=!1;if(g?.platformId!==a||g?.encodingId!==s){if(0!==a||0!==s&&1!==s&&3!==s)if(1===a&&0===s)I=!0;else if(3!==a||1!==s||!i&&g){if(t&&3===a&&0===s){I=!0;let t=!0;if(A>3;A.push(i),t=Math.max(i,t)}const i=[];for(let A=0;A<=t;A++)i.push({firstCode:e.getUint16(),entryCount:e.getUint16(),idDelta:Us(e.getByte(),e.getByte()),idRangePos:e.pos+e.getUint16()});for(let t=0;t<256;t++)if(0===A[t])e.pos=i[0].idRangePos+2*t,B=e.getUint16(),c.push({charCode:t,glyphId:B});else{const a=i[A[t]];for(C=0;C>1;e.skip(6);const t=[];let i;for(i=0;i>1)-(A-i),a.offsetIndex=n,g=Math.max(g,n+a.end-a.start+1)):a.offsetIndex=-1}const r=[];for(C=0;C>>0;for(C=0;C>>0,t=e.getInt32()>>>0;let i=e.getInt32()>>>0;for(let e=A;e<=t;e++)c.push({charCode:e,glyphId:i++})}}}c.sort((function(A,e){return A.charCode-e.charCode}));for(let A=1;A=61440&&e<=61695&&(e&=255),k[e]=A.glyphId}else for(const A of s)k[A.charCode]=A.glyphId;if(t.glyphNames&&(n.length||this.differences.length))for(let A=0;A<256;++A){if(!g&&void 0!==k[A])continue;const e=this.differences[A]||n[A];if(!e)continue;const i=t.glyphNames.indexOf(e);i>0&&F(i)&&(k[A]=i)}}0===k.length&&(k[0]=0);let S=f-1;if(p||(S=0),!t.cssFontInfo){const A=Ts(k,F,S,this.toUnicode);this.toFontChar=A.toFontChar,C.cmap={tag:"cmap",data:Ps(A.charCodeToGlyphId,A.toUnicodeExtraMap,f)},C["OS/2"]&&function(A,e){e.pos=(e.start||0)+A.offset;const t=e.getUint16();e.skip(60);const i=e.getUint16();return!(t<4&&768&i||e.getUint16()>e.getUint16()||(e.skip(6),0===e.getUint16()||(A.data[8]=A.data[9]=0,0)))}(C["OS/2"],e)||(C["OS/2"]={tag:"OS/2",data:Ws(t,A.charCodeToGlyphId,b)})}if(!Q)try{h=new ne(C["CFF "].data),B=new Ti(h,t,Ba).parse(),B.duplicateFirstGlyph();const A=new aa(B);C["CFF "].data=A.compile()}catch{N("Failed to compile font "+t.loadedName)}if(C.name){const[e,i]=r(C.name);C.name.data=Xs(A,e),this.psName=e[0][6]||null,t.composite||function(A,e,t){if(A.isInternalFont)return;if(A.hasIncludedToUnicodeMap)return;if(A.hasEncoding)return;if(A.toUnicode instanceof Ra)return;if(!e)return;if(0===t.length)return;if(A.defaultEncoding===Li)return;for(const A of t)if(!Ks(A))return;const i=Li,a=[],s=sa();for(const A in i){const e=i[A];if(""===e)continue;const t=s[e];void 0!==t&&(a[A]=String.fromCharCode(t))}a.length>0&&A.toUnicode.amend(a)}(t,this.isSymbolicFont,i)}else C.name={tag:"name",data:Xs(this.name)};const R=new ns(c.version);for(const A in C)R.addTable(A,C[A].data);return R.toArray()}convert(A,e,t){t.fixedPitch=!1,t.builtInEncoding&&function(A,e){if(A.isInternalFont)return;if(A.hasIncludedToUnicodeMap)return;if(e===A.defaultEncoding)return;if(A.toUnicode instanceof Ra)return;const t=[],i=sa();for(const a in e){if(A.hasEncoding&&(A.baseEncodingName||void 0!==A.differences[a]))continue;const s=ra(e[a],i);-1!==s&&(t[a]=String.fromCharCode(s))}t.length>0&&A.toUnicode.amend(t)}(t,t.builtInEncoding);let i=1;e instanceof Ga&&(i=e.numGlyphs-1);const s=e.getGlyphMapping(t);let n=null,g=s,r=null;t.cssFontInfo||(n=Ts(s,e.hasGlyphId.bind(e),i,this.toUnicode),this.toFontChar=n.toFontChar,g=n.charCodeToGlyphId,r=n.toUnicodeExtraMap);const o=e.numGlyphs;function I(A,e){let t=null;for(const i in A)e===A[i]&&(t||=[]).push(0|i);return t}function c(A,e){for(const t in A)if(e===A[t])return 0|t;return n.charCodeToGlyphId[n.nextAvailableFontCharCode]=e,n.nextAvailableFontCharCode++}const C=e.seacs;if(n&&C?.length){const A=t.fontMatrix||a,i=e.getCharset(),g=Object.create(null);for(let e in C){e|=0;const t=C[e],a=Mi[t[2]],r=Mi[t[3]],o=i.indexOf(a),B=i.indexOf(r);if(o<0||B<0)continue;const h={x:t[0]*A[0]+t[1]*A[2]+A[4],y:t[0]*A[1]+t[1]*A[3]+A[5]},Q=I(s,e);if(Q)for(const A of Q){const e=n.charCodeToGlyphId,t=c(e,o),i=c(e,B);g[A]={baseFontCharCode:t,accentFontCharCode:i,accentOffset:h}}}t.seacMap=g}const B=t.fontMatrix?1/Math.max(...t.fontMatrix.slice(0,4).map(Math.abs)):1e3,h=new ns("OTTO");return h.addTable("CFF ",e.data),h.addTable("OS/2",Ws(t,g)),h.addTable("cmap",Ps(g,r,o)),h.addTable("head","\0\0\0\0\0\0\0\0\0\0_<õ\0\0"+Ls(B)+"\0\0\0\0ž\v~'\0\0\0\0ž\v~'\0\0"+Ls(t.descent)+"ÿ"+Ls(t.ascent)+Ms(t.italicAngle?2:0)+"\0\0\0\0\0\0\0"),h.addTable("hhea","\0\0\0"+Ls(t.ascent)+Ls(t.descent)+"\0\0ÿÿ\0\0\0\0\0\0"+Ls(t.capHeight)+Ls(Math.tan(t.italicAngle)*t.xHeight)+"\0\0\0\0\0\0\0\0\0\0\0\0"+Ms(o)),h.addTable("hmtx",function(){const A=e.charstrings,t=e.cff?e.cff.widths:null;let i="\0\0\0\0";for(let e=1,a=o;e=65520&&I<=65535?0:I>=62976&&I<=63743?ga()[I]||I:173===I?45:I}var I;this.isType3Font&&(a=t);let c=null;if(this.seacMap?.[A]){o=!0;const e=this.seacMap[A];t=e.baseFontCharCode,c={fontChar:String.fromCodePoint(e.accentFontCharCode),offset:e.accentOffset}}let C="";if("number"==typeof t&&(t<=1114111?C=String.fromCodePoint(t):N(`charToGlyph - invalid fontCharCode: ${t}`)),this.missingFile&&this.vertical&&1===C.length){const A=ua()[C.charCodeAt(0)];A&&(C=r=String.fromCharCode(A))}return s=new Gs(A,C,r,c,i,g,a,e,o),this._glyphCache[A]=s}charsToGlyphs(A){let e=this._charsCache[A];if(e)return e;if(e=[],this.cMap){const t=Object.create(null),i=A.length;let a=0;for(;ae.length%2==1,a=this.toUnicode instanceof Ra?A=>this.toUnicode.charCodeOf(A):A=>this.toUnicode.charCodeOf(String.fromCodePoint(A));for(let s=0,n=A.length;s55295&&(n<57344||n>65533)&&s++,this.toUnicode){const A=a(n);if(-1!==A){i()&&(e.push(t.join("")),t.length=0);for(let e=(this.cMap?this.cMap.getCharCodeLength(A):1)-1;e>=0;e--)t.push(String.fromCharCode(A>>8*e&255));continue}}i()||(e.push(t.join("")),t.length=0),t.push(String.fromCodePoint(n))}return e.push(t.join("")),e}}class js{constructor(A){this.error=A,this.loadedName="g_font_error",this.missingFile=!0}charsToGlyphs(){return[]}encodeString(A){return[A]}exportData(A=!1){return{error:this.error}}}class zs{constructor(){x("Cannot initialize Pattern.")}static parseShading(A,e,t,i,a){const s=A instanceof mA?A.dict:A,n=s.get("ShadingType");try{switch(n){case 2:case 3:return new $s(s,e,t,i,a);case 4:case 5:case 6:case 7:return new an(A,e,t,i,a);default:throw new T("Unsupported ShadingType: "+n)}}catch(A){if(A instanceof DA)throw A;return N(A),new sn}}}class _s{static SMALL_NUMBER=1e-6;getIR(){x("Abstract method `getIR` called.")}}class $s extends _s{constructor(A,e,t,i,a){super(),this.shadingType=A.get("ShadingType");let s=0;if(2===this.shadingType?s=4:3===this.shadingType&&(s=6),this.coordsArr=A.getArray("Coords"),!HA(this.coordsArr,s))throw new T("RadialAxialShading: Invalid /Coords array.");const n=ce.parse({cs:A.getRaw("CS")||A.getRaw("ColorSpace"),xref:e,resources:t,pdfFunctionFactory:i,localColorSpaceCache:a});this.bbox=KA(A.getArray("BBox"),null);let g=0,r=1;const o=A.getArray("Domain");HA(o,2)&&([g,r]=o);let I=!1,c=!1;const C=A.getArray("Extend");var B;if(B=C,2,Array.isArray(B)&&2===B.length&&B.every((A=>"boolean"==typeof A))&&([I,c]=C),!(3!==this.shadingType||I&&c)){const[A,e,t,i,a,s]=this.coordsArr,n=Math.hypot(A-i,e-a);t<=s+n&&s<=t+n&&N("Unsupported radial gradient.")}this.extendStart=I,this.extendEnd=c;const h=A.getRaw("Function"),Q=i.createFromArray(h),l=(r-g)/840,E=this.colorStops=[];if(g>=r||l<=0)return void G("Bad shading domain.");const u=new Float32Array(n.numComps),d=new Float32Array(1);let f,p=0;d[0]=g,Q(d,0,u,0);let m=n.getRgb(u,0);const y=z.makeHexColor(m[0],m[1],m[2]);E.push([0,y]);let w=1;d[0]=g+l,Q(d,0,u,0);let D=n.getRgb(u,0),b=D[0]-m[0]+1,k=D[1]-m[1]+1,F=D[2]-m[2]+1,S=D[0]-m[0]-1,R=D[1]-m[1]-1,x=D[2]-m[2]-1;for(let A=2;A<840;A++){d[0]=g+A*l,Q(d,0,u,0),f=n.getRgb(u,0);const e=A-p;if(b=Math.min(b,(f[0]-m[0]+1)/e),k=Math.min(k,(f[1]-m[1]+1)/e),F=Math.min(F,(f[2]-m[2]+1)/e),S=Math.max(S,(f[0]-m[0]-1)/e),R=Math.max(R,(f[1]-m[1]-1)/e),x=Math.max(x,(f[2]-m[2]-1)/e),!(S<=b&&R<=k&&x<=F)){const A=z.makeHexColor(D[0],D[1],D[2]);E.push([w/840,A]),b=f[0]-D[0]+1,k=f[1]-D[1]+1,F=f[2]-D[2]+1,S=f[0]-D[0]-1,R=f[1]-D[1]-1,x=f[2]-D[2]-1,p=w,m=D}w=A,D=f}const U=z.makeHexColor(D[0],D[1],D[2]);E.push([1,U]);let M="transparent";A.has("Background")&&(f=n.getRgb(A.get("Background"),0),M=z.makeHexColor(f[0],f[1],f[2])),I||(E.unshift([0,M]),E[1][0]+=_s.SMALL_NUMBER),c||(E.at(-1)[0]-=_s.SMALL_NUMBER,E.push([1,M])),this.colorStops=E}getIR(){const{coordsArr:A,shadingType:e}=this;let t,i,a,s,n;return 2===e?(i=[A[0],A[1]],a=[A[2],A[3]],s=null,n=null,t="axial"):3===e?(i=[A[0],A[1]],a=[A[3],A[4]],s=A[2],n=A[5],t="radial"):x(`getPattern type unknown: ${e}`),["RadialAxial",t,this.bbox,this.colorStops,i,a,s,n]}}class An{constructor(A,e){this.stream=A,this.context=e,this.buffer=0,this.bufferLength=0;const t=e.numComps;this.tmpCompsBuf=new Float32Array(t);const i=e.colorSpace.numComps;this.tmpCsCompsBuf=e.colorFn?new Float32Array(i):this.tmpCompsBuf}get hasData(){if(this.stream.end)return this.stream.pos0)return!0;const A=this.stream.getByte();return!(A<0||(this.buffer=A,this.bufferLength=8,0))}readBits(A){let e=this.buffer,t=this.bufferLength;if(32===A){if(0===t)return(this.stream.getByte()<<24|this.stream.getByte()<<16|this.stream.getByte()<<8|this.stream.getByte())>>>0;e=e<<24|this.stream.getByte()<<16|this.stream.getByte()<<8|this.stream.getByte();const A=this.stream.getByte();return this.buffer=A&(1<>t)>>>0}if(8===A&&0===t)return this.stream.getByte();for(;t>t}align(){this.buffer=0,this.bufferLength=0}readFlag(){return this.readBits(this.context.bitsPerFlag)}readCoordinate(){const A=this.context.bitsPerCoordinate,e=this.readBits(A),t=this.readBits(A),i=this.context.decode,a=A<32?1/((1<s?s:A,e=e>n?n:e,t=tA*a[e])):t;let n,g=-2;const r=[];for(const[A,e]of i.map(((A,e)=>[A,e])).sort((([A],[e])=>A-e)))-1!==A&&(A===g+1?(n.push(s[e]),g+=1):(g=A,n=[s[e]],r.push(A,n)));return r}(A),t=new hA(null);t.set("BaseFont",cA.get(A)),t.set("Type",cA.get("Font")),t.set("Subtype",cA.get("CIDFontType2")),t.set("Encoding",cA.get("Identity-H")),t.set("CIDToGIDMap",cA.get("Identity")),t.set("W",e),t.set("FirstChar",e[0]),t.set("LastChar",e.at(-2)+e.at(-1).length-1);const i=new hA(null);t.set("FontDescriptor",i);const a=new hA(null);return a.set("Ordering","Identity"),a.set("Registry","Adobe"),a.set("Supplement",0),t.set("CIDSystemInfo",a),t}class jn{constructor(A){this.lexer=A,this.operators=[],this.token=null,this.prev=null}nextToken(){this.prev=this.token,this.token=this.lexer.getToken()}accept(A){return this.token.type===A&&(this.nextToken(),!0)}expect(A){if(this.accept(A))return!0;throw new T(`Unexpected symbol: found ${this.token.type} expected ${A}.`)}parse(){return this.nextToken(),this.expect(zn.LBRACE),this.parseBlock(),this.expect(zn.RBRACE),this.operators}parseBlock(){for(;;)if(this.accept(zn.NUMBER))this.operators.push(this.prev.value);else if(this.accept(zn.OPERATOR))this.operators.push(this.prev.value);else{if(!this.accept(zn.LBRACE))return;this.parseCondition()}}parseCondition(){const A=this.operators.length;if(this.operators.push(null,null),this.parseBlock(),this.expect(zn.RBRACE),this.accept(zn.IF))this.operators[A]=this.operators.length,this.operators[A+1]="jz";else{if(!this.accept(zn.LBRACE))throw new T("PS Function: error parsing conditional.");{const e=this.operators.length;this.operators.push(null,null);const t=this.operators.length;this.parseBlock(),this.expect(zn.RBRACE),this.expect(zn.IFELSE),this.operators[e]=this.operators.length,this.operators[e+1]="j",this.operators[A]=t,this.operators[A+1]="jz"}}}}const zn={LBRACE:0,RBRACE:1,NUMBER:2,OPERATOR:3,IF:4,IFELSE:5};class _n{static get opCache(){return L(this,"opCache",Object.create(null))}constructor(A,e){this.type=A,this.value=e}static getOperator(A){return _n.opCache[A]||=new _n(zn.OPERATOR,A)}static get LBRACE(){return L(this,"LBRACE",new _n(zn.LBRACE,"{"))}static get RBRACE(){return L(this,"RBRACE",new _n(zn.RBRACE,"}"))}static get IF(){return L(this,"IF",new _n(zn.IF,"IF"))}static get IFELSE(){return L(this,"IFELSE",new _n(zn.IFELSE,"IFELSE"))}}class $n{constructor(A){this.stream=A,this.nextChar(),this.strBuf=[]}nextChar(){return this.currentChar=this.stream.getByte()}getToken(){let A=!1,e=this.currentChar;for(;;){if(e<0)return gA;if(A)10!==e&&13!==e||(A=!1);else if(37===e)A=!0;else if(!JA(e))break;e=this.nextChar()}switch(0|e){case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:case 43:case 45:case 46:return new _n(zn.NUMBER,this.getNumber());case 123:return this.nextChar(),_n.LBRACE;case 125:return this.nextChar(),_n.RBRACE}const t=this.strBuf;for(t.length=0,t[0]=String.fromCharCode(e);(e=this.nextChar())>=0&&(e>=65&&e<=90||e>=97&&e<=122);)t.push(String.fromCharCode(e));const i=t.join("");switch(i.toLowerCase()){case"if":return _n.IF;case"ifelse":return _n.IFELSE;default:return _n.getOperator(i)}}getNumber(){let A=this.currentChar;const e=this.strBuf;for(e.length=0,e[0]=String.fromCharCode(A);(A=this.nextChar())>=0&&(A>=48&&A<=57||45===A||46===A);)e.push(String.fromCharCode(A));const t=parseFloat(e.join(""));if(isNaN(t))throw new T(`Invalid floating point number: ${t}`);return t}}class Ag{constructor(A){this._onlyRefs=!0===A?.onlyRefs,this._onlyRefs||(this._nameRefMap=new Map,this._imageMap=new Map),this._imageCache=new EA}getByName(A){this._onlyRefs&&x("Should not call `getByName` method.");const e=this._nameRefMap.get(A);return e?this.getByRef(e):this._imageMap.get(A)||null}getByRef(A){return this._imageCache.get(A)||null}set(A,e,t){x("Abstract method `set` called.")}}class eg extends Ag{set(A,e=null,t){if("string"!=typeof A)throw new Error('LocalImageCache.set - expected "name" argument.');if(e){if(this._imageCache.has(e))return;return this._nameRefMap.set(A,e),void this._imageCache.put(e,t)}this._imageMap.has(A)||this._imageMap.set(A,t)}}class tg extends Ag{set(A=null,e=null,t){if("string"!=typeof A&&!e)throw new Error('LocalColorSpaceCache.set - expected "name" and/or "ref" argument.');if(e){if(this._imageCache.has(e))return;return null!==A&&this._nameRefMap.set(A,e),void this._imageCache.put(e,t)}this._imageMap.has(A)||this._imageMap.set(A,t)}}class ig extends Ag{constructor(A){super({onlyRefs:!0})}set(A=null,e,t){if(!e)throw new Error('LocalFunctionCache.set - expected "ref" argument.');this._imageCache.has(e)||this._imageCache.put(e,t)}}class ag extends Ag{set(A,e=null,t){if("string"!=typeof A)throw new Error('LocalGStateCache.set - expected "name" argument.');if(e){if(this._imageCache.has(e))return;return this._nameRefMap.set(A,e),void this._imageCache.put(e,t)}this._imageMap.has(A)||this._imageMap.set(A,t)}}class sg extends Ag{constructor(A){super({onlyRefs:!0})}set(A=null,e,t){if(!e)throw new Error('LocalTilingPatternCache.set - expected "ref" argument.');this._imageCache.has(e)||this._imageCache.put(e,t)}}class ng extends Ag{constructor(A){super({onlyRefs:!0})}set(A=null,e,t){if(!e)throw new Error('RegionalImageCache.set - expected "ref" argument.');this._imageCache.has(e)||this._imageCache.put(e,t)}}class gg{static NUM_PAGES_THRESHOLD=2;static MIN_IMAGES_TO_CACHE=10;static MAX_BYTE_SIZE=5e7;#D=new lA;constructor(){this._refCache=new EA,this._imageCache=new EA}get#b(){let A=0;for(const e of this._imageCache)A+=e.byteSize;return A}get#k(){return!(this._imageCache.size+A)):null}class Ig{static getSampleArray(A,e,t,i){let a,s,n=1;for(a=0,s=A.length;a>r)*I,o&=(1<t?A=t:A0&&(C=s[c-1]);let B=i[1];c>1,o=a.length>>1,I=new Bg(g),c=Object.create(null);let C=8192;const B=new Float32Array(o);return function(A,e,t,i){let a,n,g="";const h=B;for(a=0;aA&&(n=A)),l[a]=n}C>0&&(C--,c[g]=l),t.set(l,i)}}}function cg(A){let e;if(A instanceof hA)e=A;else{if(!(A instanceof mA))return!1;e=A.dict}return e.has("FunctionType")}class Cg{static MAX_STACK_SIZE=100;constructor(A){this.stack=A?Array.from(A):[]}push(A){if(this.stack.length>=Cg.MAX_STACK_SIZE)throw new Error("PostScript function stack overflow.");this.stack.push(A)}pop(){if(this.stack.length<=0)throw new Error("PostScript function stack underflow.");return this.stack.pop()}copy(A){if(this.stack.length+A>=Cg.MAX_STACK_SIZE)throw new Error("PostScript function stack overflow.");const e=this.stack;for(let t=e.length-A,i=A-1;i>=0;i--,t++)e.push(e[t])}index(A){this.push(this.stack[this.stack.length-A-1])}roll(A,e){const t=this.stack,i=t.length-A,a=t.length-1,s=i+(e-Math.floor(e/A)*A);for(let A=i,e=a;A0?e.push(n<>g);break;case"ceiling":n=e.pop(),e.push(Math.ceil(n));break;case"copy":n=e.pop(),e.copy(n);break;case"cos":n=e.pop(),e.push(Math.cos(n%360/180*Math.PI));break;case"cvi":n=0|e.pop(),e.push(n);break;case"cvr":break;case"div":g=e.pop(),n=e.pop(),e.push(n/g);break;case"dup":e.copy(1);break;case"eq":g=e.pop(),n=e.pop(),e.push(n===g);break;case"exch":e.roll(2,1);break;case"exp":g=e.pop(),n=e.pop(),e.push(n**g);break;case"false":e.push(!1);break;case"floor":n=e.pop(),e.push(Math.floor(n));break;case"ge":g=e.pop(),n=e.pop(),e.push(n>=g);break;case"gt":g=e.pop(),n=e.pop(),e.push(n>g);break;case"idiv":g=e.pop(),n=e.pop(),e.push(n/g|0);break;case"index":n=e.pop(),e.index(n);break;case"le":g=e.pop(),n=e.pop(),e.push(n<=g);break;case"ln":n=e.pop(),e.push(Math.log(n));break;case"log":n=e.pop(),e.push(Math.log10(n));break;case"lt":g=e.pop(),n=e.pop(),e.push(n=e?new lg(e):A.max<=e?A:new ug(A,e)}class bg{compile(A,e,t){const i=[],a=[],s=e.length>>1,n=t.length>>1;let g,r,o,I,c,C,B,h,Q=0;for(let A=0;Ae.min&&(g.unshift("Math.max(",s,", "),g.push(")")),n4?(i=!0,e=0):(i=!1,e=1));const r=[];for(s=0;s=0&&"ET"===Lg[A];--A)Lg[A]="EN";for(let A=s+1;A0&&(e=Lg[s-1]);let t=c;A+1h&&Sg(h)&&(l=h);for(h=Q;h>=l;--h){let A=-1;for(s=0,n=r.length;s=0&&(xg(Mg,A,s),A=-1):A<0&&(A=s);A>=0&&xg(Mg,A,r.length)}for(s=0,n=Mg.length;s"!==A||(Mg[s]="")}return Ug(Mg.join(""),i)}const Hg={style:"normal",weight:"normal"},Yg={style:"normal",weight:"bold"},vg={style:"italic",weight:"normal"},Kg={style:"italic",weight:"bold"},qg=new Map([["Times-Roman",{local:["Times New Roman","Times-Roman","Times","Liberation Serif","Nimbus Roman","Nimbus Roman L","Tinos","Thorndale","TeX Gyre Termes","FreeSerif","Linux Libertine O","Libertinus Serif","DejaVu Serif","Bitstream Vera Serif","Ubuntu"],style:Hg,ultimate:"serif"}],["Times-Bold",{alias:"Times-Roman",style:Yg,ultimate:"serif"}],["Times-Italic",{alias:"Times-Roman",style:vg,ultimate:"serif"}],["Times-BoldItalic",{alias:"Times-Roman",style:Kg,ultimate:"serif"}],["Helvetica",{local:["Helvetica","Helvetica Neue","Arial","Arial Nova","Liberation Sans","Arimo","Nimbus Sans","Nimbus Sans L","A030","TeX Gyre Heros","FreeSans","DejaVu Sans","Albany","Bitstream Vera Sans","Arial Unicode MS","Microsoft Sans Serif","Apple Symbols","Cantarell"],path:"LiberationSans-Regular.ttf",style:Hg,ultimate:"sans-serif"}],["Helvetica-Bold",{alias:"Helvetica",path:"LiberationSans-Bold.ttf",style:Yg,ultimate:"sans-serif"}],["Helvetica-Oblique",{alias:"Helvetica",path:"LiberationSans-Italic.ttf",style:vg,ultimate:"sans-serif"}],["Helvetica-BoldOblique",{alias:"Helvetica",path:"LiberationSans-BoldItalic.ttf",style:Kg,ultimate:"sans-serif"}],["Courier",{local:["Courier","Courier New","Liberation Mono","Nimbus Mono","Nimbus Mono L","Cousine","Cumberland","TeX Gyre Cursor","FreeMono","Linux Libertine Mono O","Libertinus Mono"],style:Hg,ultimate:"monospace"}],["Courier-Bold",{alias:"Courier",style:Yg,ultimate:"monospace"}],["Courier-Oblique",{alias:"Courier",style:vg,ultimate:"monospace"}],["Courier-BoldOblique",{alias:"Courier",style:Kg,ultimate:"monospace"}],["ArialBlack",{local:["Arial Black"],style:{style:"normal",weight:"900"},fallback:"Helvetica-Bold"}],["ArialBlack-Bold",{alias:"ArialBlack"}],["ArialBlack-Italic",{alias:"ArialBlack",style:{style:"italic",weight:"900"},fallback:"Helvetica-BoldOblique"}],["ArialBlack-BoldItalic",{alias:"ArialBlack-Italic"}],["ArialNarrow",{local:["Arial Narrow","Liberation Sans Narrow","Helvetica Condensed","Nimbus Sans Narrow","TeX Gyre Heros Cn"],style:Hg,fallback:"Helvetica"}],["ArialNarrow-Bold",{alias:"ArialNarrow",style:Yg,fallback:"Helvetica-Bold"}],["ArialNarrow-Italic",{alias:"ArialNarrow",style:vg,fallback:"Helvetica-Oblique"}],["ArialNarrow-BoldItalic",{alias:"ArialNarrow",style:Kg,fallback:"Helvetica-BoldOblique"}],["Calibri",{local:["Calibri","Carlito"],style:Hg,fallback:"Helvetica"}],["Calibri-Bold",{alias:"Calibri",style:Yg,fallback:"Helvetica-Bold"}],["Calibri-Italic",{alias:"Calibri",style:vg,fallback:"Helvetica-Oblique"}],["Calibri-BoldItalic",{alias:"Calibri",style:Kg,fallback:"Helvetica-BoldOblique"}],["Wingdings",{local:["Wingdings","URW Dingbats"],style:Hg}],["Wingdings-Regular",{alias:"Wingdings"}],["Wingdings-Bold",{alias:"Wingdings"}]]),Tg=new Map([["Arial-Black","ArialBlack"]]);function Pg(A){const e=new Set(["thin","extralight","ultralight","demilight","semilight","light","book","regular","normal","medium","demibold","semibold","bold","extrabold","ultrabold","black","heavy","extrablack","ultrablack","roman","italic","oblique","ultracondensed","extracondensed","condensed","semicondensed","normal","semiexpanded","expanded","extraexpanded","ultraexpanded","bolditalic"]);return A.split(/[- ,+]+/g).filter((A=>!e.has(A.toLowerCase()))).join(" ")}function Wg({alias:A,local:e,path:t,fallback:i,style:a,ultimate:s},n,g,r=!0,o=!0,I=""){const c={style:null,ultimate:null};if(e){const A=I?` ${I}`:"";for(const t of e)n.push(`local(${t}${A})`)}if(A){const e=qg.get(A),s=I||function(A){switch(A){case Yg:return"Bold";case vg:return"Italic";case Kg:return"Bold Italic";default:if("bold"===A?.weight)return"Bold";if("italic"===A?.style)return"Italic"}return""}(a);Object.assign(c,Wg(e,n,g,r&&!i,o&&!t,s))}if(a&&(c.style=a),s&&(c.ultimate=s),r&&i){const A=qg.get(i),{ultimate:e}=Wg(A,n,g,r,o&&!t,I);c.ultimate||=e}return o&&t&&g&&n.push(`url(${g}${t})`),c}function Zg(A,e,t,i,a,s){if(i.startsWith("InvalidPDFjsFont_"))return null;"TrueType"!==s&&"Type1"!==s||!/^[A-Z]{6}\+/.test(i)||(i=i.slice(7));const n=i=Ea(i);let g=A.get(n);if(g)return g;let r=qg.get(i);if(!r)for(const[A,e]of Tg)if(i.startsWith(A)){i=`${e}${i.substring(A.length)}`,r=qg.get(i);break}let o=!1;r||(r=qg.get(a),o=!0);const I=`${e.getDocId()}_s${e.createFontId()}`;if(!r){if(!jA(i))return N(`Cannot substitute the font because of its name: ${i}`),A.set(n,null),null;const e=/bold/gi.test(i),t=/oblique|italic/gi.test(i),a=e&&t&&Kg||e&&Yg||t&&vg||Hg;return g={css:`"${Pg(i)}",${I}`,guessFallback:!0,loadedName:I,baseFontName:i,src:`local(${i})`,style:a},A.set(n,g),g}const c=[];o&&jA(i)&&c.push(`local(${i})`);const{style:C,ultimate:B}=Wg(r,c,t),h=null===B,Q=h?"":`,${B}`;return g={css:`"${Pg(i)}",${I}${Q}`,guessFallback:h,loadedName:I,baseFontName:i,src:c.join(","),style:C},A.set(n,g),g}class Og{constructor(A,e){this._imgData=A,this._isMask=e}static needsToBeResized(A,e){if(A<=this._goodSquareLength&&e<=this._goodSquareLength)return!1;const{MAX_DIM:t}=this;if(A>t||e>t)return!0;const i=A*e;return this._hasMaxArea?i>this.MAX_AREA:!(i(this.MAX_AREA=this._goodSquareLength**2)))}static get MAX_DIM(){return L(this,"MAX_DIM",this._guessMax(2048,65537,0,1))}static get MAX_AREA(){return this._hasMaxArea=!0,L(this,"MAX_AREA",this._guessMax(Og._goodSquareLength,this.MAX_DIM,128,0)**2)}static set MAX_AREA(A){A>=0&&(this._hasMaxArea=!0,L(this,"MAX_AREA",A))}static setMaxArea(A){this._hasMaxArea||(this.MAX_AREA=A>>2)}static _areGoodDims(A,e){try{const t=new OffscreenCanvas(A,e),i=t.getContext("2d");i.fillRect(0,0,1,1);const a=i.getImageData(0,0,1,1).data[3];return t.width=t.height=1,0!==a}catch{return!1}}static _guessMax(A,e,t,i){for(;A+t+1>3,n=t+3&-4;if(t!==n){const A=new Uint8Array(n*e);let i=0;for(let s=0,g=e*t;s>>8,e[t++]=255&a)}}else{if(!ArrayBuffer.isView(A))throw new Error("Invalid data format, must be a string or TypedArray.");e=A.slice(),t=e.byteLength}const i=t>>2,a=t-4*i,s=new Uint32Array(e.buffer,0,i);let n=0,g=0,r=this.h1,o=this.h2;const I=3432918353,c=461845907,C=11601,B=13715;for(let A=0;A>>17,n=n*c&Vg|n*B&jg,r^=n,r=r<<13|r>>>19,r=5*r+3864292196):(g=s[A],g=g*I&Vg|g*C&jg,g=g<<15|g>>>17,g=g*c&Vg|g*B&jg,o^=g,o=o<<13|o>>>19,o=5*o+3864292196);switch(n=0,a){case 3:n^=e[4*i+2]<<16;case 2:n^=e[4*i+1]<<8;case 1:n^=e[4*i],n=n*I&Vg|n*C&jg,n=n<<15|n>>>17,n=n*c&Vg|n*B&jg,1&i?r^=n:o^=n}this.h1=r,this.h2=o}hexdigest(){let A=this.h1,e=this.h2;return A^=e>>>1,A=3981806797*A&Vg|36045*A&jg,e=4283543511*e&Vg|(2950163797*(e<<16|A>>>16)&Vg)>>>16,A^=e>>>1,A=444984403*A&Vg|60499*A&jg,e=3301882366*e&Vg|(3120437893*(e<<16|A>>>16)&Vg)>>>16,A^=e>>>1,(A>>>0).toString(16).padStart(8,"0")+(e>>>0).toString(16).padStart(8,"0")}}function _g(A,e,t,i,a){let s=A;for(let A=0,t=e.length-1;A1e3&&(o=Math.max(o,C),B+=c+2,C=0,c=0),I.push({transform:e,x:C,y:B,w:t.width,h:t.height}),C+=t.width+2,c=Math.max(c,t.height)}const h=Math.max(o,C)+1,Q=B+c+1,l=new Uint8Array(h*Q*4),E=h<<2;for(let A=0;A=0;)e[s-4]=e[s],e[s-3]=e[s+1],e[s-2]=e[s+2],e[s-1]=e[s+3],e[s+t]=e[s+t-4],e[s+t+1]=e[s+t-3],e[s+t+2]=e[s+t-2],e[s+t+3]=e[s+t-1],s-=E}const u={width:h,height:Q};if(A.isOffscreenCanvasSupported){const A=new OffscreenCanvas(h,Q);A.getContext("2d").putImageData(new ImageData(new Uint8ClampedArray(l.buffer),h,Q),0,0),u.bitmap=A.transferToImageBitmap(),u.data=null}else u.kind=3,u.data=l;return t.splice(s,4*r,87),i.splice(s,4*r,[u,I]),s+1})),_g($g,[u,f,k,d],null,(function(A,e){const t=A.fnArray,i=(e-(A.iCurr-3))%4;switch(i){case 0:return t[e]===u;case 1:return t[e]===f;case 2:return t[e]===k;case 3:return t[e]===d}throw new Error(`iterateImageMaskGroup - invalid pos: ${i}`)}),(function(A,e){const t=A.fnArray,i=A.argsArray,a=A.iCurr,s=a-3,n=a-2,g=a-1;let r=Math.floor((e-s)/4);if(r<10)return e-(e-s)%4;let o,I,c=!1;const C=i[g][0],B=i[n][0],h=i[n][1],Q=i[n][2],l=i[n][3];if(h===Q){c=!0,o=n+4;let A=g+4;for(let e=1;e=4&&t[s-4]===t[n]&&t[s-3]===t[g]&&t[s-2]===t[r]&&t[s-1]===t[o]&&i[s-4][0]===I&&i[s-4][1]===c&&(C++,B-=5);let h=B+4;for(let A=1;A=t)break}i=(i||$g)[A[e]],i&&!Array.isArray(i)?(s.iCurr=e,e++,!i.checkFn||(0,i.checkFn)(s)?(a=i,i=null):i=null):e++}this.state=i,this.match=a,this.lastProcessed=e}flush(){for(;this.match;){const A=this.queue.fnArray.length;this.lastProcessed=(0,this.match.processFn)(this.context,A),this.match=null,this.state=null,this._optimize()}}reset(){this.state=null,this.match=null,this.lastProcessed=0}}class tr{static CHUNK_SIZE=1e3;static CHUNK_SIZE_ABOUT=this.CHUNK_SIZE-5;constructor(A=0,e){this._streamSink=e,this.fnArray=[],this.argsArray=[],this.optimizer=!e||256&A?new Ar(this):new er(this),this.dependencies=new Set,this._totalLength=0,this.weight=0,this._resolved=e?null:Promise.resolve()}set isOffscreenCanvasSupported(A){this.optimizer.isOffscreenCanvasSupported=A}get length(){return this.argsArray.length}get ready(){return this._resolved||this._streamSink.ready}get totalLength(){return this._totalLength+this.length}addOp(A,e){this.optimizer.push(A,e),this.weight++,this._streamSink&&(this.weight>=tr.CHUNK_SIZE||this.weight>=tr.CHUNK_SIZE_ABOUT&&(A===d||32===A))&&this.flush()}addImageOps(A,e,t){void 0!==t&&this.addOp(D,["OC",t]),this.addOp(A,e),void 0!==t&&this.addOp(b,[])}addDependency(A){this.dependencies.has(A)||(this.dependencies.add(A),this.addOp(1,[A]))}addDependencies(A){for(const e of A)this.addDependency(e)}addOpList(A){if(A instanceof tr){for(const e of A.dependencies)this.dependencies.add(e);for(let e=0,t=A.length;ei&&(A=i),A}function ar(A,e,t,i,a,s){const n=a*s;let g;g=e<=8?new Uint8Array(n):e<=16?new Uint16Array(n):new Uint32Array(n);const r=t/a,o=i/s;let I,c,C,B,h=0;const Q=new Uint16Array(a),l=t;for(I=0;I0&&Number.isInteger(t.height)&&t.height>0&&(t.width!==C||t.height!==B)&&(N("PDFImage - using the Width/Height of the image data, rather than the image dictionary."),C=t.width,B=t.height),C<1||B<1)throw new T(`Invalid image width: ${C} or height: ${B}`);this.width=C,this.height=B,this.interpolate=o.get("I","Interpolate"),this.imageMask=o.get("IM","ImageMask")||!1,this.matte=o.get("Matte")||!1;let h=t.bitsPerComponent;if(!h&&(h=o.get("BPC","BitsPerComponent"),!h)){if(!this.imageMask)throw new T(`Bits per component missing in image: ${this.imageMask}`);h=1}if(this.bpc=h,!this.imageMask){let a=o.getRaw("CS")||o.getRaw("ColorSpace");const s=!!a;if(s)this.jpxDecoderOptions?.smaskInData&&(a=cA.get("DeviceRGBA"));else if(this.jpxDecoderOptions)a=cA.get("DeviceRGBA");else switch(t.numComps){case 1:a=cA.get("DeviceGray");break;case 3:a=cA.get("DeviceRGB");break;case 4:a=cA.get("DeviceCMYK");break;default:throw new Error(`Images with ${t.numComps} color components not supported.`)}this.colorSpace=ce.parse({cs:a,xref:A,resources:i?e:null,pdfFunctionFactory:g,localColorSpaceCache:r}),this.numComps=this.colorSpace.numComps,this.jpxDecoderOptions&&(this.jpxDecoderOptions.numComponents=s?this.numComp:0,this.jpxDecoderOptions.isIndexedColormap="Indexed"===this.colorSpace.name)}if(this.decode=o.getArray("D","Decode"),this.needsDecode=!1,this.decode&&(this.colorSpace&&!this.colorSpace.isDefaultDecode(this.decode,h)||n&&!ce.isDefaultDecode(this.decode,1))){this.needsDecode=!0;const A=(1<>3)*t,g=A.byteLength;let r,o;if(!i||a&&n!==g?a?(r=new Uint8Array(n),r.set(A),r.fill(255,g)):r=new Uint8Array(A):r=A,a)for(o=0;o>7&1,n[C+1]=c>>6&1,n[C+2]=c>>5&1,n[C+3]=c>>4&1,n[C+4]=c>>3&1,n[C+5]=c>>2&1,n[C+6]=c>>1&1,n[C+7]=1&c,C+=8;if(C>=1}}else{let t=0;for(c=0,C=0,I=s;C>i;a<0?a=0:a>o&&(a=o),n[C]=a,c&=(1<n[i+1]){e=255;break}}g[I]=e}}}if(g)for(I=0,C=3,c=e*i;I>3,I=e&&Og.needsToBeResized(t,i);if("DeviceRGBA"===this.colorSpace.name){a.kind=3;const A=a.data=await this.getImageBytes(g*n*4,{});return e?I?Og.createImage(a,!1):this.createBitmap(3,t,i,A):a}if(!A){let A;if("DeviceGray"===this.colorSpace.name&&1===r?A=1:"DeviceRGB"!==this.colorSpace.name||8!==r||this.needsDecode||(A=2),A&&!this.smask&&!this.mask&&t===n&&i===g){const s=await this.getImageBytes(g*o,{});if(e)return I?Og.createImage({data:s,kind:A,width:t,height:i,interpolate:this.interpolate},this.needsDecode):this.createBitmap(A,n,g,s);if(a.kind=A,a.data=s,this.needsDecode){U(1===A,"PDFImage.createImageData: The image must be grayscale.");const e=a.data;for(let A=0,t=e.length;A>3,n=await this.getImageBytes(i*s,{internal:!0}),g=this.getComponents(n);let r,o;if(1===a){if(o=t*i,this.needsDecode)for(r=0;r>2,r=new Uint32Array(A.buffer,e,g);if(V.isLittleEndian){for(;n>>24|e<<8|4278190080,t[i+2]=e>>>16|a<<16|4278190080,t[i+3]=a>>>8|4278190080}for(let e=4*n,a=A.length;e>>8|255,t[i+2]=e<<16|a>>>16|255,t[i+3]=a<<8|255}for(let e=4*n,a=A.length;e0&&e.args[0].count++}class Ir{static TIME_SLOT_DURATION_MS=20;static CHECK_TIME_EVERY=100;constructor(){this.reset()}check(){return!(++this.checkedc){const A="Image exceeded maximum allowed size and was removed.";if(this.options.ignoreErrors)return void N(A);throw new Error(A)}let C,B,h;if(g.has("OC")&&(C=await this.parseMarkedContentProps(g.get("OC"),A)),g.get("IM","ImageMask")){const A=g.get("I","Interpolate"),t=o+7>>3,n=e.getBytes(t*I),c=g.getArray("D","Decode");if(this.parsingType3Font){if(B=sr.createRawMask({imgArray:n,width:o,height:I,imageIsFromDecodeStream:e instanceof Re,inverseDecode:c?.[0]>0,interpolate:A}),B.cached=!!a,h=[B],i.addImageOps(k,h,C),a){const A={fn:k,args:h,optionalContent:C};s.set(a,r,A),r&&this._regionalImageCache.set(null,r,A)}return}if(B=await sr.createMask({imgArray:n,width:o,height:I,imageIsFromDecodeStream:e instanceof Re,inverseDecode:c?.[0]>0,interpolate:A,isOffscreenCanvasSupported:this.options.isOffscreenCanvasSupported}),B.isSingleOpaquePixel){if(i.addImageOps(90,[],C),a){const A={fn:90,args:[],optionalContent:C};s.set(a,r,A),r&&this._regionalImageCache.set(null,r,A)}return}const Q=`mask_${this.idFactory.createObjId()}`;if(i.addDependency(Q),B.dataLen=B.bitmap?B.width*B.height*4:B.data.length,this._sendImgData(Q,B),h=[{data:Q,width:B.width,height:B.height,interpolate:B.interpolate,count:1}],i.addImageOps(k,h,C),a){const A={objId:Q,fn:k,args:h,optionalContent:C};s.set(a,r,A),r&&this._regionalImageCache.set(null,r,A)}return}if(t&&o+I<200&&!g.has("SMask")&&!g.has("Mask")){try{const a=new sr({xref:this.xref,res:A,image:e,isInline:t,pdfFunctionFactory:this._pdfFunctionFactory,localColorSpaceCache:n});B=await a.createImageData(!0,!1),i.isOffscreenCanvasSupported=this.options.isOffscreenCanvasSupported,i.addImageOps(86,[B],C)}catch(A){const e=`Unable to decode inline image: "${A}".`;if(!this.options.ignoreErrors)throw new Error(e);N(e)}return}let Q=`img_${this.idFactory.createObjId()}`,l=!1;if(this.parsingType3Font?Q=`${this.idFactory.getDocId()}_type3_${Q}`:a&&r&&(l=this.globalImageCache.shouldCache(r,this.pageIndex),l&&(U(!t,"Cannot cache an inline image globally."),Q=`${this.idFactory.getDocId()}_${Q}`)),i.addDependency(Q),h=[Q,o,I],i.addImageOps(F,h,C),l){if(this.globalImageCache.hasDecodeFailed(r))return this.globalImageCache.setData(r,{objId:Q,fn:F,args:h,optionalContent:C,byteSize:0}),void this._sendImgData(Q,null,l);if(o*I>25e4||g.has("SMask")||g.has("Mask")){const A=await this.handler.sendWithPromise("commonobj",[Q,"CopyLocalImage",{imageRef:r}]);if(A)return this.globalImageCache.setData(r,{objId:Q,fn:F,args:h,optionalContent:C,byteSize:0}),void this.globalImageCache.addByteSize(r,A)}}if(sr.buildImage({xref:this.xref,res:A,image:e,isInline:t,pdfFunctionFactory:this._pdfFunctionFactory,localColorSpaceCache:n}).then((async A=>(B=await A.createImageData(!1,this.options.isOffscreenCanvasSupported),B.dataLen=B.bitmap?B.width*B.height*4:B.data.length,B.ref=r,l&&this.globalImageCache.addByteSize(r,B.dataLen),this._sendImgData(Q,B,l)))).catch((A=>(N(`Unable to decode image "${Q}": "${A}".`),r&&this.globalImageCache.addDecodeFailed(r),this._sendImgData(Q,null,l)))),a){const A={objId:Q,fn:F,args:h,optionalContent:C};s.set(a,r,A),r&&(this._regionalImageCache.set(null,r,A),l&&this.globalImageCache.setData(r,{objId:Q,fn:F,args:h,optionalContent:C,byteSize:0}))}}handleSMask(A,e,t,i,a,s){const n=A.get("G"),g={subtype:A.get("S").name,backdrop:A.get("BC")},r=A.get("TR");if(cg(r)){const A=this._pdfFunctionFactory.create(r),e=new Uint8Array(256),t=new Float32Array(1);for(let i=0;i<256;i++)t[0]=i/255,A(t,0,t,0),e[i]=255*t[0]|0;g.transferMap=e}return this.buildFormXObject(e,n,g,t,i,a.state.clone(),s)}handleTransferFunction(A){let e;if(Array.isArray(A))e=A;else{if(!cg(A))return null;e=[A]}const t=[];let i=0,a=0;for(const A of e){const e=this.xref.fetchIfRef(A);if(i++,uA(e,"Identity")){t.push(null);continue}if(!cg(e))return null;const s=this._pdfFunctionFactory.create(e),n=new Uint8Array(256),g=new Float32Array(1);for(let A=0;A<256;A++)g[0]=A/255,s(g,0,g,0),n[A]=255*g[0]|0;t.push(n),a++}return 1!==i&&4!==i||0===a?null:t}handleTilingType(A,e,t,i,a,s,n,g){const r=new tr,o=hA.merge({xref:this.xref,dictArray:[a.get("Resources"),t]});return this.getOperatorList({stream:i,task:n,resources:o,operatorList:r}).then((function(){const t=r.getIR(),i=nn(t,a,e);s.addDependencies(r.dependencies),s.addOp(A,i),a.objId&&g.set(null,a.objId,{operatorListIR:t,dict:a})})).catch((A=>{if(!(A instanceof P)){if(!this.options.ignoreErrors)throw A;N(`handleTilingType - ignoring pattern: "${A}".`)}}))}async handleSetFont(A,e,t,i,a,s,n=null,g=null){const r=e?.[0]instanceof cA?e[0].name:null;let o=await this.loadFont(r,t,A,n,g);if(o.font.isType3Font)try{await o.loadType3Data(this,A,a),i.addDependencies(o.type3Dependencies)}catch(A){o=new Cr({loadedName:"g_font_error",font:new js(`Type3 font load error: ${A}`),dict:o.font,evaluatorOptions:this.options})}return s.font=o.font,o.send(this.handler),o.loadedName}handleText(A,e){const t=e.font,i=t.charsToGlyphs(A);return t.data&&(4&e.textRenderingMode||"Pattern"===e.fillColorSpace.name||t.disableFontFace||this.options.disableFontFace)&&cr.buildFontPaths(t,i,this.handler,this.options),i}ensureStateFont(A){if(A.font)return;const e=new T("Missing setFont (Tf) operator before text rendering operator.");if(!this.options.ignoreErrors)throw e;N(`ensureStateFont: "${e}".`)}async setGState({resources:A,gState:e,operatorList:t,cacheKey:i,task:a,stateManager:s,localGStateCache:n,localColorSpaceCache:g}){const r=e.objId;let o=!0;const I=[];let c=Promise.resolve();for(const i of e.getKeys()){const n=e.get(i);switch(i){case"Type":break;case"LW":case"LC":case"LJ":case"ML":case"D":case"RI":case"FL":case"CA":case"ca":I.push([i,n]);break;case"Font":o=!1,c=c.then((()=>this.handleSetFont(A,null,n[0],t,a,s.state).then((function(A){t.addDependency(A),I.push([i,[A,n[1]]])}))));break;case"BM":I.push([i,rr(n)]);break;case"SMask":if(uA(n,"None")){I.push([i,!1]);break}n instanceof hA?(o=!1,c=c.then((()=>this.handleSMask(n,A,t,a,s,g))),I.push([i,!0])):N("Unsupported SMask type");break;case"TR":const e=this.handleTransferFunction(n);I.push([i,e]);break;case"OP":case"op":case"OPM":case"BG":case"BG2":case"UCR":case"UCR2":case"TR2":case"HT":case"SM":case"SA":case"AIS":case"TK":G("graphic state operator "+i);break;default:G("Unknown graphic state operator "+i)}}await c,I.length>0&&t.addOp(9,[I]),o&&n.set(i,r,I)}loadFont(A,e,t,i=null,a=null){const s=async()=>new Cr({loadedName:"g_font_error",font:new js(`Font "${A}" is not available.`),dict:e,evaluatorOptions:this.options});let n;if(e)e instanceof QA&&(n=e);else{const e=t.get("Font");e&&(n=e.getRaw(A))}if(n){if(this.type3FontRefs?.has(n))return s();if(this.fontCache.has(n))return this.fontCache.get(n);try{e=this.xref.fetchIfRef(n)}catch(A){N(`loadFont - lookup failed: "${A}".`)}}if(!(e instanceof hA)){if(!this.options.ignoreErrors&&!this.parsingType3Font)return N(`Font "${A}" is not available.`),s();N(`Font "${A}" is not available -- attempting to fallback to a default font.`),e=i||cr.fallbackFontDict}if(e.cacheKey&&this.fontCache.has(e.cacheKey))return this.fontCache.get(e.cacheKey);const{promise:g,resolve:r}=Promise.withResolvers();let o;try{o=this.preEvaluateFont(e),o.cssFontInfo=a}catch(A){return N(`loadFont - preEvaluateFont failed: "${A}".`),s()}const{descriptor:I,hash:c}=o,C=n instanceof QA;let B;if(c&&I instanceof hA){const A=I.fontAliases||=Object.create(null);if(A[c]){const e=A[c].aliasRef;if(C&&e&&this.fontCache.has(e))return this.fontCache.putAlias(n,e),this.fontCache.get(n)}else A[c]={fontID:this.idFactory.createFontId()};C&&(A[c].aliasRef=n),B=A[c].fontID}else B=this.idFactory.createFontId();return U(B?.startsWith("f"),'The "fontID" must be (correctly) defined.'),C?this.fontCache.put(n,g):(e.cacheKey=`cacheKey_${B}`,this.fontCache.put(e.cacheKey,g)),e.loadedName=`${this.idFactory.getDocId()}_${B}`,this.translateFont(o).then((A=>{r(new Cr({loadedName:e.loadedName,font:A,dict:e,evaluatorOptions:this.options}))})).catch((A=>{N(`loadFont - translateFont failed: "${A}".`),r(new Cr({loadedName:e.loadedName,font:new js(A instanceof Error?A.message:A),dict:e,evaluatorOptions:this.options}))})),g}buildPath(A,e,t,i=!1){const a=A.length-1;if(t||(t=[]),a<0||91!==A.fnArray[a]){let a;switch(i&&(N(`Encountered path operator "${e}" inside of a text object.`),A.addOp(u,null)),e){case 19:const A=t[0]+t[2],e=t[1]+t[3];a=[Math.min(t[0],A),Math.min(t[1],e),Math.max(t[0],A),Math.max(t[1],e)];break;case 13:case 14:a=[t[0],t[1],t[0],t[1]];break;default:a=[1/0,1/0,-1/0,-1/0]}A.addOp(91,[[e],t,a]),i&&A.addOp(d,null)}else{const i=A.argsArray[a];i[0].push(e),i[1].push(...t);const s=i[2];switch(e){case 19:const A=t[0]+t[2],e=t[1]+t[3];s[0]=Math.min(s[0],t[0],A),s[1]=Math.min(s[1],t[1],e),s[2]=Math.max(s[2],t[0],A),s[3]=Math.max(s[3],t[1],e);break;case 13:case 14:s[0]=Math.min(s[0],t[0]),s[1]=Math.min(s[1],t[1]),s[2]=Math.max(s[2],t[0]),s[3]=Math.max(s[3],t[1])}}}parseColorSpace({cs:A,resources:e,localColorSpaceCache:t}){return ce.parseAsync({cs:A,xref:this.xref,resources:e,pdfFunctionFactory:this._pdfFunctionFactory,localColorSpaceCache:t}).catch((A=>{if(A instanceof P)return null;if(this.options.ignoreErrors)return N(`parseColorSpace - ignoring ColorSpace: "${A}".`),null;throw A}))}parseShading({shading:A,resources:e,localColorSpaceCache:t,localShadingPatternCache:i}){let a,s=i.get(A);if(s)return s;try{a=zs.parseShading(A,this.xref,e,this._pdfFunctionFactory,t).getIR()}catch(e){if(e instanceof P)return null;if(this.options.ignoreErrors)return N(`parseShading - ignoring shading: "${e}".`),i.set(A,null),null;throw e}return s=`pattern_${this.idFactory.createObjId()}`,this.parsingType3Font&&(s=`${this.idFactory.getDocId()}_type3_${s}`),i.set(A,s),this.parsingType3Font?this.handler.send("commonobj",[s,"Pattern",a]):this.handler.send("obj",[s,this.pageIndex,"Pattern",a]),s}handleColorN(A,e,t,i,a,s,n,g,r,o){const I=t.pop();if(I instanceof cA){const c=a.getRaw(I.name),C=c instanceof QA&&r.getByRef(c);if(C)try{const a=i.base?i.base.getRgb(t,0):null,s=nn(C.operatorListIR,C.dict,a);return void A.addOp(e,s)}catch{}const B=this.xref.fetchIfRef(c);if(B){const a=B instanceof mA?B.dict:B,I=a.get("PatternType");if(1===I){const g=i.base?i.base.getRgb(t,0):null;return this.handleTilingType(e,g,s,B,a,A,n,r)}if(2===I){const t=a.get("Shading"),i=this.parseShading({shading:t,resources:s,localColorSpaceCache:g,localShadingPatternCache:o});if(i){const t=YA(a.getArray("Matrix"),null);A.addOp(e,["Shading",i,t])}return}throw new T(`Unknown PatternType: ${I}`)}}throw new T(`Unknown PatternName: ${I}`)}_parseVisibilityExpression(A,e,t){if(++e>10)return void N("Visibility expression is too deeply nested");const i=A.length,a=this.xref.fetchIfRef(A[0]);if(!(i<2)&&a instanceof cA){switch(a.name){case"And":case"Or":case"Not":t.push(a.name);break;default:return void N(`Invalid operator ${a.name} in visibility expression`)}for(let a=1;a0)return{type:"OCMD",expression:e}}const e=t.get("OCGs");if(Array.isArray(e)||e instanceof hA){const A=[];if(Array.isArray(e))for(const t of e)A.push(t.toString());else A.push(e.objId);return{type:i,ids:A,policy:t.get("P")instanceof cA?t.get("P").name:null,expression:null}}if(e instanceof QA)return{type:i,id:e.toString()}}return null}getOperatorList({stream:A,task:e,resources:t,operatorList:i,initialState:a=null,fallbackFontDict:s=null}){if(t||=hA.empty,a||=new Qr,!i)throw new Error('getOperatorList: missing "operatorList" parameter');const n=this,g=this.xref;let r=!1;const o=new eg,I=new tg,c=new ag,C=new sg,B=new Map,h=t.get("XObject")||hA.empty,Q=t.get("Pattern")||hA.empty,l=new Br(a),E=new lr(A,g,l),u=new Ir;function f(A){for(let A=0,e=E.savedStatesDepth;A0&&i.addOp(9,[e]),A=null;continue}}return void b(new Promise((function(A,a){if(!M)throw new T("GState must be referred to by name.");const s=t.get("ExtGState");if(!(s instanceof hA))throw new T("ExtGState should be a dictionary.");const g=s.get(U);if(!(g instanceof hA))throw new T("GState should be a dictionary.");n.setGState({resources:t,gState:g,operatorList:i,cacheKey:U,task:e,stateManager:l,localGStateCache:c,localColorSpaceCache:I}).then(A,a)})).catch((function(A){if(!(A instanceof P)){if(!n.options.ignoreErrors)throw A;N(`getOperatorList - ignoring ExtGState: "${A}".`)}})));case 13:case 14:case 15:case 16:case 17:case 18:case 19:n.buildPath(i,a,A,r);continue;case 67:case 68:case 72:case 73:continue;case D:if(!(A[0]instanceof cA)){N(`Expected name for beginMarkedContentProps arg0=${A[0]}`),i.addOp(D,["OC",null]);continue}if("OC"===A[0].name)return void b(n.parseMarkedContentProps(A[1],t).then((A=>{i.addOp(D,["OC",A])})).catch((A=>{if(!(A instanceof P)){if(n.options.ignoreErrors)return N(`getOperatorList - ignoring beginMarkedContentProps: "${A}".`),void i.addOp(D,["OC",null]);throw A}})));A=[A[0].name,A[1]instanceof hA?A[1].get("MCID"):null];break;default:if(null!==A){for(S=0,R=A.length;S{if(!(A instanceof P)){if(this.options.ignoreErrors)return N(`getOperatorList - ignoring errors during "${e.name}" task: "${A}".`),void f();throw A}}))}getTextContent({stream:A,task:e,resources:t,stateManager:s=null,includeMarkedContent:n=!1,sink:g,seenStyles:r=new Set,viewBox:o,lang:I=null,markedContentData:c=null,disableNormalization:C=!1,keepWhiteSpace:B=!1}){t||=hA.empty,s||=new Br(new hr),n&&(c||={level:0});const h={items:[],styles:Object.create(null),lang:I},Q={initialized:!1,str:[],totalWidth:0,totalHeight:0,width:0,height:0,vertical:!1,prevTransform:null,textAdvanceScale:0,spaceInFlowMin:0,spaceInFlowMax:0,trackingSpaceMin:1/0,negativeSpaceMax:-1/0,notASpace:-1/0,transform:null,fontName:null,hasEOL:!1},l=[" "," "];let E=0;function u(A){const e=(E+1)%2,t=" "!==l[E]&&" "===l[e];return l[E]=A,E=e,!B&&t}function f(){return!B&&" "!==l[E]&&" "===l[(E+1)%2]}function y(){l[0]=l[1]=" ",E=0}const w=this,k=this.xref,F=[];let S=null;const R=new eg,G=new ag,x=new lr(A,k,s);let U;function M({width:A=0,height:e=0,transform:t=Q.prevTransform,fontName:i=Q.fontName}){h.items.push({str:" ",dir:"ltr",width:A,height:e,transform:t,fontName:i,hasEOL:!1})}function L(){const A=U.font,e=[U.fontSize*U.textHScale,0,0,U.fontSize,0,U.textRise];if(A.isType3Font&&(U.fontSize<=1||A.isCharBBox)&&!tA(U.fontMatrix,a)){const t=A.bbox[3]-A.bbox[1];t>0&&(e[3]*=t*U.fontMatrix[3])}return z.transform(U.ctm,z.transform(U.textMatrix,e))}function J(){if(Q.initialized)return Q;const{font:A,loadedName:e}=U;if(!r.has(e)&&(r.add(e),h.styles[e]={fontFamily:A.fallbackName,ascent:A.ascent,descent:A.descent,vertical:A.vertical},w.options.fontExtraProperties&&A.systemFontInfo)){const t=h.styles[e];t.fontSubstitution=A.systemFontInfo.css,t.fontSubstitutionLoadedName=A.systemFontInfo.loadedName}Q.fontName=e;const t=Q.transform=L();A.vertical?(Q.width=Q.totalWidth=Math.hypot(t[0],t[1]),Q.height=Q.totalHeight=0,Q.vertical=!0):(Q.width=Q.totalWidth=0,Q.height=Q.totalHeight=Math.hypot(t[2],t[3]),Q.vertical=!1);const i=Math.hypot(U.textLineMatrix[0],U.textLineMatrix[1]),a=Math.hypot(U.ctm[0],U.ctm[1]);Q.textAdvanceScale=a*i;const{fontSize:s}=U;return Q.trackingSpaceMin=.102*s,Q.notASpace=.03*s,Q.negativeSpaceMax=-.2*s,Q.spaceInFlowMin=.102*s,Q.spaceInFlowMax=.6*s,Q.hasEOL=!1,Q.initialized=!0,Q}function H(){if(!Q.initialized)return;const A=Math.hypot(U.textLineMatrix[0],U.textLineMatrix[1]),e=Math.hypot(U.ctm[0],U.ctm[1])*A;e!==Q.textAdvanceScale&&(Q.vertical?(Q.totalHeight+=Q.height*Q.textAdvanceScale,Q.height=0):(Q.totalWidth+=Q.width*Q.textAdvanceScale,Q.width=0),Q.textAdvanceScale=e)}async function Y(A,i){const s=await w.loadFont(A,i,t);if(s.font.isType3Font)try{await s.loadType3Data(w,t,e)}catch{}U.loadedName=s.loadedName,U.font=s.font,U.fontMatrix=s.font.fontMatrix||a}function v(A,e,t){const i=Math.hypot(t[0],t[1]);return[(t[0]*A+t[1]*e)/i,(t[2]*A+t[3]*e)/i]}function K(A){const e=L();let t=e[4],i=e[5];if(U.font?.vertical){if(to[2]||i+Ao[3])return!1}else if(t+Ao[2]||io[3])return!1;if(!U.font||!Q.prevTransform)return!0;let a=Q.prevTransform[4],s=Q.prevTransform[5];if(a===t&&s===i)return!0;let n=-1;switch(e[0]&&0===e[1]&&0===e[2]?n=e[0]>0?0:180:e[1]&&0===e[0]&&0===e[3]&&(n=e[1]>0?90:270),n){case 0:break;case 90:[t,i]=[i,t],[a,s]=[s,a];break;case 180:[t,i,a,s]=[-t,-i,-a,-s];break;case 270:[t,i]=[-i,-t],[a,s]=[-s,-a];break;default:[t,i]=v(t,i,e),[a,s]=v(a,s,Q.prevTransform)}if(U.font.vertical){const A=(s-i)/Q.textAdvanceScale,e=t-a,n=Math.sign(Q.height);return A.5*Q.width?(W(),!0):(y(),O(),!0):Math.abs(e)>Q.width?(W(),!0):(A<=n*Q.notASpace&&y(),A<=n*Q.trackingSpaceMin?f()?(y(),O(),M({height:Math.abs(A)})):Q.height+=A:Z(A,Q.prevTransform,n)||(0===Q.str.length?(y(),M({height:Math.abs(A)})):Q.height+=A),Math.abs(e)>.25*Q.width&&O(),!0)}const g=(t-a)/Q.textAdvanceScale,r=i-s,I=Math.sign(Q.width);return g.5*Q.height?(W(),!0):(y(),O(),!0):Math.abs(r)>Q.height?(W(),!0):(g<=I*Q.notASpace&&y(),g<=I*Q.trackingSpaceMin?f()?(y(),O(),M({width:Math.abs(g)})):Q.width+=g:Z(g,Q.prevTransform,I)||(0===Q.str.length?(y(),M({width:Math.abs(g)})):Q.width+=g),Math.abs(r)>.25*Q.height&&O(),!0)}function q({chars:A,extraSpacing:e}){const t=U.font;if(!A){const A=U.charSpacing+e;return A&&(t.vertical?U.translateTextMatrix(0,-A):U.translateTextMatrix(A*U.textHScale,0)),void(B&&K(0))}const i=t.charsToGlyphs(A),a=U.fontMatrix[0]*U.fontSize;for(let A=0,s=i.length;Ae?e.normalize("NFKC"):sA.get(t))));const i=Jg(e,-1,A.vertical);return{str:i.str,dir:i.dir,width:Math.abs(A.totalWidth),height:Math.abs(A.totalHeight),transform:A.transform,fontName:A.fontName,hasEOL:A.hasEOL}}(Q)),Q.initialized=!1,Q.str.length=0)}function X(A=!1){const e=h.items.length;0!==e&&(A&&e<10||(g.enqueue(h,e),h.items=[],h.styles=Object.create(null)))}const V=new Ir;return new Promise((function A(a,Q){const l=function(e){X(!0),Promise.all([e,g.ready]).then((function(){try{A(a,Q)}catch(A){Q(A)}}),Q)};e.ensureNotTerminated(),V.reset();const E={};let u,f=[];for(;!(u=V.check())&&(f.length=0,E.args=f,x.read(E));){const A=U;U=s.state;const a=E.fn;switch(f=E.args,0|a){case p:var y=f[0].name,M=f[1];if(U.font&&y===U.fontName&&M===U.fontSize)break;return O(),U.fontName=y,U.fontSize=M,void l(Y(y,null));case 39:U.textRise=f[0];break;case 35:U.textHScale=f[0]/100;break;case 36:U.leading=f[0];break;case 40:U.translateTextLineMatrix(f[0],f[1]),U.textMatrix=U.textLineMatrix.slice();break;case 41:U.leading=-f[1],U.translateTextLineMatrix(f[0],f[1]),U.textMatrix=U.textLineMatrix.slice();break;case 43:U.carriageReturn();break;case 42:U.setTextMatrix(f[0],f[1],f[2],f[3],f[4],f[5]),U.setTextLineMatrix(f[0],f[1],f[2],f[3],f[4],f[5]),H();break;case 33:U.charSpacing=f[0];break;case 34:U.wordSpacing=f[0];break;case 31:U.textMatrix=i.slice(),U.textLineMatrix=i.slice();break;case 45:if(!s.state.font){w.ensureStateFont(s.state);continue}const a=(U.font.vertical?1:-1)*U.fontSize/1e3,Q=f[0];for(let A=0,e=Q.length;A0){const A=F.join("");F.length=0,q({chars:A,extraSpacing:0})}break;case m:if(!s.state.font){w.ensureStateFont(s.state);continue}q({chars:f[0],extraSpacing:0});break;case 46:if(!s.state.font){w.ensureStateFont(s.state);continue}U.carriageReturn(),q({chars:f[0],extraSpacing:0});break;case 47:if(!s.state.font){w.ensureStateFont(s.state);continue}U.wordSpacing=f[0],U.charSpacing=f[1],U.carriageReturn(),q({chars:f[2],extraSpacing:0});break;case 66:O(),S||(S=t.get("XObject")||hA.empty);var L=f[0]instanceof cA,J=f[0].name;if(L&&R.getByName(J))break;return void l(new Promise((function(A,i){if(!L)throw new T("XObject must be referred to by name.");let a=S.getRaw(J);if(a instanceof QA){if(R.getByRef(a))return void A();if(w.globalImageCache.getData(a,w.pageIndex))return void A();a=k.fetch(a)}if(!(a instanceof mA))throw new T("XObject should be a stream");const h=a.dict.get("Subtype");if(!(h instanceof cA))throw new T("XObject should have a Name subtype");if("Form"!==h.name)return R.set(J,a.dict.objId,!0),void A();const Q=s.state.clone(),l=new Br(Q),E=YA(a.dict.getArray("Matrix"),null);E&&l.transform(E),X();const u={enqueueInvoked:!1,enqueue(A,e){this.enqueueInvoked=!0,g.enqueue(A,e)},get desiredSize(){return g.desiredSize},get ready(){return g.ready}};w.getTextContent({stream:a,task:e,resources:a.dict.get("Resources")||t,stateManager:l,includeMarkedContent:n,sink:u,seenStyles:r,viewBox:o,lang:I,markedContentData:c,disableNormalization:C,keepWhiteSpace:B}).then((function(){u.enqueueInvoked||R.set(J,a.dict.objId,!0),A()}),i)})).catch((function(A){if(!(A instanceof P)){if(!w.options.ignoreErrors)throw A;N(`getTextContent - ignoring XObject: "${A}".`)}})));case 9:if(L=f[0]instanceof cA,J=f[0].name,L&&G.getByName(J))break;return void l(new Promise((function(A,e){if(!L)throw new T("GState must be referred to by name.");const i=t.get("ExtGState");if(!(i instanceof hA))throw new T("ExtGState should be a dictionary.");const a=i.get(J);if(!(a instanceof hA))throw new T("GState should be a dictionary.");const s=a.get("Font");if(!s)return G.set(J,a.objId,!0),void A();O(),U.fontName=null,U.fontSize=s[1],Y(null,s[0]).then(A,e)})).catch((function(A){if(!(A instanceof P)){if(!w.options.ignoreErrors)throw A;N(`getTextContent - ignoring ExtGState: "${A}".`)}})));case 69:O(),n&&(c.level++,h.items.push({type:"beginMarkedContent",tag:f[0]instanceof cA?f[0].name:null}));break;case D:if(O(),n){c.level++;let A=null;f[1]instanceof hA&&(A=f[1].get("MCID")),h.items.push({type:"beginMarkedContentProps",id:Number.isInteger(A)?`${w.idFactory.getPageObjId()}_mc${A}`:null,tag:f[0]instanceof cA?f[0].name:null})}break;case b:if(O(),n){if(0===c.level)break;c.level--,h.items.push({type:"endMarkedContent"})}break;case d:!A||A.font===U.font&&A.fontSize===U.fontSize&&A.fontName===U.fontName||O()}if(h.items.length>=g.desiredSize){u=!0;break}}u?l(gr):(O(),X(),a())})).catch((A=>{if(!(A instanceof P)){if(this.options.ignoreErrors)return N(`getTextContent - ignoring errors during "${e.name}" task: "${A}".`),O(),void X();throw A}}))}async extractDataStructures(A,e){const t=this.xref;let i;const a=this.readToUnicode(e.toUnicode);if(e.composite){const t=A.get("CIDSystemInfo");t instanceof hA&&(e.cidSystemInfo={registry:$(t.get("Registry")),ordering:$(t.get("Ordering")),supplement:t.get("Supplement")});try{const e=A.get("CIDToGIDMap");e instanceof mA&&(i=e.getBytes())}catch(A){if(!this.options.ignoreErrors)throw A;N(`extractDataStructures - ignoring CIDToGIDMap data: "${A}".`)}}const s=[];let n,g=null;if(A.has("Encoding")){if(n=A.get("Encoding"),n instanceof hA){if(g=n.get("BaseEncoding"),g=g instanceof cA?g.name:null,n.has("Differences")){const A=n.get("Differences");let e=0;for(const i of A){const A=t.fetchIfRef(i);if("number"==typeof A)e=A;else{if(!(A instanceof cA))throw new T(`Invalid entry in 'Differences' array: ${A}`);s[e++]=A.name}}}}else if(n instanceof cA)g=n.name;else{const A="Encoding is not a Name nor a Dict";if(!this.options.ignoreErrors)throw new T(A);N(A)}"MacRomanEncoding"!==g&&"MacExpertEncoding"!==g&&"WinAnsiEncoding"!==g&&(g=null)}const r=!e.file||e.isInternalFont,o=ya()[e.name];if(g&&r&&o&&(g=null),g)e.defaultEncoding=Yi(g);else{const A=!!(4&e.flags),t=!!(32&e.flags);n=Mi,"TrueType"!==e.type||t||(n=Li),(A||o)&&(n=Ui,r&&(/Symbol/i.test(e.name)?n=Ji:/Dingbats/i.test(e.name)?n=Hi:/Wingdings/i.test(e.name)&&(n=Li))),e.defaultEncoding=n}e.differences=s,e.baseEncodingName=g,e.hasEncoding=!!g||s.length>0,e.dict=A,e.toUnicode=await a;const I=await this.buildToUnicode(e);return e.toUnicode=I,i&&(e.cidToGidMap=this.readCidToGidMap(i,I)),e}_simpleFontToUnicode(A,e=!1){U(!A.composite,"Must be a simple font.");const t=[],i=A.defaultEncoding.slice(),a=A.baseEncodingName,s=A.differences;for(const A in s){const e=s[A];".notdef"!==e&&(i[A]=e)}const n=sa();for(const s in i){let g=i[s];if(""===g)continue;let r=n[g];if(void 0!==r){t[s]=String.fromCharCode(r);continue}let o=0;switch(g[0]){case"G":3===g.length&&(o=parseInt(g.substring(1),16));break;case"g":5===g.length&&(o=parseInt(g.substring(1),16));break;case"C":case"c":if(g.length>=3&&g.length<=4){const t=g.substring(1);if(e){o=parseInt(t,16);break}if(o=+t,Number.isNaN(o)&&Number.isInteger(parseInt(t,16)))return this._simpleFontToUnicode(A,!0)}break;case"u":r=ra(g,n),-1!==r&&(o=r);break;default:switch(g){case"f_h":case"f_t":case"T_h":t[s]=g.replaceAll("_","");continue}}if(o>0&&o<=1114111&&Number.isInteger(o)){if(a&&o===+s){const A=Yi(a);if(A&&(g=A[s])){t[s]=String.fromCharCode(n[g]);continue}}t[s]=String.fromCodePoint(o)}}return t}async buildToUnicode(A){if(A.hasIncludedToUnicodeMap=A.toUnicode?.length>0,A.hasIncludedToUnicodeMap)return!A.composite&&A.hasEncoding&&(A.fallbackToUnicode=this._simpleFontToUnicode(A)),A.toUnicode;if(!A.composite)return new Sa(this._simpleFontToUnicode(A));if(A.composite&&(A.cMap.builtInCMap&&!(A.cMap instanceof hi)||"Adobe"===A.cidSystemInfo?.registry&&("GB1"===A.cidSystemInfo.ordering||"CNS1"===A.cidSystemInfo.ordering||"Japan1"===A.cidSystemInfo.ordering||"Korea1"===A.cidSystemInfo.ordering))){const{registry:e,ordering:t}=A.cidSystemInfo,i=cA.get(`${e}-${t}-UCS2`),a=await Fi.create({encoding:i,fetchBuiltInCMap:this._fetchBuiltInCMapBound,useCMap:null}),s=[],n=[];return A.cMap.forEach((function(A,e){if(e>65535)throw new T("Max size of CID is 65,535");const t=a.lookup(e);if(t){n.length=0;for(let A=0,e=t.length;A>1;(0!==a||e.has(s))&&(t[s]=a)}return t}extractWidths(A,e,t){const i=this.xref;let a=[],s=0;const n=[];let g;if(t.composite){const e=A.get("DW");s="number"==typeof e?Math.ceil(e):1e3;const r=A.get("W");if(Array.isArray(r))for(let A=0,e=r.length;A{const e=r.get(A),a=new tr;return i.getOperatorList({stream:e,task:t,resources:o,operatorList:a}).then((()=>{49===a.fnArray[0]&&this._removeType3ColorOperators(a,h),I[A]=a.getIR();for(const A of a.dependencies)n.add(A)})).catch((function(e){N(`Type3 font resource "${A}" is not available.`);const t=new tr;I[A]=t.getIR()}))}));return this.type3Loaded=g.then((()=>{s.charProcOperatorList=I,this._bbox&&(s.isCharBBox=!0,s.bbox=this._bbox)})),this.type3Loaded}_removeType3ColorOperators(A,e=NaN){const t=z.normalizeRect(A.argsArray[0].slice(2)),i=t[2]-t[0],a=t[3]-t[1],s=Math.hypot(i,a);0===i||0===a?(A.fnArray.splice(0,1),A.argsArray.splice(0,1)):(0===e||Math.round(s/e)>=10)&&(this._bbox||(this._bbox=[1/0,1/0,-1/0,-1/0]),this._bbox[0]=Math.min(this._bbox[0],t[0]),this._bbox[1]=Math.min(this._bbox[1],t[1]),this._bbox[2]=Math.max(this._bbox[2],t[2]),this._bbox[3]=Math.max(this._bbox[3],t[3]));let n=0,g=A.length;for(;n=13&&s<=28,a.variableArgs)g>n&&G(`Command ${i}: expected [0, ${n}] args, but received ${g} args.`);else{if(g!==n){const A=this.nonProcessedArgs;for(;g>n;)A.push(e.shift()),g--;for(;glr.MAX_INVALID_PATH_OPS)throw new T(`Invalid ${A}`);N(`Skipping ${A}`),null!==e&&(e.length=0);continue}}return this.preprocessCommand(s,e),A.fn=s,A.args=e,!0}if(t===gA)return!1;if(null!==t&&(null===e&&(e=[]),e.push(t),e.length>33))throw new T("Too many arguments")}}preprocessCommand(A,e){switch(0|A){case u:this.stateManager.save();break;case d:this.stateManager.restore();break;case f:this.stateManager.transform(e)}}}class Er extends lr{constructor(A){super(new ge(A))}parse(){const A={fn:0,args:[]},e={fontSize:0,fontName:"",fontColor:new Uint8ClampedArray(3)};try{for(;A.args.length=0,this.read(A);){if(0!==this.savedStatesDepth)continue;const{fn:t,args:i}=A;switch(0|t){case p:const[A,t]=i;A instanceof cA&&(e.fontName=A.name),"number"==typeof t&&t>0&&(e.fontSize=t);break;case w:ce.singletons.rgb.getRgbItem(i,0,e.fontColor,0);break;case 57:ce.singletons.gray.getRgbItem(i,0,e.fontColor,0);break;case 61:ce.singletons.cmyk.getRgbItem(i,0,e.fontColor,0)}}}catch(A){N(`parseDefaultAppearance - ignoring errors: "${A}".`)}return e}}function ur(A){return new Er(A).parse()}class dr extends lr{constructor(A,e,t){super(A),this.stream=A,this.evaluatorOptions=e,this.xref=t,this.resources=A.dict?.get("Resources")}parse(){const A={fn:0,args:[]};let e={scaleFactor:1,fontSize:0,fontName:"",fontColor:new Uint8ClampedArray(3),fillColorSpace:ce.singletons.gray},t=!1;const i=[];try{for(;A.args.length=0,!t&&this.read(A);){const{fn:a,args:s}=A;switch(0|a){case u:i.push({scaleFactor:e.scaleFactor,fontSize:e.fontSize,fontName:e.fontName,fontColor:e.fontColor.slice(),fillColorSpace:e.fillColorSpace});break;case d:e=i.pop()||e;break;case 42:e.scaleFactor*=Math.hypot(s[0],s[1]);break;case p:const[A,a]=s;A instanceof cA&&(e.fontName=A.name),"number"==typeof a&&a>0&&(e.fontSize=a*e.scaleFactor);break;case 51:e.fillColorSpace=ce.parse({cs:s[0],xref:this.xref,resources:this.resources,pdfFunctionFactory:this._pdfFunctionFactory,localColorSpaceCache:this._localColorSpaceCache});break;case 54:e.fillColorSpace.getRgbItem(s,0,e.fontColor,0);break;case w:ce.singletons.rgb.getRgbItem(s,0,e.fontColor,0);break;case 57:ce.singletons.gray.getRgbItem(s,0,e.fontColor,0);break;case 61:ce.singletons.cmyk.getRgbItem(s,0,e.fontColor,0);break;case m:case 45:case 46:case 47:t=!0}}}catch(A){N(`parseAppearanceStream - ignoring errors: "${A}".`)}return this.stream.reset(),delete e.scaleFactor,delete e.fillColorSpace,e}get _localColorSpaceCache(){return L(this,"_localColorSpaceCache",new tg)}get _pdfFunctionFactory(){return L(this,"_pdfFunctionFactory",new rg({xref:this.xref,isEvalSupported:this.evaluatorOptions.isEvalSupported}))}}function fr(A,e){return A[0]===A[1]&&A[1]===A[2]?`${$A(A[0]/255)} ${e?"g":"G"}`:Array.from(A,(A=>$A(A/255))).join(" ")+" "+(e?"rg":"RG")}class pr{constructor(A,e){this.xref=A,this.widths=null,this.firstChar=1/0,this.lastChar=-1/0,this.fontFamily=e;const t=new OffscreenCanvas(1,1);this.ctxMeasure=t.getContext("2d",{willReadFrequently:!0}),pr._fontNameId||(pr._fontNameId=1),this.fontName=cA.get(`InvalidPDFjsFont_${e}_${pr._fontNameId++}`)}get fontDescriptorRef(){if(!pr._fontDescriptorRef){const A=new hA(this.xref);A.set("Type",cA.get("FontDescriptor")),A.set("FontName",this.fontName),A.set("FontFamily","MyriadPro Regular"),A.set("FontBBox",[0,0,0,0]),A.set("FontStretch",cA.get("Normal")),A.set("FontWeight",400),A.set("ItalicAngle",0),pr._fontDescriptorRef=this.xref.getNewPersistentRef(A)}return pr._fontDescriptorRef}get descendantFontRef(){const A=new hA(this.xref);A.set("BaseFont",this.fontName),A.set("Type",cA.get("Font")),A.set("Subtype",cA.get("CIDFontType0")),A.set("CIDToGIDMap",cA.get("Identity")),A.set("FirstChar",this.firstChar),A.set("LastChar",this.lastChar),A.set("FontDescriptor",this.fontDescriptorRef),A.set("DW",1e3);const e=[],t=[...this.widths.entries()].sort();let i=null,a=null;for(const[A,s]of t)i?A===i+a.length?a.push(s):(e.push(i,a),i=A,a=[s]):(i=A,a=[s]);i&&e.push(i,a),A.set("W",e);const s=new hA(this.xref);return s.set("Ordering","Identity"),s.set("Registry","Adobe"),s.set("Supplement",0),A.set("CIDSystemInfo",s),this.xref.getNewPersistentRef(A)}get baseFontRef(){const A=new hA(this.xref);return A.set("BaseFont",this.fontName),A.set("Type",cA.get("Font")),A.set("Subtype",cA.get("Type0")),A.set("Encoding",cA.get("Identity-H")),A.set("DescendantFonts",[this.descendantFontRef]),A.set("ToUnicode",cA.get("Identity-H")),this.xref.getNewPersistentRef(A)}get resources(){const A=new hA(this.xref),e=new hA(this.xref);return e.set(this.fontName.name,this.baseFontRef),A.set("Font",e),A}_createContext(){return this.widths=new Map,this.ctxMeasure.font=`1000px ${this.fontFamily}`,this.ctxMeasure}createFontResources(A){const e=this._createContext();for(const t of A.split(/\r\n?|\n/))for(const A of t.split("")){const t=A.charCodeAt(0);if(this.widths.has(t))continue;const i=e.measureText(A),a=Math.ceil(i.width);this.widths.set(t,a),this.firstChar=Math.min(t,this.firstChar),this.lastChar=Math.max(t,this.lastChar)}return this.resources}static getFirstPositionInfo(A,e,t){const[i,a,n,g]=A;let r=n-i,o=g-a;e%180!=0&&([r,o]=[o,r]);const I=s*t;return{coords:[0,o+.35*t-I],bbox:[0,0,r,o],matrix:0!==e?ae(e,o,I):void 0}}createAppearance(A,e,t,i,a,n){const g=this._createContext(),r=[];let o=-1/0;for(const e of A.split(/\r\n?|\n/)){r.push(e);const A=g.measureText(e).width;o=Math.max(o,A);for(const A of XA(e)){const e=String.fromCodePoint(A);let t=this.widths.get(A);if(void 0===t){const i=g.measureText(e);t=Math.ceil(i.width),this.widths.set(A,t),this.firstChar=Math.min(A,this.firstChar),this.lastChar=Math.max(A,this.lastChar)}}}o*=i/1e3;const[I,c,C,B]=e;let h=C-I,Q=B-c;t%180!=0&&([h,Q]=[Q,h]);let l=1;o>h&&(l=h/o);let E=1;const u=s*i,d=.35*i,f=u*r.length;f>Q&&(E=Q/f);const p=i*Math.min(l,E),m=["q",`0 0 ${$A(h)} ${$A(Q)} re W n`,"BT",`1 0 0 1 0 ${$A(Q+d)} Tm 0 Tc ${fr(a,!0)}`,`/${this.fontName.name} ${$A(p)} Tf`],{resources:y}=this;if(1!==(n="number"==typeof n&&n>=0&&n<=1?n:1)){m.push("/R0 gs");const A=new hA(this.xref),e=new hA(this.xref);e.set("ca",n),e.set("CA",n),e.set("Type",cA.get("ExtGState")),A.set("R0",e),y.set("ExtGState",A)}const w=$A(u);for(const A of r)m.push(`0 -${w} Td <${te(A)}> Tj`);m.push("ET","Q");const D=m.join("\n"),b=new hA(this.xref);if(b.set("Subtype",cA.get("Form")),b.set("Type",cA.get("XObject")),b.set("BBox",[0,0,h,Q]),b.set("Length",D.length),b.set("Resources",y),t){const A=ae(t,h,Q);b.set("Matrix",A)}const k=new ge(D);return k.dict=b,k}}class mr{constructor(A,e,t){this.root=A,this.xref=e,this._type=t}getAll(){const A=new Map;if(!this.root)return A;const e=this.xref,t=new lA;t.put(this.root);const i=[this.root];for(;i.length>0;){const a=e.fetchIfRef(i.shift());if(!(a instanceof hA))continue;if(a.has("Kids")){const A=a.get("Kids");if(!Array.isArray(A))continue;for(const e of A){if(t.has(e))throw new T(`Duplicate entry in "${this._type}" tree.`);i.push(e),t.put(e)}continue}const s=a.get(this._type);if(Array.isArray(s))for(let t=0,i=s.length;t10)return N(`Search depth limit reached for "${this._type}" tree.`),null;const a=t.get("Kids");if(!Array.isArray(a))return null;let s=0,n=a.length-1;for(;s<=n;){const i=s+n>>1,g=e.fetchIfRef(a[i]),r=g.get("Limits");if(Ae.fetchIfRef(r[1]))){t=g;break}s=i+1}}if(s>n)return null}const a=t.get(this._type);if(Array.isArray(a)){let t=0,i=a.length-2;for(;t<=i;){const s=t+i>>1,n=s+(1&s),g=e.fetchIfRef(a[n]);if(Ag))return a[n+1];t=n+2}}}return null}get(A){return this.xref.fetchIfRef(this.getRaw(A))}}class yr extends mr{constructor(A,e){super(A,e,"Names")}}class wr extends mr{constructor(A,e){super(A,e,"Nums")}}function Dr(){en=Object.create(null),rA=Object.create(null),oA=Object.create(null),IA=Object.create(null),Ca.clear(),ei.cleanup()}function br(A){return A instanceof hA?A.has("UF")?A.get("UF"):A.has("F")?A.get("F"):A.has("Unix")?A.get("Unix"):A.has("Mac")?A.get("Mac"):A.has("DOS")?A.get("DOS"):null:null}class kr{#F=!1;constructor(A,e,t=!1){A instanceof hA&&(this.xref=e,this.root=A,A.has("FS")&&(this.fs=A.get("FS")),A.has("RF")&&N("Related file specifications are not supported"),t||(A.has("EF")?this.#F=!0:N("Non-embedded file specifications are not supported")))}get filename(){let A="";const e=br(this.root);return e&&"string"==typeof e&&(A=$(e).replaceAll("\\\\","\\").replaceAll("\\/","/").replaceAll("\\","/")),L(this,"filename",A||"unnamed")}get content(){if(!this.#F)return null;this._contentRef||=br(this.root?.get("EF"));let A=null;if(this._contentRef){const e=this.xref.fetchIfRef(this._contentRef);e instanceof mA?A=e.getBytes():N("Embedded file specification points to non-existing/invalid content")}else N("Embedded file specification does not have any content");return A}get description(){let A="";const e=this.root?.get("Desc");return e&&"string"==typeof e&&(A=$(e)),L(this,"description",A)}get serializable(){return{rawFilename:this.filename,filename:(A=this.filename,A.substring(A.lastIndexOf("/")+1)),content:this.content,description:this.description};var A}}function Fr(A,e){const t=A[e];return" "===t||"\n"===t||"\r"===t||"\t"===t}class Sr{_resolveEntities(A){return A.replaceAll(/&([^;]+);/g,((A,e)=>{if("#x"===e.substring(0,2))return String.fromCodePoint(parseInt(e.substring(2),16));if("#"===e.substring(0,1))return String.fromCodePoint(parseInt(e.substring(1),10));switch(e){case"lt":return"<";case"gt":return">";case"amp":return"&";case"quot":return'"';case"apos":return"'"}return this.onResolveEntity(e)}))}_parseContent(A,e){const t=[];let i=e;function a(){for(;i"!==A[i]&&"/"!==A[i];)++i;const s=A.substring(e,i);for(a();i"!==A[i]&&"/"!==A[i]&&"?"!==A[i];){a();let e="",s="";for(;i"!==A[t]&&"?"!==A[t]&&"/"!==A[t];)++t;const i=A.substring(e,t);!function(){for(;t"!==A[t+1]);)++t;return{name:i,value:A.substring(a,t),parsed:t-e}}parseXml(A){let e=0;for(;e",t),e<0)return void this.onError(-9);this.onEndElement(A.substring(t,e)),t=e+1;break;case"?":++t;const i=this._parseProcessingInstruction(A,t);if("?>"!==A.substring(t+i.parsed,t+i.parsed+2))return void this.onError(-3);this.onPi(i.name,i.value),t+=i.parsed+2;break;case"!":if("--"===A.substring(t+1,t+3)){if(e=A.indexOf("--\x3e",t+3),e<0)return void this.onError(-5);this.onComment(A.substring(t+3,e)),t=e+3}else if("[CDATA["===A.substring(t+1,t+8)){if(e=A.indexOf("]]>",t+8),e<0)return void this.onError(-2);this.onCdata(A.substring(t+8,e)),t=e+3}else{if("DOCTYPE"!==A.substring(t+1,t+8))return void this.onError(-6);{const i=A.indexOf("[",t+8);let a=!1;if(e=A.indexOf(">",t+8),e<0)return void this.onError(-4);if(i>0&&e>i){if(e=A.indexOf("]>",t+8),e<0)return void this.onError(-4);a=!0}const s=A.substring(t+8,e+(a?1:0));this.onDoctype(s),t=e+(a?2:1)}}break;default:const a=this._parseContent(A,t);if(null===a)return void this.onError(-6);let s=!1;if("/>"===A.substring(t+a.parsed,t+a.parsed+2))s=!0;else if(">"!==A.substring(t+a.parsed,t+a.parsed+1))return void this.onError(-9);this.onBeginElement(a.name,a.attributes,s),t+=a.parsed+(s?2:1)}}else{for(;t0}searchNode(A,e){if(e>=A.length)return this;const t=A[e];if(t.name.startsWith("#")&&e0)i.push([a,0]),a=a.childNodes[0];else{if(0===i.length)return null;for(;0!==i.length;){const[A,e]=i.pop(),t=e+1;if(t");for(const e of this.childNodes)e.dump(A);A.push(``)}else this.nodeValue?A.push(`>${VA(this.nodeValue)}`):A.push("/>")}else A.push(VA(this.nodeValue))}}class Gr extends Sr{constructor({hasAttributes:A=!1,lowerCaseName:e=!1}){super(),this._currentFragment=null,this._stack=null,this._errorCode=0,this._hasAttributes=A,this._lowerCaseName=e}parseFromString(A){if(this._currentFragment=[],this._stack=[],this._errorCode=0,this.parseXml(A),0!==this._errorCode)return;const[e]=this._currentFragment;return e?{documentElement:e}:void 0}onText(A){if(function(A){for(let e=0,t=A.length;e\\376\\377([^<]+)/g,(function(A,e){const t=e.replaceAll(/\\([0-3])([0-7])([0-7])/g,(function(A,e,t,i){return String.fromCharCode(64*e+8*t+1*i)})).replaceAll(/&(amp|apos|gt|lt|quot);/g,(function(A,e){switch(e){case"amp":return"&";case"apos":return"'";case"gt":return">";case"lt":return"<";case"quot":return'"'}throw new Error(`_repair: ${e} isn't defined.`)})),i=[">"];for(let A=0,e=t.length;A=32&&e<127&&60!==e&&62!==e&&38!==e?i.push(String.fromCharCode(e)):i.push("&#x"+(65536+e).toString(16).substring(1)+";")}return i.join("")}))}_getSequence(A){const e=A.nodeName;return"rdf:bag"!==e&&"rdf:seq"!==e&&"rdf:alt"!==e?null:A.childNodes.filter((A=>"rdf:li"===A.nodeName))}_parseArray(A){if(!A.hasChildNodes())return;const[e]=A.childNodes,t=this._getSequence(e)||[];this._metadataMap.set(A.nodeName,t.map((A=>A.textContent.trim())))}_parse(A){let e=A.documentElement;if("rdf:rdf"!==e.nodeName)for(e=e.firstChild;e&&"rdf:rdf"!==e.nodeName;)e=e.nextSibling;if(e&&"rdf:rdf"===e.nodeName&&e.hasChildNodes())for(const A of e.childNodes)if("rdf:description"===A.nodeName)for(const e of A.childNodes){const A=e.nodeName;switch(A){case"#text":continue;case"dc:creator":case"dc:subject":this._parseArray(e);continue}this._metadataMap.set(A,e.textContent.trim())}}get serializable(){return{parsedData:this._metadataMap,rawData:this._data}}}class xr extends Re{constructor(A,e,t){super(e),this.str=A,this.dict=A.dict,this.decrypt=t,this.nextChunk=null,this.initialized=!1}readBlock(){let A;if(this.initialized?A=this.nextChunk:(A=this.str.getBytes(512),this.initialized=!0),!A||0===A.length)return void(this.eof=!0);this.nextChunk=this.str.getBytes(512);const e=this.nextChunk?.length>0;A=(0,this.decrypt)(A,!e);const t=this.bufferLength,i=t+A.length;this.ensureBuffer(i).set(A,t),this.bufferLength=i}}class Ur{constructor(A){this.a=0,this.b=0;const e=new Uint8Array(256),t=A.length;for(let A=0;A<256;++A)e[A]=A;for(let i=0,a=0;i<256;++i){const s=e[i];a=a+s+A[i%t]&255,e[i]=e[a],e[a]=s}this.s=e}encryptBlock(A){let e=this.a,t=this.b;const i=this.s,a=A.length,s=new Uint8Array(a);for(let n=0;n>5&255,I[c++]=a>>13&255,I[c++]=a>>21&255,I[c++]=a>>>29&255,I[c++]=0,I[c++]=0,I[c++]=0;const h=new Int32Array(16);for(c=0;c>>32-g)|0,a=s}s=s+a|0,n=n+o|0,g=g+B|0,r=r+Q|0}return new Uint8Array([255&s,s>>8&255,s>>16&255,s>>>24&255,255&n,n>>8&255,n>>16&255,n>>>24&255,255&g,g>>8&255,g>>16&255,g>>>24&255,255&r,r>>8&255,r>>16&255,r>>>24&255])}}();class Lr{constructor(A,e){this.high=0|A,this.low=0|e}and(A){this.high&=A.high,this.low&=A.low}xor(A){this.high^=A.high,this.low^=A.low}or(A){this.high|=A.high,this.low|=A.low}shiftRight(A){A>=32?(this.low=this.high>>>A-32|0,this.high=0):(this.low=this.low>>>A|this.high<<32-A,this.high=this.high>>>A|0)}shiftLeft(A){A>=32?(this.high=this.low<>>32-A,this.low<<=A)}rotateRight(A){let e,t;32&A?(t=this.low,e=this.high):(e=this.low,t=this.high),A&=31,this.low=e>>>A|t<<32-A,this.high=t>>>A|e<<32-A}not(){this.high=~this.high,this.low=~this.low}add(A){const e=(this.low>>>0)+(A.low>>>0);let t=(this.high>>>0)+(A.high>>>0);e>4294967295&&(t+=1),this.low=0|e,this.high=0|t}copyTo(A,e){A[e]=this.high>>>24&255,A[e+1]=this.high>>16&255,A[e+2]=this.high>>8&255,A[e+3]=255&this.high,A[e+4]=this.low>>>24&255,A[e+5]=this.low>>16&255,A[e+6]=this.low>>8&255,A[e+7]=255&this.low}assign(A){this.high=A.high,this.low=A.low}}const Jr=function(){function A(A,e){return A>>>e|A<<32-e}function e(A,e,t){return A&e^~A&t}function t(A,e,t){return A&e^A&t^e&t}function i(e){return A(e,2)^A(e,13)^A(e,22)}function a(e){return A(e,6)^A(e,11)^A(e,25)}function s(e){return A(e,7)^A(e,18)^e>>>3}const n=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];return function(g,r,o){let I=1779033703,c=3144134277,C=1013904242,B=2773480762,h=1359893119,Q=2600822924,l=528734635,E=1541459225;const u=64*Math.ceil((o+9)/64),d=new Uint8Array(u);let f,p;for(f=0;f>>29&255,d[f++]=o>>21&255,d[f++]=o>>13&255,d[f++]=o>>5&255,d[f++]=o<<3&255;const y=new Uint32Array(64);for(f=0;f>>10)+y[p-7]+s(y[p-15])+y[p-16];let g,r,o=I,u=c,m=C,D=B,b=h,k=Q,F=l,S=E;for(p=0;p<64;++p)g=S+a(b)+e(b,k,F)+n[p]+y[p],r=i(o)+t(o,u,m),S=F,F=k,k=b,b=D+g|0,D=m,m=u,u=o,o=g+r|0;I=I+o|0,c=c+u|0,C=C+m|0,B=B+D|0,h=h+b|0,Q=Q+k|0,l=l+F|0,E=E+S|0}var w;return new Uint8Array([I>>24&255,I>>16&255,I>>8&255,255&I,c>>24&255,c>>16&255,c>>8&255,255&c,C>>24&255,C>>16&255,C>>8&255,255&C,B>>24&255,B>>16&255,B>>8&255,255&B,h>>24&255,h>>16&255,h>>8&255,255&h,Q>>24&255,Q>>16&255,Q>>8&255,255&Q,l>>24&255,l>>16&255,l>>8&255,255&l,E>>24&255,E>>16&255,E>>8&255,255&E])}}(),Hr=function(){function A(A,e,t,i,a){A.assign(e),A.and(t),a.assign(e),a.not(),a.and(i),A.xor(a)}function e(A,e,t,i,a){A.assign(e),A.and(t),a.assign(e),a.and(i),A.xor(a),a.assign(t),a.and(i),A.xor(a)}function t(A,e,t){A.assign(e),A.rotateRight(28),t.assign(e),t.rotateRight(34),A.xor(t),t.assign(e),t.rotateRight(39),A.xor(t)}function i(A,e,t){A.assign(e),A.rotateRight(14),t.assign(e),t.rotateRight(18),A.xor(t),t.assign(e),t.rotateRight(41),A.xor(t)}function a(A,e,t){A.assign(e),A.rotateRight(1),t.assign(e),t.rotateRight(8),A.xor(t),t.assign(e),t.shiftRight(7),A.xor(t)}function s(A,e,t){A.assign(e),A.rotateRight(19),t.assign(e),t.rotateRight(61),A.xor(t),t.assign(e),t.shiftRight(6),A.xor(t)}const n=[new Lr(1116352408,3609767458),new Lr(1899447441,602891725),new Lr(3049323471,3964484399),new Lr(3921009573,2173295548),new Lr(961987163,4081628472),new Lr(1508970993,3053834265),new Lr(2453635748,2937671579),new Lr(2870763221,3664609560),new Lr(3624381080,2734883394),new Lr(310598401,1164996542),new Lr(607225278,1323610764),new Lr(1426881987,3590304994),new Lr(1925078388,4068182383),new Lr(2162078206,991336113),new Lr(2614888103,633803317),new Lr(3248222580,3479774868),new Lr(3835390401,2666613458),new Lr(4022224774,944711139),new Lr(264347078,2341262773),new Lr(604807628,2007800933),new Lr(770255983,1495990901),new Lr(1249150122,1856431235),new Lr(1555081692,3175218132),new Lr(1996064986,2198950837),new Lr(2554220882,3999719339),new Lr(2821834349,766784016),new Lr(2952996808,2566594879),new Lr(3210313671,3203337956),new Lr(3336571891,1034457026),new Lr(3584528711,2466948901),new Lr(113926993,3758326383),new Lr(338241895,168717936),new Lr(666307205,1188179964),new Lr(773529912,1546045734),new Lr(1294757372,1522805485),new Lr(1396182291,2643833823),new Lr(1695183700,2343527390),new Lr(1986661051,1014477480),new Lr(2177026350,1206759142),new Lr(2456956037,344077627),new Lr(2730485921,1290863460),new Lr(2820302411,3158454273),new Lr(3259730800,3505952657),new Lr(3345764771,106217008),new Lr(3516065817,3606008344),new Lr(3600352804,1432725776),new Lr(4094571909,1467031594),new Lr(275423344,851169720),new Lr(430227734,3100823752),new Lr(506948616,1363258195),new Lr(659060556,3750685593),new Lr(883997877,3785050280),new Lr(958139571,3318307427),new Lr(1322822218,3812723403),new Lr(1537002063,2003034995),new Lr(1747873779,3602036899),new Lr(1955562222,1575990012),new Lr(2024104815,1125592928),new Lr(2227730452,2716904306),new Lr(2361852424,442776044),new Lr(2428436474,593698344),new Lr(2756734187,3733110249),new Lr(3204031479,2999351573),new Lr(3329325298,3815920427),new Lr(3391569614,3928383900),new Lr(3515267271,566280711),new Lr(3940187606,3454069534),new Lr(4118630271,4000239992),new Lr(116418474,1914138554),new Lr(174292421,2731055270),new Lr(289380356,3203993006),new Lr(460393269,320620315),new Lr(685471733,587496836),new Lr(852142971,1086792851),new Lr(1017036298,365543100),new Lr(1126000580,2618297676),new Lr(1288033470,3409855158),new Lr(1501505948,4234509866),new Lr(1607167915,987167468),new Lr(1816402316,1246189591)];return function(g,r,o,I=!1){let c,C,B,h,Q,l,E,u;I?(c=new Lr(3418070365,3238371032),C=new Lr(1654270250,914150663),B=new Lr(2438529370,812702999),h=new Lr(355462360,4144912697),Q=new Lr(1731405415,4290775857),l=new Lr(2394180231,1750603025),E=new Lr(3675008525,1694076839),u=new Lr(1203062813,3204075428)):(c=new Lr(1779033703,4089235720),C=new Lr(3144134277,2227873595),B=new Lr(1013904242,4271175723),h=new Lr(2773480762,1595750129),Q=new Lr(1359893119,2917565137),l=new Lr(2600822924,725511199),E=new Lr(528734635,4215389547),u=new Lr(1541459225,327033209));const d=128*Math.ceil((o+17)/128),f=new Uint8Array(d);let p,m;for(p=0;p>>29&255,f[p++]=o>>21&255,f[p++]=o>>13&255,f[p++]=o>>5&255,f[p++]=o<<3&255;const w=new Array(80);for(p=0;p<80;p++)w[p]=new Lr(0,0);let D=new Lr(0,0),b=new Lr(0,0),k=new Lr(0,0),F=new Lr(0,0),S=new Lr(0,0),R=new Lr(0,0),G=new Lr(0,0),N=new Lr(0,0);const x=new Lr(0,0),U=new Lr(0,0),M=new Lr(0,0),L=new Lr(0,0);let J,H;for(p=0;p=1;--A){t=s[13],s[13]=s[9],s[9]=s[5],s[5]=s[1],s[1]=t,t=s[14],i=s[10],s[14]=s[6],s[10]=s[2],s[6]=t,s[2]=i,t=s[15],i=s[11],a=s[7],s[15]=s[3],s[11]=t,s[7]=i,s[3]=a;for(let A=0;A<16;++A)s[A]=this._inv_s[s[A]];for(let t=0,i=16*A;t<16;++t,++i)s[t]^=e[i];for(let A=0;A<16;A+=4){const e=this._mix[s[A]],i=this._mix[s[A+1]],a=this._mix[s[A+2]],n=this._mix[s[A+3]];t=e^i>>>8^i<<24^a>>>16^a<<16^n>>>24^n<<8,s[A]=t>>>24&255,s[A+1]=t>>16&255,s[A+2]=t>>8&255,s[A+3]=255&t}}t=s[13],s[13]=s[9],s[9]=s[5],s[5]=s[1],s[1]=t,t=s[14],i=s[10],s[14]=s[6],s[10]=s[2],s[6]=t,s[2]=i,t=s[15],i=s[11],a=s[7],s[15]=s[3],s[11]=t,s[7]=i,s[3]=a;for(let A=0;A<16;++A)s[A]=this._inv_s[s[A]],s[A]^=e[A];return s}_encrypt(A,e){const t=this._s;let i,a,s;const n=new Uint8Array(16);n.set(A);for(let A=0;A<16;++A)n[A]^=e[A];for(let A=1;A=i;--t)if(A[t]!==e){e=0;break}g-=e,s[s.length-1]=A.subarray(0,16-e)}}const r=new Uint8Array(g);for(let A=0,e=0,t=s.length;A=256&&(g=255&(27^g)));for(let e=0;e<4;++e)t[A]=i^=t[A-32],A++,t[A]=a^=t[A-32],A++,t[A]=s^=t[A-32],A++,t[A]=n^=t[A-32],A++}return t}}class Tr{checkOwnerPassword(A,e,t,i){const a=new Uint8Array(A.length+56);return a.set(A,0),a.set(e,A.length),a.set(t,A.length+e.length),tA(Jr(a,0,a.length),i)}checkUserPassword(A,e,t){const i=new Uint8Array(A.length+8);return i.set(A,0),i.set(e,A.length),tA(Jr(i,0,i.length),t)}getOwnerKey(A,e,t,i){const a=new Uint8Array(A.length+56);a.set(A,0),a.set(e,A.length),a.set(t,A.length+e.length);const s=Jr(a,0,a.length);return new qr(s).decryptBlock(i,!1,new Uint8Array(16))}getUserKey(A,e,t){const i=new Uint8Array(A.length+8);i.set(A,0),i.set(e,A.length);const a=Jr(i,0,i.length);return new qr(a).decryptBlock(t,!1,new Uint8Array(16))}}class Pr{_hash(A,e,t){let i=Jr(e,0,e.length).subarray(0,32),a=[0],s=0;for(;s<64||a.at(-1)>s-32;){const e=A.length+i.length+t.length,r=new Uint8Array(e);let o=0;r.set(A,o),o+=A.length,r.set(i,o),o+=i.length,r.set(t,o);const I=new Uint8Array(64*e);for(let A=0,t=0;A<64;A++,t+=e)I.set(r,t);a=new Kr(i.subarray(0,16)).encrypt(I,i.subarray(16,32));const c=a.slice(0,16).reduce(((A,e)=>A+e),0)%3;0===c?i=Jr(a,0,a.length):1===c?(n=a,0,g=a.length,i=Hr(n,0,g,!0)):2===c&&(i=Hr(a,0,a.length)),s++}var n,g;return i.subarray(0,32)}checkOwnerPassword(A,e,t,i){const a=new Uint8Array(A.length+56);return a.set(A,0),a.set(e,A.length),a.set(t,A.length+e.length),tA(this._hash(A,a,t),i)}checkUserPassword(A,e,t){const i=new Uint8Array(A.length+8);return i.set(A,0),i.set(e,A.length),tA(this._hash(A,i,[]),t)}getOwnerKey(A,e,t,i){const a=new Uint8Array(A.length+56);a.set(A,0),a.set(e,A.length),a.set(t,A.length+e.length);const s=this._hash(A,a,t);return new qr(s).decryptBlock(i,!1,new Uint8Array(16))}getUserKey(A,e,t){const i=new Uint8Array(A.length+8);i.set(A,0),i.set(e,A.length);const a=this._hash(A,i,[]);return new qr(a).decryptBlock(t,!1,new Uint8Array(16))}}class Wr{constructor(A,e){this.StringCipherConstructor=A,this.StreamCipherConstructor=e}createStream(A,e){const t=new this.StreamCipherConstructor;return new xr(A,e,(function(A,e){return t.decryptBlock(A,e)}))}decryptString(A){const e=new this.StringCipherConstructor;let t=Z(A);return t=e.decryptBlock(t,!0),W(t)}encryptString(A){const e=new this.StringCipherConstructor;if(e instanceof vr){const t=16-A.length%16;A+=String.fromCharCode(t).repeat(t);const i=new Uint8Array(16);if("undefined"!=typeof crypto)crypto.getRandomValues(i);else for(let A=0;A<16;A++)i[A]=Math.floor(256*Math.random());let a=Z(A);a=e.encrypt(a,i);const s=new Uint8Array(16+a.length);return s.set(i),s.set(a,16),W(s)}let t=Z(A);return t=e.encrypt(t),W(t)}}class Zr{static#S=new Uint8Array([40,191,78,94,78,117,138,65,100,0,78,86,255,250,1,8,46,46,0,182,208,104,62,128,47,12,169,254,100,83,105,122]);#R(A,e,t,i,a,s,n,g,r,o,I,c){if(e){const A=Math.min(127,e.length);e=e.subarray(0,A)}else e=[];const C=6===A?new Pr:new Tr;return C.checkUserPassword(e,g,n)?C.getUserKey(e,r,I):e.length&&C.checkOwnerPassword(e,i,s,t)?C.getOwnerKey(e,a,s,o):null}#G(A,e,t,i,a,s,n,g){const r=40+t.length+A.length,o=new Uint8Array(r);let I,c,C=0;if(e)for(c=Math.min(32,e.length);C>8&255,o[C++]=a>>16&255,o[C++]=a>>>24&255,I=0,c=A.length;I=4&&!g&&(o[C++]=255,o[C++]=255,o[C++]=255,o[C++]=255);let B=Mr(o,0,C);const h=n>>3;if(s>=3)for(I=0;I<50;++I)B=Mr(B,0,h);const Q=B.subarray(0,h);let l,E;if(s>=3){for(C=0;C<32;++C)o[C]=Zr.#S[C];for(I=0,c=A.length;I>3;if(t>=3)for(g=0;g<50;++g)r=Mr(r,0,r.length);let I,c;if(t>=3){c=e;const A=new Uint8Array(o);for(g=19;g>=0;g--){for(let e=0;e>8&255,a[n++]=A>>16&255,a[n++]=255&e,a[n++]=e>>8&255,i&&(a[n++]=115,a[n++]=65,a[n++]=108,a[n++]=84),Mr(a,0,n).subarray(0,Math.min(t.length+5,16))}#U(A,e,t,i,a){if(!(e instanceof cA))throw new T("Invalid crypt filter name.");const s=this,n=A.get(e.name),g=n?.get("CFM");if(!g||"None"===g.name)return function(){return new Yr};if("V2"===g.name)return function(){return new Ur(s.#x(t,i,a,!1))};if("AESV2"===g.name)return function(){return new Kr(s.#x(t,i,a,!0))};if("AESV3"===g.name)return function(){return new qr(a)};throw new T("Unknown crypto method")}constructor(A,e,t){const i=A.get("Filter");if(!uA(i,"Standard"))throw new T("unknown encryption method");this.filterName=i.name,this.dict=A;const a=A.get("V");if(!Number.isInteger(a)||1!==a&&2!==a&&4!==a&&5!==a)throw new T("unsupported encryption algorithm");this.algorithm=a;let s=A.get("Length");if(!s)if(a<=3)s=40;else{const e=A.get("CF"),t=A.get("StmF");if(e instanceof hA&&t instanceof cA){e.suppressEncryption=!0;const A=e.get(t.name);s=A?.get("Length")||128,s<40&&(s<<=3)}}if(!Number.isInteger(s)||s<40||s%8!=0)throw new T("invalid key length");const n=Z(A.get("O")),g=Z(A.get("U")),r=n.subarray(0,32),o=g.subarray(0,32),I=A.get("P"),c=A.get("R"),C=(4===a||5===a)&&!1!==A.get("EncryptMetadata");this.encryptMetadata=C;const B=Z(e);let h,Q;if(t){if(6===c)try{t=eA(t)}catch{N("CipherTransformFactory: Unable to convert UTF8 encoded password.")}h=Z(t)}if(5!==a)Q=this.#G(B,h,r,o,I,c,s,C);else{const e=n.subarray(32,40),t=n.subarray(40,48),i=g.subarray(0,48),a=g.subarray(32,40),s=g.subarray(40,48),I=Z(A.get("OE")),C=Z(A.get("UE")),B=Z(A.get("Perms"));Q=this.#R(c,h,r,e,t,i,o,a,s,I,C,B)}if(!Q&&!t)throw new H("No password given",1);if(!Q&&t){const A=this.#N(h,r,c,s);Q=this.#G(B,A,r,o,I,c,s,C)}if(!Q)throw new H("Incorrect Password",2);if(this.encryptionKey=Q,a>=4){const e=A.get("CF");e instanceof hA&&(e.suppressEncryption=!0),this.cf=e,this.stmf=A.get("StmF")||cA.get("Identity"),this.strf=A.get("StrF")||cA.get("Identity"),this.eff=A.get("EFF")||this.stmf}}createCipherTransform(A,e){if(4===this.algorithm||5===this.algorithm)return new Wr(this.#U(this.cf,this.strf,A,e,this.encryptionKey),this.#U(this.cf,this.stmf,A,e,this.encryptionKey));const t=this.#x(A,e,this.encryptionKey,!1),i=function(){return new Ur(t)};return new Wr(i,i)}}async function Or(A,e,t,{encrypt:i=null}){const a=i?.createCipherTransform(A.num,A.gen);t.push(`${A.num} ${A.gen} obj\n`),e instanceof hA?await Xr(e,t,a):e instanceof mA?await Vr(e,t,a):(Array.isArray(e)||ArrayBuffer.isView(e))&&await jr(e,t,a),t.push("\nendobj\n")}async function Xr(A,e,t){e.push("<<");for(const i of A.getKeys())e.push(` /${TA(i)} `),await zr(A.getRaw(i),e,t);e.push(">>")}async function Vr(A,e,t){let i=A.getBytes();const{dict:a}=A,[s,n]=await Promise.all([a.getAsync("Filter"),a.getAsync("DecodeParms")]),g=uA(Array.isArray(s)?await a.xref.fetchIfRefAsync(s[0]):s,"FlateDecode");if(i.length>=256||g)try{const A=new CompressionStream("deflate"),e=A.writable.getWriter();e.write(i),e.close();const t=await new Response(A.readable).arrayBuffer();let r,o;i=new Uint8Array(t),s?g||(r=Array.isArray(s)?[cA.get("FlateDecode"),...s]:[cA.get("FlateDecode"),s],n&&(o=Array.isArray(n)?[null,...n]:[null,n])):r=cA.get("FlateDecode"),r&&a.set("Filter",r),o&&a.set("DecodeParms",o)}catch(A){G(`writeStream - cannot compress data: "${A}".`)}let r=W(i);t&&(r=t.encryptString(r)),a.set("Length",r.length),await Xr(a,e,t),e.push(" stream\n",r,"\nendstream")}async function jr(A,e,t){e.push("[");let i=!0;for(const a of A)i?i=!1:e.push(" "),await zr(a,e,t);e.push("]")}async function zr(A,e,t){A instanceof cA?e.push(`/${TA(A.name)}`):A instanceof QA?e.push(`${A.num} ${A.gen} R`):Array.isArray(A)||ArrayBuffer.isView(A)?await jr(A,e,t):"string"==typeof A?(t&&(A=t.encryptString(A)),e.push(`(${PA(A)})`)):"number"==typeof A?e.push($A(A)):"boolean"==typeof A?e.push(A.toString()):A instanceof hA?await Xr(A,e,t):A instanceof mA?await Vr(A,e,t):null===A?e.push("null"):N(`Unhandled value in writer: ${typeof A}, please file a bug.`)}function _r(A,e,t,i){for(let a=e+t-1;a>t-1;a--)i[a]=255&A,A>>=8;return t+e}function $r(A,e,t){for(let i=0,a=A.length;i0){const i=function(A,e){const t=Math.floor(Date.now()/1e3),i=e.filename||"",a=[t.toString(),i,A.toString()];let s=a.reduce(((A,e)=>A+e.length),0);for(const A of Object.values(e.info))a.push(A),s+=A.length;const n=new Uint8Array(s);let g=0;for(const A of a)$r(A,g,n),g+=A.length;return W(Mr(n))}(A,e);t.set("ID",[e.fileIds[0],i])}}async function to({originalData:A,xrefInfo:e,newRefs:t,xref:i=null,hasXfa:a=!1,xfaDatasetsRef:s=null,hasXfaDatasetsEntry:n=!1,needAppearances:g,acroFormRef:r=null,acroForm:o=null,xfaData:I=null,useXrefStream:c=!1}){await async function({xref:A,acroForm:e,acroFormRef:t,hasXfa:i,hasXfaDatasetsEntry:a,xfaDatasetsRef:s,needAppearances:n,newRefs:g}){if(!i||a||s||N("XFA - Cannot save it"),!n&&(!i||!s||a))return;const r=e.clone();if(i&&!a){const A=e.get("XFA").slice();A.splice(2,0,"datasets"),A.splice(3,0,s),r.set("XFA",A)}n&&r.set("NeedAppearances",!0);const o=[];await Or(t,r,o,A),g.push({ref:t,data:o.join("")})}({xref:i,acroForm:o,acroFormRef:r,hasXfa:a,hasXfaDatasetsEntry:n,xfaDatasetsRef:s,needAppearances:g,newRefs:t}),a&&function({xfaData:A,xfaDatasetsRef:e,newRefs:t,xref:i}){null===A&&(A=function(A,e){const t=new Gr({hasAttributes:!0}).parseFromString(A);for(const{xfa:A}of e){if(!A)continue;const{path:e,value:i}=A;if(!e)continue;const a=qA(e);let s=t.documentElement.searchNode(a,0);!s&&a.length>1&&(s=t.documentElement.searchNode([a.at(-1)],0)),s?s.childNodes=Array.isArray(i)?i.map((A=>new Rr("value",A))):[new Rr("#text",i)]:N(`Node not found for path: ${e}`)}const i=[];return t.documentElement.dump(i),i.join("")}(i.fetchIfRef(e).getString(),t));const a=i.encrypt;a&&(A=a.createCipherTransform(e.num,e.gen).encryptString(A));const s=`${e.num} ${e.gen} obj\n<< /Type /EmbeddedFile /Length ${A.length}>>\nstream\n`+A+"\nendstream\nendobj\n";t.push({ref:e,data:s})}({xfaData:I,xfaDatasetsRef:s,newRefs:t,xref:i});const C=[];let B=A.length;const h=A.at(-1);10!==h&&13!==h&&(C.push("\n"),B+=1);const Q=function(A,e,t){const i=new hA(null);i.set("Prev",A.startXRef);const a=A.newRef;return t?(e.push({ref:a,data:""}),i.set("Size",a.num+1),i.set("Type",cA.get("XRef"))):i.set("Size",a.num),null!==A.rootRef&&i.set("Root",A.rootRef),null!==A.infoRef&&i.set("Info",A.infoRef),null!==A.encryptRef&&i.set("Encrypt",A.encryptRef),i}(e,t,c);t=t.sort(((A,e)=>A.ref.num-e.ref.num));for(const{data:A}of t)null!==A&&C.push(A);await(c?async function(A,e,t,i,a){const s=[];let n=0,g=0;for(const{ref:A,data:i}of t){let t;n=Math.max(n,e),null!==i?(t=Math.min(A.gen,65535),s.push([1,e,t]),e+=i.length):(t=Math.min(A.gen+1,65535),s.push([0,0,t])),g=Math.max(g,t)}i.set("Index",Ao(t));const r=[1,se(n),se(g)];i.set("W",r),eo(e,A,i);const o=r.reduce(((A,e)=>A+e),0),I=new Uint8Array(o*s.length),c=new ne(I);c.dict=i;let C=0;for(const[A,e,t]of s)C=_r(A,r[0],C,I),C=_r(e,r[1],C,I),C=_r(t,r[2],C,I);await Or(A.newRef,c,a,{}),a.push("startxref\n",e.toString(),"\n%%EOF\n")}(e,B,t,Q,C):async function(A,e,t,i,a){a.push("xref\n");const s=Ao(t);let n=0;for(const{ref:A,data:i}of t)A.num===s[n]&&(a.push(`${s[n]} ${s[n+1]}\n`),n+=2),null!==i?(a.push(`${e.toString().padStart(10,"0")} ${Math.min(A.gen,65535).toString().padStart(5,"0")} n\r\n`),e+=i.length):a.push(`0000000000 ${Math.min(A.gen+1,65535).toString().padStart(5,"0")} f\r\n`);eo(e,A,i),a.push("trailer\n"),await Xr(i,a),a.push("\nstartxref\n",e.toString(),"\n%%EOF\n")}(e,B,t,Q,C));const l=C.reduce(((A,e)=>A+e.length),A.length),E=new Uint8Array(l);E.set(A);let u=A.length;for(const A of C)$r(A,u,E),u+=A.length;return E}class io{constructor(A,e){this.dict=A,this.ref=e instanceof QA?e:null,this.roleMap=new Map,this.structParentIds=null}init(){this.readRoleMap()}#M(A,e,t){if(!(A instanceof QA)||e<0)return;this.structParentIds||=new EA;let i=this.structParentIds.get(A);i||(i=[],this.structParentIds.put(A,i)),i.push([e,t])}addAnnotationIdToPage(A,e){this.#M(A,e,4)}readRoleMap(){const A=this.dict.get("RoleMap");A instanceof hA&&A.forEach(((A,e)=>{e instanceof cA&&this.roleMap.set(A,e.name)}))}static async canCreateStructureTree({catalogRef:A,pdfManager:e,newAnnotationsByPage:t}){if(!(A instanceof QA))return N("Cannot save the struct tree: no catalog reference."),!1;let i=0,a=!0;for(const[A,s]of t){const{ref:t}=await e.getPage(A);if(!(t instanceof QA)){N(`Cannot save the struct tree: page ${A} has no ref.`),a=!0;break}for(const A of s)A.accessibilityData?.type&&(A.parentTreeId=i++,a=!1)}if(a){for(const A of t.values())for(const e of A)delete e.parentTreeId;return!1}return!0}static async createStructureTree({newAnnotationsByPage:A,xref:e,catalogRef:t,pdfManager:i,newRefs:a}){const s=i.catalog.cloneDict(),n=new EA;n.put(t,s);const g=e.getNewTemporaryRef();s.set("StructTreeRoot",g);const r=new hA(e);r.set("Type",cA.get("StructTreeRoot"));const o=e.getNewTemporaryRef();r.set("ParentTree",o);const I=[];r.set("K",I),n.put(g,r);const c=new hA(e),C=[];c.set("Nums",C);const B=await this.#L({newAnnotationsByPage:A,structTreeRootRef:g,structTreeRoot:null,kids:I,nums:C,xref:e,pdfManager:i,newRefs:a,cache:n});r.set("ParentTreeNextKey",B),n.put(o,c);const h=[];for(const[A,t]of n.items())h.length=0,await Or(A,t,h,e),a.push({ref:A,data:h.join("")})}async canUpdateStructTree({pdfManager:A,xref:e,newAnnotationsByPage:t}){if(!this.ref)return N("Cannot update the struct tree: no root reference."),!1;let i=this.dict.get("ParentTreeNextKey");if(!Number.isInteger(i)||i<0)return N("Cannot update the struct tree: invalid next key."),!1;const a=this.dict.get("ParentTree");if(!(a instanceof hA))return N("Cannot update the struct tree: ParentTree isn't a dict."),!1;const s=a.get("Nums");if(!Array.isArray(s))return N("Cannot update the struct tree: nums isn't an array."),!1;const n=new wr(a,e);for(const e of t.keys()){const{pageDict:t}=await A.getPage(e);if(!t.has("StructParents"))continue;const i=t.get("StructParents");if(!Number.isInteger(i)||!Array.isArray(n.get(i)))return N(`Cannot save the struct tree: page ${e} has a wrong id.`),!1}let g=!0;for(const[e,a]of t){const{pageDict:t}=await A.getPage(e);io.#J({elements:a,xref:this.dict.xref,pageDict:t,numberTree:n});for(const A of a)A.accessibilityData?.type&&(A.accessibilityData.structParent>=0||(A.parentTreeId=i++),g=!1)}if(g){for(const A of t.values())for(const e of A)delete e.parentTreeId,delete e.structTreeParent;return!1}return!0}async updateStructureTree({newAnnotationsByPage:A,pdfManager:e,newRefs:t}){const i=this.dict.xref,a=this.dict.clone(),s=this.ref,n=new EA;n.put(s,a);let g,r=a.getRaw("ParentTree");r instanceof QA?g=i.fetch(r):(g=r,r=i.getNewTemporaryRef(),a.set("ParentTree",r)),g=g.clone(),n.put(r,g);let o=g.getRaw("Nums"),I=null;o instanceof QA&&(I=o,o=i.fetch(I)),o=o.slice(),I||g.set("Nums",o);const c=await io.#L({newAnnotationsByPage:A,structTreeRootRef:s,structTreeRoot:this,kids:null,nums:o,xref:i,pdfManager:e,newRefs:t,cache:n});if(-1===c)return;a.set("ParentTreeNextKey",c),I&&n.put(I,o);const C=[];for(const[A,e]of n.items())C.length=0,await Or(A,e,C,i),t.push({ref:A,data:C.join("")})}static async#L({newAnnotationsByPage:A,structTreeRootRef:e,structTreeRoot:t,kids:i,nums:a,xref:s,pdfManager:n,newRefs:g,cache:r}){const o=cA.get("OBJR");let I,c=-1;const C=[];for(const[B,h]of A){const A=await n.getPage(B),{ref:Q}=A,l=Q instanceof QA;for(const{accessibilityData:n,ref:E,parentTreeId:u,structTreeParent:d}of h){if(!n?.type)continue;const{structParent:h}=n;if(t&&Number.isInteger(h)&&h>=0){let e=(I||=new Map).get(B);void 0===e&&(e=new no(t,A.pageDict).collectObjects(Q),I.set(B,e));const i=e?.get(h);if(i){const A=s.fetch(i).clone();io.#H(A,n),C.length=0,await Or(i,A,C,s),g.push({ref:i,data:C.join("")});continue}}c=Math.max(c,u);const f=s.getNewTemporaryRef(),p=new hA(s);io.#H(p,n),await this.#Y({structTreeParent:d,tagDict:p,newTagRef:f,structTreeRootRef:e,fallbackKids:i,xref:s,cache:r});const m=new hA(s);p.set("K",m),m.set("Type",o),l&&m.set("Pg",Q),m.set("Obj",E),r.put(f,p),a.push(u,f)}}return c+1}static#H(A,{type:e,title:t,lang:i,alt:a,expanded:s,actualText:n}){A.set("S",cA.get(e)),t&&A.set("T",ee(t)),i&&A.set("Lang",ee(i)),a&&A.set("Alt",ee(a)),s&&A.set("E",ee(s)),n&&A.set("ActualText",ee(n))}static#J({elements:A,xref:e,pageDict:t,numberTree:i}){const a=new Map;for(const e of A)if(e.structTreeParentId){const A=parseInt(e.structTreeParentId.split("_mc")[1],10);let t=a.get(A);t||(t=[],a.set(A,t)),t.push(e)}const s=t.get("StructParents");if(!Number.isInteger(s))return;const n=i.get(s),g=(A,t,i)=>{const s=a.get(A);if(s){const A=t.getRaw("P"),a=e.fetchIfRef(A);if(A instanceof QA&&a instanceof hA){const A={ref:i,dict:t};for(const e of s)e.structTreeParent=A}return!0}return!1};for(const A of n){if(!(A instanceof QA))continue;const t=e.fetch(A),i=t.get("K");if(Number.isInteger(i))g(i,t,A);else if(Array.isArray(i))for(let a of i){if(a=e.fetchIfRef(a),Number.isInteger(a)&&g(a,t,A))break;if(!(a instanceof hA))continue;if(!uA(a.get("Type"),"MCR"))break;const i=a.get("MCID");if(Number.isInteger(i)&&g(i,t,A))break}}}static async#Y({structTreeParent:A,tagDict:e,newTagRef:t,structTreeRootRef:i,fallbackKids:a,xref:s,cache:n}){let g,r=null;A?(({ref:r}=A),g=A.dict.getRaw("P")||i):g=i,e.set("P",g);const o=s.fetchIfRef(g);if(!o)return void a.push(t);let I=n.get(g);I||(I=o.clone(),n.put(g,I));const c=I.getRaw("K");let C=c instanceof QA?n.get(c):null;if(!C){C=s.fetchIfRef(c),C=Array.isArray(C)?C.slice():[c];const A=s.getNewTemporaryRef();I.set("K",A),n.put(A,C)}const B=C.indexOf(r);C.splice(B>=0?B+1:C.length,0,t)}}class ao{constructor(A,e){this.tree=A,this.dict=e,this.kids=[],this.parseKids()}get role(){const A=this.dict.get("S"),e=A instanceof cA?A.name:"",{root:t}=this.tree;return t.roleMap.has(e)?t.roleMap.get(e):e}parseKids(){let A=null;const e=this.dict.getRaw("Pg");e instanceof QA&&(A=e.toString());const t=this.dict.get("K");if(Array.isArray(t))for(const e of t){const t=this.parseKid(A,e);t&&this.kids.push(t)}else{const e=this.parseKid(A,t);e&&this.kids.push(e)}}parseKid(A,e){if(Number.isInteger(e))return this.tree.pageDict.objId!==A?null:new so({type:1,mcid:e,pageObjId:A});let t=null;if(e instanceof QA?t=this.dict.xref.fetch(e):e instanceof hA&&(t=e),!t)return null;const i=t.getRaw("Pg");i instanceof QA&&(A=i.toString());const a=t.get("Type")instanceof cA?t.get("Type").name:null;if("MCR"===a){if(this.tree.pageDict.objId!==A)return null;const e=t.getRaw("Stm");return new so({type:2,refObjId:e instanceof QA?e.toString():null,pageObjId:A,mcid:t.get("MCID")})}if("OBJR"===a){if(this.tree.pageDict.objId!==A)return null;const e=t.getRaw("Obj");return new so({type:3,refObjId:e instanceof QA?e.toString():null,pageObjId:A})}return new so({type:5,dict:t})}}class so{constructor({type:A,dict:e=null,mcid:t=null,pageObjId:i=null,refObjId:a=null}){this.type=A,this.dict=e,this.mcid=t,this.pageObjId=i,this.refObjId=a,this.parentNode=null}}class no{constructor(A,e){this.root=A,this.rootDict=A?A.dict:null,this.pageDict=e,this.nodes=[]}collectObjects(A){if(!(this.root&&this.rootDict&&A instanceof QA))return null;const e=this.rootDict.get("ParentTree");if(!e)return null;const t=this.root.structParentIds?.get(A);if(!t)return null;const i=new Map,a=new wr(e,this.rootDict.xref);for(const[A]of t){const e=a.getRaw(A);e instanceof QA&&i.set(A,e)}return i}parse(A){if(!(this.root&&this.rootDict&&A instanceof QA))return;const e=this.rootDict.get("ParentTree");if(!e)return;const t=this.pageDict.get("StructParents"),i=this.root.structParentIds?.get(A);if(!Number.isInteger(t)&&!i)return;const a=new Map,s=new wr(e,this.rootDict.xref);if(Number.isInteger(t)){const A=s.get(t);if(Array.isArray(A))for(const e of A)e instanceof QA&&this.addNode(this.rootDict.xref.fetch(e),a)}if(i)for(const[A,e]of i){const t=s.get(A);if(t){const A=this.addNode(this.rootDict.xref.fetchIfRef(t),a);1===A?.kids?.length&&3===A.kids[0].type&&(A.kids[0].type=e)}}}addNode(A,e,t=0){if(t>40)return N("StructTree MAX_DEPTH reached."),null;if(!(A instanceof hA))return null;if(e.has(A))return e.get(A);const i=new ao(this,A);e.set(A,i);const a=A.get("P");if(!a||uA(a.get("Type"),"StructTreeRoot"))return this.addTopLevelNode(A,i)||e.delete(A),i;const s=this.addNode(a,e,t+1);if(!s)return i;let n=!1;for(const e of s.kids)5===e.type&&e.dict===A&&(e.parentNode=i,n=!0);return n||e.delete(A),i}addTopLevelNode(A,e){const t=this.rootDict.get("K");if(!t)return!1;if(t instanceof hA)return t.objId===A.objId&&(this.nodes[0]=e,!0);if(!Array.isArray(t))return!0;let i=!1;for(let a=0;a40)return void N("StructTree too deep to be fully serialized.");const a=Object.create(null);a.role=e.role,a.children=[],t.children.push(a);let s=e.dict.get("Alt");"string"!=typeof s&&(s=e.dict.get("ActualText")),"string"==typeof s&&(a.alt=$(s));const n=e.dict.get("A");if(n instanceof hA){const A=KA(n.getArray("BBox"),null);if(A)a.bbox=A;else{const A=n.get("Width"),e=n.get("Height");"number"==typeof A&&A>0&&"number"==typeof e&&e>0&&(a.bbox=[0,0,A,e])}}const g=e.dict.get("Lang");"string"==typeof g&&(a.lang=$(g));for(const t of e.kids){const e=5===t.type?t.parentNode:null;e?A(e,a,i+1):1===t.type||2===t.type?a.children.push({type:"content",id:`p${t.pageObjId}_mc${t.mcid}`}):3===t.type?a.children.push({type:"object",id:t.refObjId}):4===t.type&&a.children.push({type:"annotation",id:`pdfjs_internal_id_${t.refObjId}`})}}const e=Object.create(null);e.children=[],e.role="Root";for(const t of this.nodes)t&&A(t,e);return e}}function go(A){if(!Array.isArray(A)||A.length<2)return!1;const[e,t,...i]=A;if(!(e instanceof QA||Number.isInteger(e)))return!1;if(!(t instanceof cA))return!1;const a=i.length;let s=!0;switch(t.name){case"XYZ":if(a<2||a>3)return!1;break;case"Fit":case"FitB":return 0===a;case"FitH":case"FitBH":case"FitV":case"FitBV":if(a>1)return!1;break;case"FitR":if(4!==a)return!1;s=!1;break;default:return!1}for(const A of i)if(!("number"==typeof A||s&&null===A))return!1;return!0}function ro(A){return A instanceof hA&&(A=A.get("D")),go(A)?A:null}function oo(A){let e=A.get("D");if(e){if(e instanceof cA&&(e=e.name),"string"==typeof e)return $(e);if(go(e))return JSON.stringify(e)}return null}class Io{constructor(A,e){if(this.pdfManager=A,this.xref=e,this._catDict=e.getCatalogObj(),!(this._catDict instanceof hA))throw new T("Catalog object is not a dictionary.");this.toplevelPagesDict,this._actualNumPages=null,this.fontCache=new EA,this.builtInCMapCache=new Map,this.standardFontDataCache=new Map,this.globalImageCache=new gg,this.pageKidsCountCache=new EA,this.pageIndexCache=new EA,this.pageDictCache=new EA,this.nonBlendModesSet=new lA,this.systemFontCache=new Map}cloneDict(){return this._catDict.clone()}get version(){const A=this._catDict.get("Version");if(A instanceof cA){if(yA.test(A.name))return L(this,"version",A.name);N(`Invalid PDF catalog version: ${A.name}`)}return L(this,"version",null)}get lang(){const A=this._catDict.get("Lang");return L(this,"lang",A&&"string"==typeof A?$(A):null)}get needsRendering(){const A=this._catDict.get("NeedsRendering");return L(this,"needsRendering","boolean"==typeof A&&A)}get collection(){let A=null;try{const e=this._catDict.get("Collection");e instanceof hA&&e.size>0&&(A=e)}catch(A){if(A instanceof DA)throw A;G("Cannot fetch Collection entry; assuming no collection is present.")}return L(this,"collection",A)}get acroForm(){let A=null;try{const e=this._catDict.get("AcroForm");e instanceof hA&&e.size>0&&(A=e)}catch(A){if(A instanceof DA)throw A;G("Cannot fetch AcroForm entry; assuming no forms are present.")}return L(this,"acroForm",A)}get acroFormRef(){const A=this._catDict.getRaw("AcroForm");return L(this,"acroFormRef",A instanceof QA?A:null)}get metadata(){const A=this._catDict.getRaw("Metadata");if(!(A instanceof QA))return L(this,"metadata",null);let e=null;try{const t=this.xref.fetch(A,!this.xref.encrypt?.encryptMetadata);if(t instanceof mA&&t.dict instanceof hA){const A=t.dict.get("Type"),i=t.dict.get("Subtype");if(uA(A,"Metadata")&&uA(i,"XML")){const A=AA(t.getString());A&&(e=new Nr(A).serializable)}}}catch(A){if(A instanceof DA)throw A;G(`Skipping invalid Metadata: "${A}".`)}return L(this,"metadata",e)}get markInfo(){let A=null;try{A=this._readMarkInfo()}catch(A){if(A instanceof DA)throw A;N("Unable to read mark info.")}return L(this,"markInfo",A)}_readMarkInfo(){const A=this._catDict.get("MarkInfo");if(!(A instanceof hA))return null;const e={Marked:!1,UserProperties:!1,Suspects:!1};for(const t in e){const i=A.get(t);"boolean"==typeof i&&(e[t]=i)}return e}get structTreeRoot(){let A=null;try{A=this._readStructTreeRoot()}catch(A){if(A instanceof DA)throw A;N("Unable read to structTreeRoot info.")}return L(this,"structTreeRoot",A)}_readStructTreeRoot(){const A=this._catDict.getRaw("StructTreeRoot"),e=this.xref.fetchIfRef(A);if(!(e instanceof hA))return null;const t=new io(e,A);return t.init(),t}get toplevelPagesDict(){const A=this._catDict.get("Pages");if(!(A instanceof hA))throw new T("Invalid top-level pages dictionary.");return L(this,"toplevelPagesDict",A)}get documentOutline(){let A=null;try{A=this._readDocumentOutline()}catch(A){if(A instanceof DA)throw A;N("Unable to read document outline.")}return L(this,"documentOutline",A)}_readDocumentOutline(){let A=this._catDict.get("Outlines");if(!(A instanceof hA))return null;if(A=A.getRaw("First"),!(A instanceof QA))return null;const e={items:[]},t=[{obj:A,parent:e}],i=new lA;i.put(A);const a=this.xref,s=new Uint8ClampedArray(3);for(;t.length>0;){const e=t.shift(),n=a.fetchIfRef(e.obj);if(null===n)continue;n.has("Title")||N("Invalid outline item encountered.");const g={url:null,dest:null,action:null};Io.parseDestDictionary({destDict:n,resultObj:g,docBaseUrl:this.baseUrl,docAttachments:this.attachments});const r=n.get("Title"),o=n.get("F")||0,I=n.getArray("C"),c=n.get("Count");let C=s;!HA(I,3)||0===I[0]&&0===I[1]&&0===I[2]||(C=ce.singletons.rgb.getRgb(I,0));const B={action:g.action,attachment:g.attachment,dest:g.dest,url:g.url,unsafeUrl:g.unsafeUrl,newWindow:g.newWindow,setOCGState:g.setOCGState,title:"string"==typeof r?$(r):"",color:C,count:Number.isInteger(c)?c:void 0,bold:!!(2&o),italic:!!(1&o),items:[]};e.parent.items.push(B),A=n.getRaw("First"),A instanceof QA&&!i.has(A)&&(t.push({obj:A,parent:B}),i.put(A)),A=n.getRaw("Next"),A instanceof QA&&!i.has(A)&&(t.push({obj:A,parent:e.parent}),i.put(A))}return e.items.length>0?e.items:null}get permissions(){let A=null;try{A=this._readPermissions()}catch(A){if(A instanceof DA)throw A;N("Unable to read permissions.")}return L(this,"permissions",A)}_readPermissions(){const A=this.xref.trailer.get("Encrypt");if(!(A instanceof hA))return null;let e=A.get("P");if("number"!=typeof e)return null;e+=2**32;const t=[];for(const A in r){const i=r[A];e&i&&t.push(i)}return t}get optionalContentConfig(){let A=null;try{const e=this._catDict.get("OCProperties");if(!e)return L(this,"optionalContentConfig",null);const t=e.get("D");if(!t)return L(this,"optionalContentConfig",null);const i=e.get("OCGs");if(!Array.isArray(i))return L(this,"optionalContentConfig",null);const a=[],s=new lA;for(const A of i)A instanceof QA&&!s.has(A)&&(s.put(A),a.push(this.#v(A)));A=this.#K(t,s),A.groups=a}catch(A){if(A instanceof DA)throw A;N(`Unable to read optional content config: ${A}`)}return L(this,"optionalContentConfig",A)}#v(A){const e=this.xref.fetch(A),t={id:A.toString(),name:null,intent:null,usage:{print:null,view:null}},i=e.get("Name");"string"==typeof i&&(t.name=$(i));let a=e.getArray("Intent");Array.isArray(a)||(a=[a]),a.every((A=>A instanceof cA))&&(t.intent=a.map((A=>A.name)));const s=e.get("Usage");if(!(s instanceof hA))return t;const n=t.usage,g=s.get("Print");if(g instanceof hA){const A=g.get("PrintState");if(A instanceof cA)switch(A.name){case"ON":case"OFF":n.print={printState:A.name}}}const r=s.get("View");if(r instanceof hA){const A=r.get("ViewState");if(A instanceof cA)switch(A.name){case"ON":case"OFF":n.view={viewState:A.name}}}return t}#K(A,e){function t(A){const t=[];if(Array.isArray(A))for(const i of A)i instanceof QA&&e.has(i)&&t.push(i.toString());return t}function i(A,t=0){if(!Array.isArray(A))return null;const i=[];for(const s of A){if(s instanceof QA&&e.has(s)){n.put(s),i.push(s.toString());continue}const A=a(s,t);A&&i.push(A)}if(t>0)return i;const s=[];for(const A of e)n.has(A)||s.push(A.toString());return s.length&&i.push({name:null,order:s}),i}function a(A,e){if(++e>g)return N("parseNestedOrder - reached MAX_NESTED_LEVELS."),null;const t=s.fetchIfRef(A);if(!Array.isArray(t))return null;const a=s.fetchIfRef(t[0]);if("string"!=typeof a)return null;const n=i(t.slice(1),e);return n&&n.length?{name:$(a),order:n}:null}const s=this.xref,n=new lA,g=10;return{name:"string"==typeof A.get("Name")?$(A.get("Name")):null,creator:"string"==typeof A.get("Creator")?$(A.get("Creator")):null,baseState:A.get("BaseState")instanceof cA?A.get("BaseState").name:null,on:t(A.get("ON")),off:t(A.get("OFF")),order:i(A.get("Order")),groups:null}}setActualNumPages(A=null){this._actualNumPages=A}get hasActualNumPages(){return null!==this._actualNumPages}get _pagesCount(){const A=this.toplevelPagesDict.get("Count");if(!Number.isInteger(A))throw new T("Page count in top-level pages dictionary is not an integer.");return L(this,"_pagesCount",A)}get numPages(){return this.hasActualNumPages?this._actualNumPages:this._pagesCount}get destinations(){const A=this._readDests(),e=Object.create(null);if(A instanceof yr)for(const[t,i]of A.getAll()){const A=ro(i);A&&(e[$(t)]=A)}else A instanceof hA&&A.forEach((function(A,t){const i=ro(t);i&&(e[A]=i)}));return L(this,"destinations",e)}getDestination(A){const e=this._readDests();if(e instanceof yr){const t=ro(e.get(A));if(t)return t;const i=this.destinations[A];if(i)return N(`Found "${A}" at an incorrect position in the NameTree.`),i}else if(e instanceof hA){const t=ro(e.get(A));if(t)return t}return null}_readDests(){const A=this._catDict.get("Names");return A?.has("Dests")?new yr(A.getRaw("Dests"),this.xref):this._catDict.has("Dests")?this._catDict.get("Dests"):void 0}get pageLabels(){let A=null;try{A=this._readPageLabels()}catch(A){if(A instanceof DA)throw A;N("Unable to read page labels.")}return L(this,"pageLabels",A)}_readPageLabels(){const A=this._catDict.getRaw("PageLabels");if(!A)return null;const e=new Array(this.numPages);let t=null,i="";const a=new wr(A,this.xref).getAll();let s="",n=1;for(let A=0,g=this.numPages;A=1))throw new T("Invalid start in PageLabel dictionary.");n=A}else n=1}switch(t){case"D":s=n;break;case"R":case"r":s=NA(n,"r"===t);break;case"A":case"a":const A=26,e="a"===t?97:65,i=n-1;s=String.fromCharCode(e+i%A).repeat(Math.floor(i/A)+1);break;default:if(t)throw new T(`Invalid style "${t}" in PageLabel dictionary.`);s=""}e[A]=i+s,n++}return e}get pageLayout(){const A=this._catDict.get("PageLayout");let e="";if(A instanceof cA)switch(A.name){case"SinglePage":case"OneColumn":case"TwoColumnLeft":case"TwoColumnRight":case"TwoPageLeft":case"TwoPageRight":e=A.name}return L(this,"pageLayout",e)}get pageMode(){const A=this._catDict.get("PageMode");let e="UseNone";if(A instanceof cA)switch(A.name){case"UseNone":case"UseOutlines":case"UseThumbs":case"FullScreen":case"UseOC":case"UseAttachments":e=A.name}return L(this,"pageMode",e)}get viewerPreferences(){const A=this._catDict.get("ViewerPreferences");if(!(A instanceof hA))return L(this,"viewerPreferences",null);let e=null;for(const t of A.getKeys()){const i=A.get(t);let a;switch(t){case"HideToolbar":case"HideMenubar":case"HideWindowUI":case"FitWindow":case"CenterWindow":case"DisplayDocTitle":case"PickTrayByPDFSize":"boolean"==typeof i&&(a=i);break;case"NonFullScreenPageMode":if(i instanceof cA)switch(i.name){case"UseNone":case"UseOutlines":case"UseThumbs":case"UseOC":a=i.name;break;default:a="UseNone"}break;case"Direction":if(i instanceof cA)switch(i.name){case"L2R":case"R2L":a=i.name;break;default:a="L2R"}break;case"ViewArea":case"ViewClip":case"PrintArea":case"PrintClip":if(i instanceof cA)switch(i.name){case"MediaBox":case"CropBox":case"BleedBox":case"TrimBox":case"ArtBox":a=i.name;break;default:a="CropBox"}break;case"PrintScaling":if(i instanceof cA)switch(i.name){case"None":case"AppDefault":a=i.name;break;default:a="AppDefault"}break;case"Duplex":if(i instanceof cA)switch(i.name){case"Simplex":case"DuplexFlipShortEdge":case"DuplexFlipLongEdge":a=i.name;break;default:a="None"}break;case"PrintPageRange":Array.isArray(i)&&i.length%2==0&&i.every(((A,e,t)=>Number.isInteger(A)&&A>0&&(0===e||A>=t[e-1])&&A<=this.numPages))&&(a=i);break;case"NumCopies":Number.isInteger(i)&&i>0&&(a=i);break;default:N(`Ignoring non-standard key in ViewerPreferences: ${t}.`);continue}void 0!==a?(e||(e=Object.create(null)),e[t]=a):N(`Bad value, for key "${t}", in ViewerPreferences: ${i}.`)}return L(this,"viewerPreferences",e)}get openAction(){const A=this._catDict.get("OpenAction"),e=Object.create(null);if(A instanceof hA){const t=new hA(this.xref);t.set("A",A);const i={url:null,dest:null,action:null};Io.parseDestDictionary({destDict:t,resultObj:i}),Array.isArray(i.dest)?e.dest=i.dest:i.action&&(e.action=i.action)}else Array.isArray(A)&&(e.dest=A);return L(this,"openAction",X(e)>0?e:null)}get attachments(){const A=this._catDict.get("Names");let e=null;if(A instanceof hA&&A.has("EmbeddedFiles")){const t=new yr(A.getRaw("EmbeddedFiles"),this.xref);for(const[A,i]of t.getAll()){const t=new kr(i,this.xref);e||(e=Object.create(null)),e[$(A)]=t.serializable}}return L(this,"attachments",e)}get xfaImages(){const A=this._catDict.get("Names");let e=null;if(A instanceof hA&&A.has("XFAImages")){const t=new yr(A.getRaw("XFAImages"),this.xref);for(const[A,i]of t.getAll())e||(e=new hA(this.xref)),e.set($(A),i)}return L(this,"xfaImages",e)}_collectJavaScript(){const A=this._catDict.get("Names");let e=null;function t(A,t){if(!(t instanceof hA))return;if(!uA(t.get("S"),"JavaScript"))return;let i=t.get("JS");if(i instanceof mA)i=i.getString();else if("string"!=typeof i)return;i=$(i).replaceAll("\0",""),i&&(e||=new Map).set(A,i)}if(A instanceof hA&&A.has("JavaScript")){const e=new yr(A.getRaw("JavaScript"),this.xref);for(const[A,i]of e.getAll())t($(A),i)}const i=this._catDict.get("OpenAction");return i&&t("OpenAction",i),e}get jsActions(){const A=this._collectJavaScript();let e=ZA(this.xref,this._catDict,h);if(A){e||=Object.create(null);for(const[t,i]of A)t in e?e[t].push(i):e[t]=[i]}return L(this,"jsActions",e)}async fontFallback(A,e){const t=await Promise.all(this.fontCache);for(const i of t)if(i.loadedName===A)return void i.fallback(e)}async cleanup(A=!1){Dr(),this.globalImageCache.clear(A),this.pageKidsCountCache.clear(),this.pageIndexCache.clear(),this.pageDictCache.clear(),this.nonBlendModesSet.clear();const e=await Promise.all(this.fontCache);for(const{dict:A}of e)delete A.cacheKey;this.fontCache.clear(),this.builtInCMapCache.clear(),this.standardFontDataCache.clear(),this.systemFontCache.clear()}async getPageDict(A){const e=[this.toplevelPagesDict],t=new lA,i=this._catDict.getRaw("Pages");i instanceof QA&&t.put(i);const a=this.xref,s=this.pageKidsCountCache,n=this.pageIndexCache,g=this.pageDictCache;let r=0;for(;e.length;){const i=e.pop();if(i instanceof QA){const o=s.get(i);if(o>=0&&r+o<=A){r+=o;continue}if(t.has(i))throw new T("Pages tree contains circular reference.");t.put(i);const I=await(g.get(i)||a.fetchAsync(i));if(I instanceof hA){let e=I.getRaw("Type");if(e instanceof QA&&(e=await a.fetchAsync(e)),uA(e,"Page")||!I.has("Kids")){if(s.has(i)||s.put(i,1),n.has(i)||n.put(i,r),r===A)return[I,i];r++;continue}}e.push(I);continue}if(!(i instanceof hA))throw new T("Page dictionary kid reference points to wrong type of object.");const{objId:o}=i;let I=i.getRaw("Count");if(I instanceof QA&&(I=await a.fetchAsync(I)),Number.isInteger(I)&&I>=0&&(o&&!s.has(o)&&s.put(o,I),r+I<=A)){r+=I;continue}let c=i.getRaw("Kids");if(c instanceof QA&&(c=await a.fetchAsync(c)),!Array.isArray(c)){let e=i.getRaw("Type");if(e instanceof QA&&(e=await a.fetchAsync(e)),uA(e,"Page")||!i.has("Kids")){if(r===A)return[i,null];r++;continue}throw new T("Page dictionary kids object is not an array.")}for(let A=c.length-1;A>=0;A--){const t=c[A];e.push(t),i===this.toplevelPagesDict&&t instanceof QA&&!g.has(t)&&g.put(t,a.fetchAsync(t))}}throw new Error(`Page index ${A} not found.`)}async getAllPageDicts(A=!1){const{ignoreErrors:e}=this.pdfManager.evaluatorOptions,t=[{currentNode:this.toplevelPagesDict,posInKids:0}],i=new lA,a=this._catDict.getRaw("Pages");a instanceof QA&&i.put(a);const s=new Map,n=this.xref,g=this.pageIndexCache;let r=0;function o(t){if(t instanceof kA&&!A)throw t;A&&e&&0===r&&(N(`getAllPageDicts - Skipping invalid first page: "${t}".`),t=hA.empty),s.set(r++,[t,null])}for(;t.length>0;){const A=t.at(-1),{currentNode:e,posInKids:a}=A;let C=e.getRaw("Kids");if(C instanceof QA)try{C=await n.fetchAsync(C)}catch(A){o(A);break}if(!Array.isArray(C)){o(new T("Page dictionary kids object is not an array."));break}if(a>=C.length){t.pop();continue}const B=C[a];let h;if(B instanceof QA){if(i.has(B)){o(new T("Pages tree contains circular reference."));break}i.put(B);try{h=await n.fetchAsync(B)}catch(A){o(A);break}}else h=B;if(!(h instanceof hA)){o(new T("Page dictionary kid reference points to wrong type of object."));break}let Q=h.getRaw("Type");if(Q instanceof QA)try{Q=await n.fetchAsync(Q)}catch(A){o(A);break}uA(Q,"Page")||!h.has("Kids")?(I=h,(c=B instanceof QA?B:null)&&!g.has(c)&&g.put(c,r),s.set(r++,[I,c])):t.push({currentNode:h,posInKids:0}),A.posInKids++}var I,c;return s}getPageIndex(A){const e=this.pageIndexCache.get(A);if(void 0!==e)return Promise.resolve(e);const t=this.xref;let i=0;const a=e=>function(e){let i,a=0;return t.fetchAsync(e).then((function(t){if(pA(e,A)&&!fA(t,"Page")&&!(t instanceof hA&&!t.has("Type")&&t.has("Contents")))throw new T("The reference does not point to a /Page dictionary.");if(!t)return null;if(!(t instanceof hA))throw new T("Node must be a dictionary.");return i=t.getRaw("Parent"),t.getAsync("Parent")})).then((function(A){if(!A)return null;if(!(A instanceof hA))throw new T("Parent must be a dictionary.");return A.getAsync("Kids")})).then((function(A){if(!A)return null;const s=[];let n=!1;for(const i of A){if(!(i instanceof QA))throw new T("Kid must be a reference.");if(pA(i,e)){n=!0;break}s.push(t.fetchAsync(i).then((function(A){if(!(A instanceof hA))throw new T("Kid node must be a dictionary.");A.has("Count")?a+=A.get("Count"):a++})))}if(!n)throw new T("Kid reference not found in parent's kids.");return Promise.all(s).then((function(){return[a,i]}))}))}(e).then((e=>{if(!e)return this.pageIndexCache.put(A,i),i;const[t,s]=e;return i+=t,a(s)}));return a(A)}get baseUrl(){const A=this._catDict.get("URI");if(A instanceof hA){const e=A.get("Base");if("string"==typeof e){const A=M(e,null,{tryConvertEncoding:!0});if(A)return L(this,"baseUrl",A.href)}}return L(this,"baseUrl",this.pdfManager.docBaseUrl)}static parseDestDictionary({destDict:A,resultObj:e,docBaseUrl:t=null,docAttachments:i=null}){if(!(A instanceof hA))return void N("parseDestDictionary: `destDict` must be a dictionary.");let a,s,n=A.get("A");if(n instanceof hA||(A.has("Dest")?n=A.get("Dest"):(n=A.get("AA"),n instanceof hA&&(n.has("D")?n=n.get("D"):n.has("U")&&(n=n.get("U"))))),n instanceof hA){const A=n.get("S");if(!(A instanceof cA))return void N("parseDestDictionary: Invalid type in Action dictionary.");const t=A.name;switch(t){case"ResetForm":const A=n.get("Flags"),g=!(1&("number"==typeof A?A:0)),r=[],o=[];for(const A of n.get("Fields")||[])A instanceof QA?o.push(A.toString()):"string"==typeof A&&r.push($(A));e.resetForm={fields:r,refs:o,include:g};break;case"URI":a=n.get("URI"),a instanceof cA&&(a="/"+a.name);break;case"GoTo":s=n.get("D");break;case"Launch":case"GoToR":const I=n.get("F");if(I instanceof hA){const A=new kr(I,null,!0),{rawFilename:e}=A.serializable;a=e}else"string"==typeof I&&(a=I);const c=oo(n);c&&"string"==typeof a&&(a=a.split("#",1)[0]+"#"+c);const C=n.get("NewWindow");"boolean"==typeof C&&(e.newWindow=C);break;case"GoToE":const B=n.get("T");let h;if(i&&B instanceof hA){const A=B.get("R"),e=B.get("N");uA(A,"C")&&"string"==typeof e&&(h=i[$(e)])}if(h){e.attachment=h;const A=oo(n);A&&(e.attachmentDest=A)}else N('parseDestDictionary - unimplemented "GoToE" action.');break;case"Named":const Q=n.get("N");Q instanceof cA&&(e.action=Q.name);break;case"SetOCGState":const l=n.get("State"),E=n.get("PreserveRB");if(!Array.isArray(l)||0===l.length)break;const u=[];for(const A of l)if(A instanceof cA)switch(A.name){case"ON":case"OFF":case"Toggle":u.push(A.name)}else A instanceof QA&&u.push(A.toString());if(u.length!==l.length)break;e.setOCGState={state:u,preserveRB:"boolean"!=typeof E||E};break;case"JavaScript":const d=n.get("JS");let f;d instanceof mA?f=d.getString():"string"==typeof d&&(f=d);const p=f&&_A($(f));if(p){a=p.url,e.newWindow=p.newWindow;break}default:if("JavaScript"===t||"SubmitForm"===t)break;N(`parseDestDictionary - unsupported action: "${t}".`)}}else A.has("Dest")&&(s=A.get("Dest"));if("string"==typeof a){const A=M(a,t,{addDefaultProtocol:!0,tryConvertEncoding:!0});A&&(e.url=A.href),e.unsafeUrl=a}s&&(s instanceof cA&&(s=s.name),"string"==typeof s?e.dest=$(s):go(s)&&(e.dest=s))}}function co(A,e){if(A instanceof hA)A=A.getRawValues();else if(A instanceof mA)A=A.dict.getRawValues();else if(!Array.isArray(A))return;for(const i of A)((t=i)instanceof QA||t instanceof hA||t instanceof mA||Array.isArray(t))&&e.push(i);var t}class Co{constructor(A,e,t){this.dict=A,this.keys=e,this.xref=t,this.refSet=null}async load(){if(this.xref.stream.isDataLoaded)return;const{keys:A,dict:e}=this;this.refSet=new lA;const t=[];for(const i of A){const A=e.getRaw(i);void 0!==A&&t.push(A)}return this._walk(t)}async _walk(A){const e=[],t=[];for(;A.length;){let i=A.pop();if(i instanceof QA){if(this.refSet.has(i))continue;try{this.refSet.put(i),i=this.xref.fetch(i)}catch(A){if(!(A instanceof DA)){N(`ObjectLoader._walk - requesting all data: "${A}".`),this.refSet=null;const{manager:e}=this.xref.stream;return e.requestAllChunks()}e.push(i),t.push({begin:A.begin,end:A.end})}}if(i instanceof mA){const A=i.getBaseStreams();if(A){let a=!1;for(const e of A)e.isDataLoaded||(a=!0,t.push({begin:e.start,end:e.end}));a&&e.push(i)}}co(i,A)}if(t.length){await this.xref.stream.manager.requestRanges(t);for(const A of e)A instanceof QA&&this.refSet.remove(A);return this._walk(e)}this.refSet=null}}const Bo=Symbol(),ho=Symbol(),Qo=Symbol(),lo=Symbol(),Eo=Symbol(),uo=Symbol(),fo=Symbol(),po=Symbol(),mo=Symbol(),yo=Symbol("content"),wo=Symbol("data"),Do=Symbol(),bo=Symbol("extra"),ko=Symbol(),Fo=Symbol(),So=Symbol(),Ro=Symbol(),Go=Symbol(),No=Symbol(),xo=Symbol(),Uo=Symbol(),Mo=Symbol(),Lo=Symbol(),Jo=Symbol(),Ho=Symbol(),Yo=Symbol(),vo=Symbol(),Ko=Symbol(),qo=Symbol(),To=Symbol(),Po=Symbol(),Wo=Symbol(),Zo=Symbol(),Oo=Symbol(),Xo=Symbol(),Vo=Symbol(),jo=Symbol(),zo=Symbol(),_o=Symbol(),$o=Symbol(),AI=Symbol(),eI=Symbol(),tI=Symbol(),iI=Symbol(),aI=Symbol(),sI=Symbol("namespaceId"),nI=Symbol("nodeName"),gI=Symbol(),rI=Symbol(),oI=Symbol(),II=Symbol(),cI=Symbol(),CI=Symbol(),BI=Symbol(),hI=Symbol(),QI=Symbol("root"),lI=Symbol(),EI=Symbol(),uI=Symbol(),dI=Symbol(),fI=Symbol(),pI=Symbol(),mI=Symbol(),yI=Symbol(),wI=Symbol(),DI=Symbol(),bI=Symbol(),kI=Symbol("uid"),FI=Symbol(),SI={config:{id:0,check:A=>A.startsWith("http://www.xfa.org/schema/xci/")},connectionSet:{id:1,check:A=>A.startsWith("http://www.xfa.org/schema/xfa-connection-set/")},datasets:{id:2,check:A=>A.startsWith("http://www.xfa.org/schema/xfa-data/")},form:{id:3,check:A=>A.startsWith("http://www.xfa.org/schema/xfa-form/")},localeSet:{id:4,check:A=>A.startsWith("http://www.xfa.org/schema/xfa-locale-set/")},pdf:{id:5,check:A=>"http://ns.adobe.com/xdp/pdf/"===A},signature:{id:6,check:A=>"http://www.w3.org/2000/09/xmldsig#"===A},sourceSet:{id:7,check:A=>A.startsWith("http://www.xfa.org/schema/xfa-source-set/")},stylesheet:{id:8,check:A=>"http://www.w3.org/1999/XSL/Transform"===A},template:{id:9,check:A=>A.startsWith("http://www.xfa.org/schema/xfa-template/")},xdc:{id:10,check:A=>A.startsWith("http://www.xfa.org/schema/xdc/")},xdp:{id:11,check:A=>"http://ns.adobe.com/xdp/"===A},xfdf:{id:12,check:A=>"http://ns.adobe.com/xfdf/"===A},xhtml:{id:13,check:A=>"http://www.w3.org/1999/xhtml"===A},xmpmeta:{id:14,check:A=>"http://ns.adobe.com/xmpmeta/"===A}},RI={pt:A=>A,cm:A=>A/2.54*72,mm:A=>A/25.4*72,in:A=>72*A,px:A=>A},GI=/([+-]?\d+\.?\d*)(.*)/;function NI(A){return A.startsWith("'")||A.startsWith('"')?A.slice(1,-1):A}function xI({data:A,defaultValue:e,validate:t}){if(!A)return e;A=A.trim();const i=parseInt(A,10);return!isNaN(i)&&t(i)?i:e}function UI({data:A,defaultValue:e,validate:t}){if(!A)return e;A=A.trim();const i=parseFloat(A);return!isNaN(i)&&t(i)?i:e}function MI({data:A,defaultValue:e,validate:t}){return A&&t(A=A.trim())?A:e}function LI(A,e){return MI({data:A,defaultValue:e[0],validate:A=>e.includes(A)})}function JI(A,e="0"){if(e||="0",!A)return JI(e);const t=A.trim().match(GI);if(!t)return JI(e);const[,i,a]=t,s=parseFloat(i);if(isNaN(s))return JI(e);if(0===s)return 0;const n=RI[a];return n?n(s):s}function HI(A){if(!A)return{num:1,den:1};const e=A.trim().split(/\s*:\s*/).map((A=>parseFloat(A))).filter((A=>!isNaN(A)));if(1===e.length&&e.push(1),0===e.length)return{num:1,den:1};const[t,i]=e;return{num:t,den:i}}function YI(A){return A?A.trim().split(/\s+/).map((A=>({excluded:"-"===A[0],viewname:A.substring(1)}))):[]}class vI{static get FAILURE(){return L(this,"FAILURE",new vI(!1,null,null,null))}static get EMPTY(){return L(this,"EMPTY",new vI(!0,null,null,null))}constructor(A,e,t,i){this.success=A,this.html=e,this.bbox=t,this.breakNode=i}isBreak(){return!!this.breakNode}static breakNode(A){return new vI(!1,null,null,A)}static success(A,e=null){return new vI(!0,A,e,null)}}class KI{constructor(A){this.fonts=new Map,this.cache=new Map,this.warned=new Set,this.defaultFont=null,this.add(A)}add(A,e=null){for(const e of A)this.addPdfFont(e);for(const A of this.fonts.values())A.regular||(A.regular=A.italic||A.bold||A.bolditalic);if(!e||0===e.size)return;const t=this.fonts.get("PdfJS-Fallback-PdfJS-XFA");for(const A of e)this.fonts.set(A,t)}addPdfFont(A){const e=A.cssFontInfo,t=e.fontFamily;let i=this.fonts.get(t);i||(i=Object.create(null),this.fonts.set(t,i),this.defaultFont||(this.defaultFont=i));let a="";const s=parseFloat(e.fontWeight);0!==parseFloat(e.italicAngle)?a=s>=700?"bolditalic":"italic":s>=700&&(a="bold"),a||((A.name.includes("Bold")||A.psName?.includes("Bold"))&&(a="bold"),(A.name.includes("Italic")||A.name.endsWith("It")||A.psName?.includes("Italic")||A.psName?.endsWith("It"))&&(a+="italic")),a||(a="regular"),i[a]=A}getDefault(){return this.defaultFont}find(A,e=!0){let t=this.fonts.get(A)||this.cache.get(A);if(t)return t;const i=/,|-|_| |bolditalic|bold|italic|regular|it/gi;let a=A.replaceAll(i,"");if(t=this.fonts.get(a),t)return this.cache.set(A,t),t;a=a.toLowerCase();const s=[];for(const[A,e]of this.fonts.entries())A.replaceAll(i,"").toLowerCase().startsWith(a)&&s.push(e);if(0===s.length)for(const[,A]of this.fonts.entries())A.regular.name?.replaceAll(i,"").toLowerCase().startsWith(a)&&s.push(A);if(0===s.length){a=a.replaceAll(/psmt|mt/gi,"");for(const[A,e]of this.fonts.entries())A.replaceAll(i,"").toLowerCase().startsWith(a)&&s.push(e)}if(0===s.length)for(const A of this.fonts.values())A.regular.name?.replaceAll(i,"").toLowerCase().startsWith(a)&&s.push(A);return s.length>=1?(1!==s.length&&e&&N(`XFA - Too many choices to guess the correct font: ${A}`),this.cache.set(A,s[0]),s[0]):(e&&!this.warned.has(A)&&(this.warned.add(A),N(`XFA - Cannot find the font: ${A}`)),null)}}function qI(A,e){return"italic"===A.posture?"bold"===A.weight?e.bolditalic:e.italic:"bold"===A.weight?e.bold:e.regular}class TI{constructor(A,e,t,i){if(this.lineHeight=t,this.paraMargin=e||{top:0,bottom:0,left:0,right:0},!A)return void([this.pdfFont,this.xfaFont]=this.defaultFont(i));this.xfaFont={typeface:A.typeface,posture:A.posture,weight:A.weight,size:A.size,letterSpacing:A.letterSpacing};const a=i.find(A.typeface);a?(this.pdfFont=qI(A,a),this.pdfFont||([this.pdfFont,this.xfaFont]=this.defaultFont(i))):[this.pdfFont,this.xfaFont]=this.defaultFont(i)}defaultFont(A){const e=A.find("Helvetica",!1)||A.find("Myriad Pro",!1)||A.find("Arial",!1)||A.getDefault();if(e?.regular){const A=e.regular;return[A,{typeface:A.cssFontInfo.fontFamily,posture:"normal",weight:"normal",size:10,letterSpacing:0}]}return[null,{typeface:"Courier",posture:"normal",weight:"normal",size:10,letterSpacing:0}]}}class PI{constructor(A,e,t,i){this.fontFinder=i,this.stack=[new TI(A,e,t,i)]}pushData(A,e,t){const i=this.stack.at(-1);for(const e of["typeface","posture","weight","size","letterSpacing"])A[e]||(A[e]=i.xfaFont[e]);for(const A of["top","bottom","left","right"])isNaN(e[A])&&(e[A]=i.paraMargin[A]);const a=new TI(A,e,t||i.lineHeight,this.fontFinder);a.pdfFont||(a.pdfFont=i.pdfFont),this.stack.push(a)}popFont(){this.stack.pop()}topFont(){return this.stack.at(-1)}}class WI{constructor(A,e,t,i){this.glyphs=[],this.fontSelector=new PI(A,e,t,i),this.extraHeight=0}pushData(A,e,t){this.fontSelector.pushData(A,e,t)}popFont(A){return this.fontSelector.popFont()}addPara(){const A=this.fontSelector.topFont();this.extraHeight+=A.paraMargin.top+A.paraMargin.bottom}addString(A){if(!A)return;const e=this.fontSelector.topFont(),t=e.xfaFont.size;if(e.pdfFont){const i=e.xfaFont.letterSpacing,a=e.pdfFont,s=a.lineHeight||1.2,n=e.lineHeight||Math.max(1.2,s)*t,g=s-(void 0===a.lineGap?.2:a.lineGap),r=Math.max(1,g)*t,o=t/1e3,I=a.defaultWidth||a.charsToGlyphs(" ")[0].width;for(const e of A.split(/[\u2029\n]/)){const A=a.encodeString(e).join(""),t=a.charsToGlyphs(A);for(const A of t){const e=A.width||I;this.glyphs.push([e*o+i,n,r,A.unicode,!1])}this.glyphs.push([0,0,0,"\n",!0])}this.glyphs.pop()}else{for(const e of A.split(/[\u2029\n]/)){for(const A of e.split(""))this.glyphs.push([t,1.2*t,t,A,!1]);this.glyphs.push([0,0,0,"\n",!0])}this.glyphs.pop()}}compute(A){let e=-1,t=0,i=0,a=0,s=0,n=0,g=!1,r=!0;for(let o=0,I=this.glyphs.length;oA?(i=Math.max(i,s),s=0,a+=n,n=l,e=-1,t=0,g=!0,r=!1):(n=Math.max(l,n),t=s,s+=I,e=o):s+I>A?(a+=n,n=l,-1!==e?(o=e,i=Math.max(i,t),s=0,e=-1,t=0):(i=Math.max(i,s),s=I),g=!0,r=!1):(s+=I,n=Math.max(l,n))}return i=Math.max(i,s),a+=n+this.extraHeight,{width:1.02*i,height:a,isBroken:g}}}const ZI=/^[^.[]+/,OI=/^[^\]]+/,XI={dot:0,dotDot:1,dotHash:2,dotBracket:3,dotParen:4},VI=new Map([["$data",(A,e)=>A.datasets?A.datasets.data:A],["$record",(A,e)=>(A.datasets?A.datasets.data:A)[Ho]()[0]],["$template",(A,e)=>A.template],["$connectionSet",(A,e)=>A.connectionSet],["$form",(A,e)=>A.form],["$layout",(A,e)=>A.layout],["$host",(A,e)=>A.host],["$dataWindow",(A,e)=>A.dataWindow],["$event",(A,e)=>A.event],["!",(A,e)=>A.datasets],["$xfa",(A,e)=>A],["xfa",(A,e)=>A],["$",(A,e)=>e]]),jI=new WeakMap;function zI(A,e,t=!0){let i=A.match(ZI);if(!i)return null;let[a]=i;const s=[{name:a,cacheName:"."+a,index:0,js:null,formCalc:null,operator:XI.dot}];let n=a.length;for(;n0&&I.push(A)}if(0!==I.length||g||0!==r)A=isFinite(o)?I.filter((A=>oA[o])):I.flat();else{const t=e[qo]();if(!(e=t))return null;r=-1,A=[e]}}return 0===A.length?null:A}function $I(A,e,t){const i=zI(t);if(!i)return null;if(i.some((A=>A.operator===XI.dotDot)))return null;const a=VI.get(i[0].name);let s=0;a?(A=a(A,e),s=1):A=e||A;for(let e=i.length;sA[mI]())).join("")}get[tc](){const A=Object.getPrototypeOf(this);if(!A._attributes){const e=A._attributes=new Set;for(const A of Object.getOwnPropertyNames(this)){if(null===this[A]||this[A]instanceof dc||this[A]instanceof fc)break;e.add(A)}}return L(this,tc,A._attributes)}[_o](A){let e=this;for(;e;){if(e===A)return!0;e=e[qo]()}return!1}[qo](){return this[Bc]}[Ko](){return this[qo]()}[Ho](A=null){return A?this[A]:this[ic]}[Do](){const A=Object.create(null);this[yo]&&(A.$content=this[yo]);for(const e of Object.getOwnPropertyNames(this)){const t=this[e];null!==t&&(t instanceof dc?A[e]=t[Do]():t instanceof fc?t.isEmpty()||(A[e]=t.dump()):A[e]=t)}return A}[bI](){return null}[wI](){return vI.EMPTY}*[Yo](){for(const A of this[Ho]())yield A}*[gc](A,e){for(const t of this[Yo]())if(!A||e===A.has(t[nI])){const A=this[Go](),e=t[wI](A);e.success||(this[bo].failingNode=t),yield e}}[Fo](){return null}[ho](A,e){this[bo].children.push(A)}[Go](){}[lo]({filter:A=null,include:e=!0}){if(this[bo].generator){const A=this[Go](),e=this[bo].failingNode[wI](A);if(!e.success)return e;e.html&&this[ho](e.html,e.bbox),delete this[bo].failingNode}else this[bo].generator=this[gc](A,e);for(;;){const A=this[bo].generator.next();if(A.done)break;const e=A.value;if(!e.success)return e;e.html&&this[ho](e.html,e.bbox)}return this[bo].generator=null,vI.EMPTY}[dI](A){this[Qc]=new Set(Object.keys(A))}[oc](A){const e=this[tc],t=this[Qc];return[...A].filter((A=>e.has(A)&&!t.has(A)))}[lI](A,e=new Set){for(const t of this[ic])t[hc](A,e)}[hc](A,e){const t=this[rc](A,e);t?this[Ac](t,A,e):this[lI](A,e)}[rc](A,e){const{use:t,usehref:i}=this;if(!t&&!i)return null;let a=null,s=null,n=null,g=t;if(i?(g=i,i.startsWith("#som(")&&i.endsWith(")")?s=i.slice(5,-1):i.startsWith(".#som(")&&i.endsWith(")")?s=i.slice(6,-1):i.startsWith("#")?n=i.slice(1):i.startsWith(".#")&&(n=i.slice(2))):t.startsWith("#")?n=t.slice(1):s=t,this.use=this.usehref="",n?a=A.get(n):(a=_I(A.get(QI),this,s,!0,!1),a&&(a=a[0])),!a)return N(`XFA - Invalid prototype reference: ${g}.`),null;if(a[nI]!==this[nI])return N(`XFA - Incompatible prototype: ${a[nI]} !== ${this[nI]}.`),null;if(e.has(a))return N("XFA - Cycle detected in prototypes use."),null;e.add(a);const r=a[rc](A,e);return r&&a[Ac](r,A,e),a[lI](A,e),e.delete(a),a}[Ac](A,e,t){if(t.has(A))N("XFA - Cycle detected in prototypes use.");else{!this[yo]&&A[yo]&&(this[yo]=A[yo]),new Set(t).add(A);for(const e of this[oc](A[Qc]))this[e]=A[e],this[Qc]&&this[Qc].add(e);for(const i of Object.getOwnPropertyNames(this)){if(this[tc].has(i))continue;const a=this[i],s=A[i];if(a instanceof fc){for(const A of a[ic])A[hc](e,t);for(let i=a[ic].length,n=s[ic].length;idc[ac](A))):"object"==typeof A&&null!==A?Object.assign({},A):A}[po](){const A=Object.create(Object.getPrototypeOf(this));for(const e of Object.getOwnPropertySymbols(this))try{A[e]=this[e]}catch{L(A,e,this[e])}A[kI]=`${A[nI]}${Ec++}`,A[ic]=[];for(const e of Object.getOwnPropertyNames(this)){if(this[tc].has(e)){A[e]=dc[ac](this[e]);continue}const t=this[e];A[e]=t instanceof fc?new fc(t[cc]):null}for(const e of this[ic]){const t=e[nI],i=e[po]();A[ic].push(i),i[Bc]=A,null===A[t]?A[t]=i:A[t][ic].push(i)}return A}[Ho](A=null){return A?this[ic].filter((e=>e[nI]===A)):this[ic]}[No](A){return this[A]}[xo](A,e,t=!0){return Array.from(this[Uo](A,e,t))}*[Uo](A,e,t=!0){if("parent"!==A){for(const t of this[ic])t[nI]===A&&(yield t),t.name===A&&(yield t),(e||t[tI]())&&(yield*t[Uo](A,e,!1));t&&this[tc].has(A)&&(yield new pc(this,A,this[A]))}else yield this[Bc]}}class fc{constructor(A=1/0){this[cc]=A,this[ic]=[]}get isXFAObject(){return!1}get isXFAObjectArray(){return!0}push(A){return this[ic].length<=this[cc]?(this[ic].push(A),!0):(N(`XFA - node "${A[nI]}" accepts no more than ${this[cc]} children`),!1)}isEmpty(){return 0===this[ic].length}dump(){return 1===this[ic].length?this[ic][0][Do]():this[ic].map((A=>A[Do]()))}[po](){const A=new fc(this[cc]);return A[ic]=this[ic].map((A=>A[po]())),A}get children(){return this[ic]}clear(){this[ic].length=0}}class pc{constructor(A,e,t){this[Bc]=A,this[nI]=e,this[yo]=t,this[mo]=!1,this[kI]="attribute"+Ec++}[qo](){return this[Bc]}[zo](){return!0}[Mo](){return this[yo].trim()}[fI](A){A=A.value||"",this[yo]=A.toString()}[mI](){return this[yo]}[_o](A){return this[Bc]===A||this[Bc][_o](A)}}class mc extends dc{constructor(A,e,t={}){if(super(A,e),this[yo]="",this[sc]=null,"#text"!==e){const A=new Map;this[ec]=A;for(const[e,i]of Object.entries(t))A.set(e,new pc(this,e,i));if(t.hasOwnProperty(gI)){const A=t[gI].xfa.dataNode;void 0!==A&&("dataGroup"===A?this[sc]=!1:"dataValue"===A&&(this[sc]=!0))}}this[mo]=!1}[DI](A){const e=this[nI];if("#text"===e)return void A.push(VA(this[yo]));const t=eA(e),i=this[sI]===uc?"xfa:":"";A.push(`<${i}${t}`);for(const[e,t]of this[ec].entries()){const i=eA(e);A.push(` ${i}="${VA(t[yo])}"`)}if(null!==this[sc]&&(this[sc]?A.push(' xfa:dataNode="dataValue"'):A.push(' xfa:dataNode="dataGroup"')),this[yo]||0!==this[ic].length){if(A.push(">"),this[yo])"string"==typeof this[yo]?A.push(VA(this[yo])):this[yo][DI](A);else for(const e of this[ic])e[DI](A);A.push(``)}else A.push("/>")}[rI](A){if(this[yo]){const A=new mc(this[sI],"#text");this[Qo](A),A[yo]=this[yo],this[yo]=""}return this[Qo](A),!0}[II](A){this[yo]+=A}[ko](){if(this[yo]&&this[ic].length>0){const A=new mc(this[sI],"#text");this[Qo](A),A[yo]=this[yo],delete this[yo]}}[wI](){return"#text"===this[nI]?vI.success({name:"#text",value:this[yo]}):vI.EMPTY}[Ho](A=null){return A?this[ic].filter((e=>e[nI]===A)):this[ic]}[Ro](){return this[ec]}[No](A){const e=this[ec].get(A);return void 0!==e?e:this[Ho](A)}*[Uo](A,e){const t=this[ec].get(A);t&&(yield t);for(const t of this[ic])t[nI]===A&&(yield t),e&&(yield*t[Uo](A,e))}*[So](A,e){const t=this[ec].get(A);!t||e&&t[mo]||(yield t);for(const t of this[ic])yield*t[So](A,e)}*[Jo](A,e,t){for(const i of this[ic])i[nI]!==A||t&&i[mo]||(yield i),e&&(yield*i[Jo](A,e,t))}[zo](){return null===this[sc]?0===this[ic].length||this[ic][0][sI]===SI.xhtml.id:this[sc]}[Mo](){return null===this[sc]?0===this[ic].length?this[yo].trim():this[ic][0][sI]===SI.xhtml.id?this[ic][0][mI]().trim():null:this[yo].trim()}[fI](A){A=A.value||"",this[yo]=A.toString()}[Do](A=!1){const e=Object.create(null);A&&(e.$ns=this[sI]),this[yo]&&(e.$content=this[yo]),e.$name=this[nI],e.children=[];for(const t of this[ic])e.children.push(t[Do](A));e.attributes=Object.create(null);for(const[A,t]of this[ec])e.attributes[A]=t[yo];return e}}class yc extends dc{constructor(A,e){super(A,e),this[yo]=""}[II](A){this[yo]+=A}[ko](){}}class wc extends yc{constructor(A,e,t){super(A,e),this[Cc]=t}[ko](){this[yo]=MI({data:this[yo],defaultValue:this[Cc][0],validate:A=>this[Cc].includes(A)})}[Eo](A){super[Eo](A),delete this[Cc]}}class Dc extends yc{[ko](){this[yo]=this[yo].trim()}}class bc extends yc{constructor(A,e,t,i){super(A,e),this[nc]=t,this[lc]=i}[ko](){this[yo]=xI({data:this[yo],defaultValue:this[nc],validate:this[lc]})}[Eo](A){super[Eo](A),delete this[nc],delete this[lc]}}class kc extends bc{constructor(A,e){super(A,e,0,(A=>1===A))}}class Fc extends bc{constructor(A,e){super(A,e,1,(A=>0===A))}}function Sc(A){return"string"==typeof A?"0px":Number.isInteger(A)?`${A}px`:`${A.toFixed(2)}px`}const Rc={anchorType(A,e){const t=A[Ko]();if(t&&(!t.layout||"position"===t.layout))switch("transform"in e||(e.transform=""),A.anchorType){case"bottomCenter":e.transform+="translate(-50%, -100%)";break;case"bottomLeft":e.transform+="translate(0,-100%)";break;case"bottomRight":e.transform+="translate(-100%,-100%)";break;case"middleCenter":e.transform+="translate(-50%,-50%)";break;case"middleLeft":e.transform+="translate(0,-50%)";break;case"middleRight":e.transform+="translate(-100%,-50%)";break;case"topCenter":e.transform+="translate(-50%,0)";break;case"topRight":e.transform+="translate(-100%,0)"}},dimensions(A,e){const t=A[Ko]();let i=A.w;const a=A.h;if(t.layout?.includes("row")){const e=t[bo],a=A.colSpan;let s;-1===a?(s=e.columnWidths.slice(e.currentColumn).reduce(((A,e)=>A+e),0),e.currentColumn=0):(s=e.columnWidths.slice(e.currentColumn,e.currentColumn+a).reduce(((A,e)=>A+e),0),e.currentColumn=(e.currentColumn+A.colSpan)%e.columnWidths.length),isNaN(s)||(i=A.w=s)}e.width=""!==i?Sc(i):"auto",e.height=""!==a?Sc(a):"auto"},position(A,e){const t=A[Ko]();t?.layout&&"position"!==t.layout||(e.position="absolute",e.left=Sc(A.x),e.top=Sc(A.y))},rotate(A,e){A.rotate&&("transform"in e||(e.transform=""),e.transform+=`rotate(-${A.rotate}deg)`,e.transformOrigin="top left")},presence(A,e){switch(A.presence){case"invisible":e.visibility="hidden";break;case"hidden":case"inactive":e.display="none"}},hAlign(A,e){if("para"===A[nI])switch(A.hAlign){case"justifyAll":e.textAlign="justify-all";break;case"radix":e.textAlign="left";break;default:e.textAlign=A.hAlign}else switch(A.hAlign){case"left":e.alignSelf="start";break;case"center":e.alignSelf="center";break;case"right":e.alignSelf="end"}},margin(A,e){A.margin&&(e.margin=A.margin[bI]().margin)}};function Gc(A,e){"position"===A[Ko]().layout&&(A.minW>0&&(e.minWidth=Sc(A.minW)),A.maxW>0&&(e.maxWidth=Sc(A.maxW)),A.minH>0&&(e.minHeight=Sc(A.minH)),A.maxH>0&&(e.maxHeight=Sc(A.maxH)))}function Nc(A,e,t,i,a,s){const n=new WI(e,t,i,a);return"string"==typeof A?n.addString(A):A[cI](n),n.compute(s)}function xc(A,e){let t=null,i=null,a=!1;if((!A.w||!A.h)&&A.value){let s=0,n=0;A.margin&&(s=A.margin.leftInset+A.margin.rightInset,n=A.margin.topInset+A.margin.bottomInset);let g=null,r=null;A.para&&(r=Object.create(null),g=""===A.para.lineHeight?null:A.para.lineHeight,r.top=""===A.para.spaceAbove?0:A.para.spaceAbove,r.bottom=""===A.para.spaceBelow?0:A.para.spaceBelow,r.left=""===A.para.marginLeft?0:A.para.marginLeft,r.right=""===A.para.marginRight?0:A.para.marginRight);let o=A.font;if(!o){const e=A[To]();let t=A[qo]();for(;t&&t!==e;){if(t.font){o=t.font;break}t=t[qo]()}}const I=(A.w||e.width)-s,c=A[Po].fontFinder;if(A.value.exData&&A.value.exData[yo]&&"text/html"===A.value.exData.contentType){const e=Nc(A.value.exData[yo],o,r,g,c,I);i=e.width,t=e.height,a=e.isBroken}else{const e=A.value[mI]();if(e){const A=Nc(e,o,r,g,c,I);i=A.width,t=A.height,a=A.isBroken}}null===i||A.w||(i+=s),null===t||A.h||(t+=n)}return{w:i,h:t,isBroken:a}}function Uc(A,e,t){let i;if(""!==A.w&&""!==A.h)i=[A.x,A.y,A.w,A.h];else{if(!t)return null;let a=A.w;if(""===a){if(0===A.maxW){const e=A[Ko]();a="position"===e.layout&&""!==e.w?0:A.minW}else a=Math.min(A.maxW,t.width);e.attributes.style.width=Sc(a)}let s=A.h;if(""===s){if(0===A.maxH){const e=A[Ko]();s="position"===e.layout&&""!==e.h?0:A.minH}else s=Math.min(A.maxH,t.height);e.attributes.style.height=Sc(s)}i=[A.x,A.y,a,s]}return i}function Mc(A){const e=A[Ko]();if(e.layout?.includes("row")){const t=e[bo],i=A.colSpan;let a;a=-1===i?t.columnWidths.slice(t.currentColumn).reduce(((A,e)=>A+e),0):t.columnWidths.slice(t.currentColumn,t.currentColumn+i).reduce(((A,e)=>A+e),0),isNaN(a)||(A.w=a)}e.layout&&"position"!==e.layout&&(A.x=A.y=0),"table"===A.layout&&""===A.w&&Array.isArray(A.columnWidths)&&(A.w=A.columnWidths.reduce(((A,e)=>A+e),0))}function Lc(A){switch(A.layout){case"position":default:return"xfaPosition";case"lr-tb":return"xfaLrTb";case"rl-row":return"xfaRlRow";case"rl-tb":return"xfaRlTb";case"row":return"xfaRow";case"table":return"xfaTable";case"tb":return"xfaTb"}}function Jc(A,...e){const t=Object.create(null);for(const i of e){const e=A[i];if(null!==e)if(Rc.hasOwnProperty(i))Rc[i](A,t);else if(e instanceof dc){const A=e[bI]();A?Object.assign(t,A):N(`(DEBUG) - XFA - style for ${i} not implemented yet`)}}return t}function Hc(A,e){const{attributes:t}=e,{style:i}=t,a={name:"div",attributes:{class:["xfaWrapper"],style:Object.create(null)},children:[]};if(t.class.push("xfaWrapped"),A.border){const{widths:t,insets:s}=A.border[bo];let n,g,r=s[0],o=s[3];const I=s[0]+s[2],c=s[1]+s[3];switch(A.border.hand){case"even":r-=t[0]/2,o-=t[3]/2,n=`calc(100% + ${(t[1]+t[3])/2-c}px)`,g=`calc(100% + ${(t[0]+t[2])/2-I}px)`;break;case"left":r-=t[0],o-=t[3],n=`calc(100% + ${t[1]+t[3]-c}px)`,g=`calc(100% + ${t[0]+t[2]-I}px)`;break;case"right":n=c?`calc(100% - ${c}px)`:"100%",g=I?`calc(100% - ${I}px)`:"100%"}const C=["xfaBorder"];Kc(A.border)&&C.push("xfaPrintOnly");const B={name:"div",attributes:{class:C,style:{top:`${r}px`,left:`${o}px`,width:n,height:g}},children:[]};for(const A of["border","borderWidth","borderColor","borderRadius","borderStyle"])void 0!==i[A]&&(B.attributes.style[A]=i[A],delete i[A]);a.children.push(B,e)}else a.children.push(e);for(const A of["background","backgroundClip","top","left","width","height","minWidth","minHeight","maxWidth","maxHeight","transform","transformOrigin","visibility"])void 0!==i[A]&&(a.attributes.style[A]=i[A],delete i[A]);return a.attributes.style.position="absolute"===i.position?"absolute":"relative",delete i.position,i.alignSelf&&(a.attributes.style.alignSelf=i.alignSelf,delete i.alignSelf),a}function Yc(A){const e=JI(A.textIndent,"0px");if(e>=0)return;const t="padding"+("left"==("right"===A.textAlign?"right":"left")?"Left":"Right"),i=JI(A[t],"0px");A[t]=i-e+"px"}function vc(A,e){switch(A.access){case"nonInteractive":e.push("xfaNonInteractive");break;case"readOnly":e.push("xfaReadOnly");break;case"protected":e.push("xfaDisabled")}}function Kc(A){return A.relevant.length>0&&!A.relevant[0].excluded&&"print"===A.relevant[0].viewname}function qc(A){const e=A[To]()[bo].paraStack;return e.length?e.at(-1):null}function Tc(A,e,t){if(t.attributes.class?.includes("xfaRich")){e&&(""===A.h&&(e.height="auto"),""===A.w&&(e.width="auto"));const i=qc(A);if(i){const A=t.attributes.style;switch(A.display="flex",A.flexDirection="column",i.vAlign){case"top":A.justifyContent="start";break;case"bottom":A.justifyContent="end";break;case"middle":A.justifyContent="center"}const e=i[bI]();for(const[t,i]of Object.entries(e))t in A||(A[t]=i)}}}function Pc(A,e,t,i){if(!t)return void delete i.fontFamily;const a=NI(A.typeface);i.fontFamily=`"${a}"`;const s=t.find(a);if(s){const{fontFamily:t}=s.regular.cssFontInfo;t!==a&&(i.fontFamily=`"${t}"`);const n=qc(e);if(n&&""!==n.lineHeight)return;if(i.lineHeight)return;const g=qI(A,s);g&&(i.lineHeight=Math.max(1.2,g.lineHeight))}}function Wc(A){const e=M(A,null,{addDefaultProtocol:!0,tryConvertEncoding:!0});return e?e.href:null}function Zc(A,e){return{name:"div",attributes:{class:["lr-tb"===A.layout?"xfaLr":"xfaRl"]},children:e}}function Oc(A){if(!A[bo])return null;const e={name:"div",attributes:A[bo].attributes,children:A[bo].children};if(A[bo].failingNode){const t=A[bo].failingNode[Fo]();t&&(A.layout.endsWith("-tb")?e.children.push(Zc(A,[t])):e.children.push(t))}return 0===e.children.length?null:e}function Xc(A,e,t){const i=A[bo],a=i.availableSpace,[s,n,g,r]=t;switch(A.layout){case"position":i.width=Math.max(i.width,s+g),i.height=Math.max(i.height,n+r),i.children.push(e);break;case"lr-tb":case"rl-tb":i.line&&1!==i.attempt||(i.line=Zc(A,[]),i.children.push(i.line),i.numberInLine=0),i.numberInLine+=1,i.line.children.push(e),0===i.attempt?(i.currentWidth+=g,i.height=Math.max(i.height,i.prevHeight+r)):(i.currentWidth=g,i.prevHeight=i.height,i.height+=r,i.attempt=0),i.width=Math.max(i.width,i.currentWidth);break;case"rl-row":case"row":{i.children.push(e),i.width+=g,i.height=Math.max(i.height,r);const A=Sc(i.height);for(const e of i.children)e.attributes.style.height=A;break}case"table":case"tb":i.width=Math.min(a.width,Math.max(i.width,g)),i.height+=r,i.children.push(e)}}function Vc(A){const e=A[bo].availableSpace,t=A.margin?A.margin.topInset+A.margin.bottomInset:0,i=A.margin?A.margin.leftInset+A.margin.rightInset:0;switch(A.layout){case"lr-tb":case"rl-tb":return 0===A[bo].attempt?{width:e.width-i-A[bo].currentWidth,height:e.height-t-A[bo].prevHeight}:{width:e.width-i,height:e.height-t-A[bo].height};case"rl-row":case"row":return{width:A[bo].columnWidths.slice(A[bo].currentColumn).reduce(((A,e)=>A+e)),height:e.height-i};case"table":case"tb":return{width:e.width-i,height:e.height-t-A[bo].height};default:return e}}function jc(A,e){if(null===A[To]()[bo].firstUnsplittable)return!0;if(0===A.w||0===A.h)return!0;const t=A[Ko](),i=t[bo]?.attempt||0,[,a,s,n]=function(A){let e,t,i=""===A.w?NaN:A.w,a=""===A.h?NaN:A.h,[s,n]=[0,0];switch(A.anchorType||""){case"bottomCenter":[s,n]=[i/2,a];break;case"bottomLeft":[s,n]=[0,a];break;case"bottomRight":[s,n]=[i,a];break;case"middleCenter":[s,n]=[i/2,a/2];break;case"middleLeft":[s,n]=[0,a/2];break;case"middleRight":[s,n]=[i,a/2];break;case"topCenter":[s,n]=[i/2,0];break;case"topRight":[s,n]=[i,0]}switch(A.rotate||0){case 0:[e,t]=[-s,-n];break;case 90:[e,t]=[-n,s],[i,a]=[a,-i];break;case 180:[e,t]=[s,n],[i,a]=[-i,-a];break;case 270:[e,t]=[n,-s],[i,a]=[-a,i]}return[A.x+e+Math.min(0,i),A.y+t+Math.min(0,a),Math.abs(i),Math.abs(a)]}(A);switch(t.layout){case"lr-tb":case"rl-tb":return 0===i?A[To]()[bo].noLayoutFailure?""!==A.w?Math.round(s-e.width)<=2:e.width>2:!(""!==A.h&&Math.round(n-e.height)>2)&&(""!==A.w?Math.round(s-e.width)<=2||0===t[bo].numberInLine&&e.height>2:e.width>2):!!A[To]()[bo].noLayoutFailure||!(""!==A.h&&Math.round(n-e.height)>2)&&(""===A.w||Math.round(s-e.width)<=2||!t[eI]())&&e.height>2;case"table":case"tb":return!!A[To]()[bo].noLayoutFailure||(""===A.h||A[AI]()?(""===A.w||Math.round(s-e.width)<=2||!t[eI]())&&e.height>2:Math.round(n-e.height)<=2);case"position":return!!A[To]()[bo].noLayoutFailure||(""===A.h||Math.round(n+a-e.height)<=2||n+a>A[To]()[bo].currentContentArea.h);case"rl-row":case"row":return!!A[To]()[bo].noLayoutFailure||""===A.h||Math.round(n-e.height)<=2;default:return!0}}const zc=SI.template.id,_c="http://www.w3.org/2000/svg",$c=/^H(\d+)$/,AC=new Set(["image/gif","image/jpeg","image/jpg","image/pjpeg","image/png","image/apng","image/x-png","image/bmp","image/x-ms-bmp","image/tiff","image/tif","application/octet-stream"]),eC=[[[66,77],"image/bmp"],[[255,216,255],"image/jpeg"],[[73,73,42,0],"image/tiff"],[[77,77,0,42],"image/tiff"],[[71,73,70,56,57,97],"image/gif"],[[137,80,78,71,13,10,26,10],"image/png"]];function tC(A){if(!A||!A.border)return{w:0,h:0};const e=A.border[Lo]();return e?{w:e.widths[0]+e.widths[2]+e.insets[0]+e.insets[2],h:e.widths[1]+e.widths[3]+e.insets[1]+e.insets[3]}:{w:0,h:0}}function iC(A){return A.margin&&(A.margin.topInset||A.margin.rightInset||A.margin.bottomInset||A.margin.leftInset)}function aC(A,e){if(!A.value){const e=new uh({});A[Qo](e),A.value=e}A.value[fI](e)}function*sC(A){for(const e of A[Ho]())e instanceof ah?yield*e[Yo]():yield e}function nC(A){return"error"===A.validate?.nullTest}function gC(A){for(;A;){if(!A.traversal)return void(A[pI]=A[qo]()[pI]);if(A[pI])return;let e=null;for(const t of A.traversal[Ho]())if("next"===t.operation){e=t;break}if(!e||!e.ref)return void(A[pI]=A[qo]()[pI]);const t=A[To]();A[pI]=++t[pI];const i=t[EI](e.ref,A);if(!i)return;A=i[0]}}function rC(A,e){const t=A.assist;if(t){const A=t[wI]();A&&(e.title=A);const i=t.role.match($c);if(i){const A="heading",t=i[1];e.role=A,e["aria-level"]=t}}if("table"===A.layout)e.role="table";else if("row"===A.layout)e.role="row";else{const t=A[qo]();"row"===t.layout&&(e.role="TH"===t.assist?.role?"columnheader":"cell")}}function oC(A){if(!A.assist)return null;const e=A.assist;return e.speak&&""!==e.speak[yo]?e.speak[yo]:e.toolTip?e.toolTip[yo]:null}function IC(A){return vI.success({name:"div",attributes:{class:["xfaRich"],style:Object.create(null)},children:[{name:"span",attributes:{style:Object.create(null)},value:A}]})}function cC(A){const e=A[To]();null===e[bo].firstUnsplittable&&(e[bo].firstUnsplittable=A,e[bo].noLayoutFailure=!0)}function CC(A){const e=A[To]();e[bo].firstUnsplittable===A&&(e[bo].noLayoutFailure=!1)}function BC(A){if(A[bo])return!1;if(A[bo]=Object.create(null),"auto"===A.targetType)return!1;const e=A[To]();let t=null;if(A.target){if(t=e[EI](A.target,A[qo]()),!t)return!1;t=t[0]}const{currentPageArea:i,currentContentArea:a}=e[bo];if("pageArea"===A.targetType)return t instanceof JB||(t=null),A.startNew?(A[bo].target=t||i,!0):!(!t||t===i||(A[bo].target=t,0));t instanceof HC||(t=null);const s=t&&t[qo]();let n,g=s;if(A.startNew)if(t){const A=s.contentArea.children,e=A.indexOf(a),i=A.indexOf(t);-1!==e&&eA,i[bo].noLayoutFailure=!0;const n=e[wI](t);A[ho](n.html,n.bbox),i[bo].noLayoutFailure=a,e[Ko]=s}class QC extends Dc{constructor(A){super(zc,"appearanceFilter"),this.id=A.id||"",this.type=LI(A.type,["optional","required"]),this.use=A.use||"",this.usehref=A.usehref||""}}class lC extends dc{constructor(A){super(zc,"arc",!0),this.circular=xI({data:A.circular,defaultValue:0,validate:A=>1===A}),this.hand=LI(A.hand,["even","left","right"]),this.id=A.id||"",this.startAngle=UI({data:A.startAngle,defaultValue:0,validate:A=>!0}),this.sweepAngle=UI({data:A.sweepAngle,defaultValue:360,validate:A=>!0}),this.use=A.use||"",this.usehref=A.usehref||"",this.edge=null,this.fill=null}[wI](){const A=this.edge||new VC({}),e=A[bI](),t=Object.create(null);let i;"visible"===this.fill?.presence?Object.assign(t,this.fill[bI]()):t.fill="transparent",t.strokeWidth=Sc("visible"===A.presence?A.thickness:0),t.stroke=e.color;const a={xmlns:_c,style:{width:"100%",height:"100%",overflow:"visible"}};if(360===this.sweepAngle)i={name:"ellipse",attributes:{xmlns:_c,cx:"50%",cy:"50%",rx:"50%",ry:"50%",style:t}};else{const A=this.startAngle*Math.PI/180,e=this.sweepAngle*Math.PI/180,s=this.sweepAngle>180?1:0,[n,g,r,o]=[50*(1+Math.cos(A)),50*(1-Math.sin(A)),50*(1+Math.cos(A+e)),50*(1-Math.sin(A+e))];i={name:"path",attributes:{xmlns:_c,d:`M ${n} ${g} A 50 50 0 ${s} 0 ${r} ${o}`,vectorEffect:"non-scaling-stroke",style:t}},Object.assign(a,{viewBox:"0 0 100 100",preserveAspectRatio:"none"})}const s={name:"svg",children:[i],attributes:a};return iC(this[qo]()[qo]())?vI.success({name:"div",attributes:{style:{display:"inline",width:"100%",height:"100%"}},children:[s]}):(s.attributes.style.position="absolute",vI.success(s))}}class EC extends dc{constructor(A){super(zc,"area",!0),this.colSpan=xI({data:A.colSpan,defaultValue:1,validate:A=>A>=1||-1===A}),this.id=A.id||"",this.name=A.name||"",this.relevant=YI(A.relevant),this.use=A.use||"",this.usehref=A.usehref||"",this.x=JI(A.x,"0pt"),this.y=JI(A.y,"0pt"),this.desc=null,this.extras=null,this.area=new fc,this.draw=new fc,this.exObject=new fc,this.exclGroup=new fc,this.field=new fc,this.subform=new fc,this.subformSet=new fc}*[Yo](){yield*sC(this)}[tI](){return!0}[jo](){return!0}[ho](A,e){const[t,i,a,s]=e;this[bo].width=Math.max(this[bo].width,t+a),this[bo].height=Math.max(this[bo].height,i+s),this[bo].children.push(A)}[Go](){return this[bo].availableSpace}[wI](A){const e=Jc(this,"position"),t={style:e,id:this[kI],class:["xfaArea"]};Kc(this)&&t.class.push("xfaPrintOnly"),this.name&&(t.xfaName=this.name);const i=[];this[bo]={children:i,width:0,height:0,availableSpace:A};const a=this[lo]({filter:new Set(["area","draw","field","exclGroup","subform","subformSet"]),include:!0});if(!a.success)return a.isBreak()?a:(delete this[bo],vI.FAILURE);e.width=Sc(this[bo].width),e.height=Sc(this[bo].height);const s={name:"div",attributes:t,children:i},n=[this.x,this.y,this[bo].width,this[bo].height];return delete this[bo],vI.success(s,n)}}class uC extends dc{constructor(A){super(zc,"assist",!0),this.id=A.id||"",this.role=A.role||"",this.use=A.use||"",this.usehref=A.usehref||"",this.speak=null,this.toolTip=null}[wI](){return this.toolTip?.[yo]||null}}class dC extends dc{constructor(A){super(zc,"barcode",!0),this.charEncoding=MI({data:A.charEncoding?A.charEncoding.toLowerCase():"",defaultValue:"",validate:A=>["utf-8","big-five","fontspecific","gbk","gb-18030","gb-2312","ksc-5601","none","shift-jis","ucs-2","utf-16"].includes(A)||A.match(/iso-8859-\d{2}/)}),this.checksum=LI(A.checksum,["none","1mod10","1mod10_1mod11","2mod10","auto"]),this.dataColumnCount=xI({data:A.dataColumnCount,defaultValue:-1,validate:A=>A>=0}),this.dataLength=xI({data:A.dataLength,defaultValue:-1,validate:A=>A>=0}),this.dataPrep=LI(A.dataPrep,["none","flateCompress"]),this.dataRowCount=xI({data:A.dataRowCount,defaultValue:-1,validate:A=>A>=0}),this.endChar=A.endChar||"",this.errorCorrectionLevel=xI({data:A.errorCorrectionLevel,defaultValue:-1,validate:A=>A>=0&&A<=8}),this.id=A.id||"",this.moduleHeight=JI(A.moduleHeight,"5mm"),this.moduleWidth=JI(A.moduleWidth,"0.25mm"),this.printCheckDigit=xI({data:A.printCheckDigit,defaultValue:0,validate:A=>1===A}),this.rowColumnRatio=HI(A.rowColumnRatio),this.startChar=A.startChar||"",this.textLocation=LI(A.textLocation,["below","above","aboveEmbedded","belowEmbedded","none"]),this.truncate=xI({data:A.truncate,defaultValue:0,validate:A=>1===A}),this.type=LI(A.type?A.type.toLowerCase():"",["aztec","codabar","code2of5industrial","code2of5interleaved","code2of5matrix","code2of5standard","code3of9","code3of9extended","code11","code49","code93","code128","code128a","code128b","code128c","code128sscc","datamatrix","ean8","ean8add2","ean8add5","ean13","ean13add2","ean13add5","ean13pwcd","fim","logmars","maxicode","msi","pdf417","pdf417macro","plessey","postauscust2","postauscust3","postausreplypaid","postausstandard","postukrm4scc","postusdpbc","postusimb","postusstandard","postus5zip","qrcode","rfid","rss14","rss14expanded","rss14limited","rss14stacked","rss14stackedomni","rss14truncated","telepen","ucc128","ucc128random","ucc128sscc","upca","upcaadd2","upcaadd5","upcapwcd","upce","upceadd2","upceadd5","upcean2","upcean5","upsmaxicode"]),this.upsMode=LI(A.upsMode,["usCarrier","internationalCarrier","secureSymbol","standardSymbol"]),this.use=A.use||"",this.usehref=A.usehref||"",this.wideNarrowRatio=HI(A.wideNarrowRatio),this.encrypt=null,this.extras=null}}class fC extends dc{constructor(A){super(zc,"bind",!0),this.match=LI(A.match,["once","dataRef","global","none"]),this.ref=A.ref||"",this.picture=null}}class pC extends dc{constructor(A){super(zc,"bindItems"),this.connection=A.connection||"",this.labelRef=A.labelRef||"",this.ref=A.ref||"",this.valueRef=A.valueRef||""}}class mC extends dc{constructor(A){super(zc,"bookend"),this.id=A.id||"",this.leader=A.leader||"",this.trailer=A.trailer||"",this.use=A.use||"",this.usehref=A.usehref||""}}class yC extends kc{constructor(A){super(zc,"boolean"),this.id=A.id||"",this.name=A.name||"",this.use=A.use||"",this.usehref=A.usehref||""}[wI](A){return IC(1===this[yo]?"1":"0")}}class wC extends dc{constructor(A){super(zc,"border",!0),this.break=LI(A.break,["close","open"]),this.hand=LI(A.hand,["even","left","right"]),this.id=A.id||"",this.presence=LI(A.presence,["visible","hidden","inactive","invisible"]),this.relevant=YI(A.relevant),this.use=A.use||"",this.usehref=A.usehref||"",this.corner=new fc(4),this.edge=new fc(4),this.extras=null,this.fill=null,this.margin=null}[Lo](){if(!this[bo]){const A=this.edge.children.slice();if(A.length<4){const e=A.at(-1)||new VC({});for(let t=A.length;t<4;t++)A.push(e)}const e=A.map((A=>A.thickness)),t=[0,0,0,0];this.margin&&(t[0]=this.margin.topInset,t[1]=this.margin.rightInset,t[2]=this.margin.bottomInset,t[3]=this.margin.leftInset),this[bo]={widths:e,insets:t,edges:A}}return this[bo]}[bI](){const{edges:A}=this[Lo](),e=A.map((A=>{const e=A[bI]();return e.color||="#000000",e})),t=Object.create(null);if(this.margin&&Object.assign(t,this.margin[bI]()),"visible"===this.fill?.presence&&Object.assign(t,this.fill[bI]()),this.corner.children.some((A=>0!==A.radius))){const A=this.corner.children.map((A=>A[bI]()));if(2===A.length||3===A.length){const e=A.at(-1);for(let t=A.length;t<4;t++)A.push(e)}t.borderRadius=A.map((A=>A.radius)).join(" ")}switch(this.presence){case"invisible":case"hidden":t.borderStyle="";break;case"inactive":t.borderStyle="none";break;default:t.borderStyle=e.map((A=>A.style)).join(" ")}return t.borderWidth=e.map((A=>A.width)).join(" "),t.borderColor=e.map((A=>A.color)).join(" "),t}}class DC extends dc{constructor(A){super(zc,"break",!0),this.after=LI(A.after,["auto","contentArea","pageArea","pageEven","pageOdd"]),this.afterTarget=A.afterTarget||"",this.before=LI(A.before,["auto","contentArea","pageArea","pageEven","pageOdd"]),this.beforeTarget=A.beforeTarget||"",this.bookendLeader=A.bookendLeader||"",this.bookendTrailer=A.bookendTrailer||"",this.id=A.id||"",this.overflowLeader=A.overflowLeader||"",this.overflowTarget=A.overflowTarget||"",this.overflowTrailer=A.overflowTrailer||"",this.startNew=xI({data:A.startNew,defaultValue:0,validate:A=>1===A}),this.use=A.use||"",this.usehref=A.usehref||"",this.extras=null}}class bC extends dc{constructor(A){super(zc,"breakAfter",!0),this.id=A.id||"",this.leader=A.leader||"",this.startNew=xI({data:A.startNew,defaultValue:0,validate:A=>1===A}),this.target=A.target||"",this.targetType=LI(A.targetType,["auto","contentArea","pageArea"]),this.trailer=A.trailer||"",this.use=A.use||"",this.usehref=A.usehref||"",this.script=null}}class kC extends dc{constructor(A){super(zc,"breakBefore",!0),this.id=A.id||"",this.leader=A.leader||"",this.startNew=xI({data:A.startNew,defaultValue:0,validate:A=>1===A}),this.target=A.target||"",this.targetType=LI(A.targetType,["auto","contentArea","pageArea"]),this.trailer=A.trailer||"",this.use=A.use||"",this.usehref=A.usehref||"",this.script=null}[wI](A){return this[bo]={},vI.FAILURE}}class FC extends dc{constructor(A){super(zc,"button",!0),this.highlight=LI(A.highlight,["inverted","none","outline","push"]),this.id=A.id||"",this.use=A.use||"",this.usehref=A.usehref||"",this.extras=null}[wI](A){const e=this[qo]()[qo](),t={name:"button",attributes:{id:this[kI],class:["xfaButton"],style:{}},children:[]};for(const A of e.event.children){if("click"!==A.activity||!A.script)continue;const e=_A(A.script[yo]);if(!e)continue;const i=Wc(e.url);i&&t.children.push({name:"a",attributes:{id:"link"+this[kI],href:i,newWindow:e.newWindow,class:["xfaLink"],style:{}},children:[]})}return vI.success(t)}}class SC extends dc{constructor(A){super(zc,"calculate",!0),this.id=A.id||"",this.override=LI(A.override,["disabled","error","ignore","warning"]),this.use=A.use||"",this.usehref=A.usehref||"",this.extras=null,this.message=null,this.script=null}}class RC extends dc{constructor(A){super(zc,"caption",!0),this.id=A.id||"",this.placement=LI(A.placement,["left","bottom","inline","right","top"]),this.presence=LI(A.presence,["visible","hidden","inactive","invisible"]),this.reserve=Math.ceil(JI(A.reserve)),this.use=A.use||"",this.usehref=A.usehref||"",this.extras=null,this.font=null,this.margin=null,this.para=null,this.value=null}[fI](A){aC(this,A)}[Lo](A){if(!this[bo]){let{width:e,height:t}=A;switch(this.placement){case"left":case"right":case"inline":e=this.reserve<=0?e:this.reserve;break;case"top":case"bottom":t=this.reserve<=0?t:this.reserve}this[bo]=xc(this,{width:e,height:t})}return this[bo]}[wI](A){if(!this.value)return vI.EMPTY;this[BI]();const e=this.value[wI](A).html;if(!e)return this[CI](),vI.EMPTY;const t=this.reserve;if(this.reserve<=0){const{w:e,h:t}=this[Lo](A);switch(this.placement){case"left":case"right":case"inline":this.reserve=e;break;case"top":case"bottom":this.reserve=t}}const i=[];"string"==typeof e?i.push({name:"#text",value:e}):i.push(e);const a=Jc(this,"font","margin","visibility");switch(this.placement){case"left":case"right":this.reserve>0&&(a.width=Sc(this.reserve));break;case"top":case"bottom":this.reserve>0&&(a.height=Sc(this.reserve))}return Tc(this,null,e),this[CI](),this.reserve=t,vI.success({name:"div",attributes:{style:a,class:["xfaCaption"]},children:i})}}class GC extends Dc{constructor(A){super(zc,"certificate"),this.id=A.id||"",this.name=A.name||"",this.use=A.use||"",this.usehref=A.usehref||""}}class NC extends dc{constructor(A){super(zc,"certificates",!0),this.credentialServerPolicy=LI(A.credentialServerPolicy,["optional","required"]),this.id=A.id||"",this.url=A.url||"",this.urlPolicy=A.urlPolicy||"",this.use=A.use||"",this.usehref=A.usehref||"",this.encryption=null,this.issuers=null,this.keyUsage=null,this.oids=null,this.signing=null,this.subjectDNs=null}}class xC extends dc{constructor(A){super(zc,"checkButton",!0),this.id=A.id||"",this.mark=LI(A.mark,["default","check","circle","cross","diamond","square","star"]),this.shape=LI(A.shape,["square","round"]),this.size=JI(A.size,"10pt"),this.use=A.use||"",this.usehref=A.usehref||"",this.border=null,this.extras=null,this.margin=null}[wI](A){const e=Jc("margin"),t=Sc(this.size);let i,a,s;e.width=e.height=t;const n=this[qo]()[qo](),g=n.items.children.length&&n.items.children[0][wI]().html||[],r={on:(void 0!==g[0]?g[0]:"on").toString(),off:(void 0!==g[1]?g[1]:"off").toString()},o=(n.value?.[mI]()||"off")===r.on||void 0,I=n[Ko](),c=n[kI];let C;I instanceof nB?(s=I[kI],i="radio",a="xfaRadio",C=I[wo]?.[kI]||I[kI]):(i="checkbox",a="xfaCheckbox",C=n[wo]?.[kI]||n[kI]);const B={name:"input",attributes:{class:[a],style:e,fieldId:c,dataId:C,type:i,checked:o,xfaOn:r.on,xfaOff:r.off,"aria-label":oC(n),"aria-required":!1}};return s&&(B.attributes.name=s),nC(n)&&(B.attributes["aria-required"]=!0,B.attributes.required=!0),vI.success({name:"label",attributes:{class:["xfaLabel"]},children:[B]})}}class UC extends dc{constructor(A){super(zc,"choiceList",!0),this.commitOn=LI(A.commitOn,["select","exit"]),this.id=A.id||"",this.open=LI(A.open,["userControl","always","multiSelect","onEntry"]),this.textEntry=xI({data:A.textEntry,defaultValue:0,validate:A=>1===A}),this.use=A.use||"",this.usehref=A.usehref||"",this.border=null,this.extras=null,this.margin=null}[wI](A){const e=Jc(this,"border","margin"),t=this[qo]()[qo](),i={fontSize:`calc(${t.font?.size||10}px * var(--scale-factor))`},a=[];if(t.items.children.length>0){const A=t.items;let e=0,s=0;2===A.children.length&&(e=A.children[0].save,s=1-e);const n=A.children[e][wI]().html,g=A.children[s][wI]().html;let r=!1;const o=t.value?.[mI]()||"";for(let A=0,e=n.length;AMath.min(Math.max(0,parseInt(A.trim(),10)),255))).map((A=>isNaN(A)?0:A));return s.length<3||([t,i,a]=s),{r:t,g:i,b:a}}(A.value):"",this.extras=null}[Wo](){return!1}[bI](){return this.value?z.makeHexColor(this.value.r,this.value.g,this.value.b):null}}class LC extends dc{constructor(A){super(zc,"comb"),this.id=A.id||"",this.numberOfCells=xI({data:A.numberOfCells,defaultValue:0,validate:A=>A>=0}),this.use=A.use||"",this.usehref=A.usehref||""}}class JC extends dc{constructor(A){super(zc,"connect",!0),this.connection=A.connection||"",this.id=A.id||"",this.ref=A.ref||"",this.usage=LI(A.usage,["exportAndImport","exportOnly","importOnly"]),this.use=A.use||"",this.usehref=A.usehref||"",this.picture=null}}class HC extends dc{constructor(A){super(zc,"contentArea",!0),this.h=JI(A.h),this.id=A.id||"",this.name=A.name||"",this.relevant=YI(A.relevant),this.use=A.use||"",this.usehref=A.usehref||"",this.w=JI(A.w),this.x=JI(A.x,"0pt"),this.y=JI(A.y,"0pt"),this.desc=null,this.extras=null}[wI](A){const e={left:Sc(this.x),top:Sc(this.y),width:Sc(this.w),height:Sc(this.h)},t=["xfaContentarea"];return Kc(this)&&t.push("xfaPrintOnly"),vI.success({name:"div",children:[],attributes:{style:e,class:t,id:this[kI]}})}}class YC extends dc{constructor(A){super(zc,"corner",!0),this.id=A.id||"",this.inverted=xI({data:A.inverted,defaultValue:0,validate:A=>1===A}),this.join=LI(A.join,["square","round"]),this.presence=LI(A.presence,["visible","hidden","inactive","invisible"]),this.radius=JI(A.radius),this.stroke=LI(A.stroke,["solid","dashDot","dashDotDot","dashed","dotted","embossed","etched","lowered","raised"]),this.thickness=JI(A.thickness,"0.5pt"),this.use=A.use||"",this.usehref=A.usehref||"",this.color=null,this.extras=null}[bI](){const A=Jc(this,"visibility");return A.radius=Sc("square"===this.join?0:this.radius),A}}class vC extends yc{constructor(A){super(zc,"date"),this.id=A.id||"",this.name=A.name||"",this.use=A.use||"",this.usehref=A.usehref||""}[ko](){const A=this[yo].trim();this[yo]=A?new Date(A):null}[wI](A){return IC(this[yo]?this[yo].toString():"")}}class KC extends yc{constructor(A){super(zc,"dateTime"),this.id=A.id||"",this.name=A.name||"",this.use=A.use||"",this.usehref=A.usehref||""}[ko](){const A=this[yo].trim();this[yo]=A?new Date(A):null}[wI](A){return IC(this[yo]?this[yo].toString():"")}}class qC extends dc{constructor(A){super(zc,"dateTimeEdit",!0),this.hScrollPolicy=LI(A.hScrollPolicy,["auto","off","on"]),this.id=A.id||"",this.picker=LI(A.picker,["host","none"]),this.use=A.use||"",this.usehref=A.usehref||"",this.border=null,this.comb=null,this.extras=null,this.margin=null}[wI](A){const e=Jc(this,"border","font","margin"),t=this[qo]()[qo](),i={name:"input",attributes:{type:"text",fieldId:t[kI],dataId:t[wo]?.[kI]||t[kI],class:["xfaTextfield"],style:e,"aria-label":oC(t),"aria-required":!1}};return nC(t)&&(i.attributes["aria-required"]=!0,i.attributes.required=!0),vI.success({name:"label",attributes:{class:["xfaLabel"]},children:[i]})}}class TC extends yc{constructor(A){super(zc,"decimal"),this.fracDigits=xI({data:A.fracDigits,defaultValue:2,validate:A=>!0}),this.id=A.id||"",this.leadDigits=xI({data:A.leadDigits,defaultValue:-1,validate:A=>!0}),this.name=A.name||"",this.use=A.use||"",this.usehref=A.usehref||""}[ko](){const A=parseFloat(this[yo].trim());this[yo]=isNaN(A)?null:A}[wI](A){return IC(null!==this[yo]?this[yo].toString():"")}}class PC extends dc{constructor(A){super(zc,"defaultUi",!0),this.id=A.id||"",this.use=A.use||"",this.usehref=A.usehref||"",this.extras=null}}class WC extends dc{constructor(A){super(zc,"desc",!0),this.id=A.id||"",this.use=A.use||"",this.usehref=A.usehref||"",this.boolean=new fc,this.date=new fc,this.dateTime=new fc,this.decimal=new fc,this.exData=new fc,this.float=new fc,this.image=new fc,this.integer=new fc,this.text=new fc,this.time=new fc}}class ZC extends wc{constructor(A){super(zc,"digestMethod",["","SHA1","SHA256","SHA512","RIPEMD160"]),this.id=A.id||"",this.use=A.use||"",this.usehref=A.usehref||""}}class OC extends dc{constructor(A){super(zc,"digestMethods",!0),this.id=A.id||"",this.type=LI(A.type,["optional","required"]),this.use=A.use||"",this.usehref=A.usehref||"",this.digestMethod=new fc}}class XC extends dc{constructor(A){super(zc,"draw",!0),this.anchorType=LI(A.anchorType,["topLeft","bottomCenter","bottomLeft","bottomRight","middleCenter","middleLeft","middleRight","topCenter","topRight"]),this.colSpan=xI({data:A.colSpan,defaultValue:1,validate:A=>A>=1||-1===A}),this.h=A.h?JI(A.h):"",this.hAlign=LI(A.hAlign,["left","center","justify","justifyAll","radix","right"]),this.id=A.id||"",this.locale=A.locale||"",this.maxH=JI(A.maxH,"0pt"),this.maxW=JI(A.maxW,"0pt"),this.minH=JI(A.minH,"0pt"),this.minW=JI(A.minW,"0pt"),this.name=A.name||"",this.presence=LI(A.presence,["visible","hidden","inactive","invisible"]),this.relevant=YI(A.relevant),this.rotate=xI({data:A.rotate,defaultValue:0,validate:A=>A%90==0}),this.use=A.use||"",this.usehref=A.usehref||"",this.w=A.w?JI(A.w):"",this.x=JI(A.x,"0pt"),this.y=JI(A.y,"0pt"),this.assist=null,this.border=null,this.caption=null,this.desc=null,this.extras=null,this.font=null,this.keep=null,this.margin=null,this.para=null,this.traversal=null,this.ui=null,this.value=null,this.setProperty=new fc}[fI](A){aC(this,A)}[wI](A){if(gC(this),"hidden"===this.presence||"inactive"===this.presence)return vI.EMPTY;Mc(this),this[BI]();const e=this.w,t=this.h,{w:i,h:a,isBroken:s}=xc(this,A);if(i&&""===this.w){if(s&&this[Ko]()[eI]())return this[CI](),vI.FAILURE;this.w=i}if(a&&""===this.h&&(this.h=a),cC(this),!jc(this,A))return this.w=e,this.h=t,this[CI](),vI.FAILURE;CC(this);const n=Jc(this,"font","hAlign","dimensions","position","presence","rotate","anchorType","border","margin");Gc(this,n),n.margin&&(n.padding=n.margin,delete n.margin);const g=["xfaDraw"];this.font&&g.push("xfaFont"),Kc(this)&&g.push("xfaPrintOnly");const r={style:n,id:this[kI],class:g};this.name&&(r.xfaName=this.name);const o={name:"div",attributes:r,children:[]};rC(this,r);const I=Uc(this,o,A),c=this.value?this.value[wI](A).html:null;return null===c?(this.w=e,this.h=t,this[CI](),vI.success(Hc(this,o),I)):(o.children.push(c),Tc(this,n,c),this.w=e,this.h=t,this[CI](),vI.success(Hc(this,o),I))}}class VC extends dc{constructor(A){super(zc,"edge",!0),this.cap=LI(A.cap,["square","butt","round"]),this.id=A.id||"",this.presence=LI(A.presence,["visible","hidden","inactive","invisible"]),this.stroke=LI(A.stroke,["solid","dashDot","dashDotDot","dashed","dotted","embossed","etched","lowered","raised"]),this.thickness=JI(A.thickness,"0.5pt"),this.use=A.use||"",this.usehref=A.usehref||"",this.color=null,this.extras=null}[bI](){const A=Jc(this,"visibility");if(Object.assign(A,{linecap:this.cap,width:Sc(this.thickness),color:this.color?this.color[bI]():"#000000",style:""}),"visible"!==this.presence)A.style="none";else switch(this.stroke){case"solid":A.style="solid";break;case"dashDot":case"dashDotDot":case"dashed":A.style="dashed";break;case"dotted":A.style="dotted";break;case"embossed":A.style="ridge";break;case"etched":A.style="groove";break;case"lowered":A.style="inset";break;case"raised":A.style="outset"}return A}}class jC extends wc{constructor(A){super(zc,"encoding",["adbe.x509.rsa_sha1","adbe.pkcs7.detached","adbe.pkcs7.sha1"]),this.id=A.id||"",this.use=A.use||"",this.usehref=A.usehref||""}}class zC extends dc{constructor(A){super(zc,"encodings",!0),this.id=A.id||"",this.type=LI(A.type,["optional","required"]),this.use=A.use||"",this.usehref=A.usehref||"",this.encoding=new fc}}class _C extends dc{constructor(A){super(zc,"encrypt",!0),this.id=A.id||"",this.use=A.use||"",this.usehref=A.usehref||"",this.certificate=null}}class $C extends dc{constructor(A){super(zc,"encryptData",!0),this.id=A.id||"",this.operation=LI(A.operation,["encrypt","decrypt"]),this.target=A.target||"",this.use=A.use||"",this.usehref=A.usehref||"",this.filter=null,this.manifest=null}}class AB extends dc{constructor(A){super(zc,"encryption",!0),this.id=A.id||"",this.type=LI(A.type,["optional","required"]),this.use=A.use||"",this.usehref=A.usehref||"",this.certificate=new fc}}class eB extends wc{constructor(A){super(zc,"encryptionMethod",["","AES256-CBC","TRIPLEDES-CBC","AES128-CBC","AES192-CBC"]),this.id=A.id||"",this.use=A.use||"",this.usehref=A.usehref||""}}class tB extends dc{constructor(A){super(zc,"encryptionMethods",!0),this.id=A.id||"",this.type=LI(A.type,["optional","required"]),this.use=A.use||"",this.usehref=A.usehref||"",this.encryptionMethod=new fc}}class iB extends dc{constructor(A){super(zc,"event",!0),this.activity=LI(A.activity,["click","change","docClose","docReady","enter","exit","full","indexChange","initialize","mouseDown","mouseEnter","mouseExit","mouseUp","postExecute","postOpen","postPrint","postSave","postSign","postSubmit","preExecute","preOpen","prePrint","preSave","preSign","preSubmit","ready","validationState"]),this.id=A.id||"",this.listen=LI(A.listen,["refOnly","refAndDescendents"]),this.name=A.name||"",this.ref=A.ref||"",this.use=A.use||"",this.usehref=A.usehref||"",this.extras=null,this.encryptData=null,this.execute=null,this.script=null,this.signData=null,this.submit=null}}class aB extends yc{constructor(A){super(zc,"exData"),this.contentType=A.contentType||"",this.href=A.href||"",this.id=A.id||"",this.maxLength=xI({data:A.maxLength,defaultValue:-1,validate:A=>A>=-1}),this.name=A.name||"",this.rid=A.rid||"",this.transferEncoding=LI(A.transferEncoding,["none","base64","package"]),this.use=A.use||"",this.usehref=A.usehref||""}[Vo](){return"text/html"===this.contentType}[rI](A){return("text/html"===this.contentType&&A[sI]===SI.xhtml.id||"text/xml"===this.contentType)&&(this[yo]=A,!0)}[wI](A){return"text/html"===this.contentType&&this[yo]?this[yo][wI](A):vI.EMPTY}}class sB extends dc{constructor(A){super(zc,"exObject",!0),this.archive=A.archive||"",this.classId=A.classId||"",this.codeBase=A.codeBase||"",this.codeType=A.codeType||"",this.id=A.id||"",this.name=A.name||"",this.use=A.use||"",this.usehref=A.usehref||"",this.extras=null,this.boolean=new fc,this.date=new fc,this.dateTime=new fc,this.decimal=new fc,this.exData=new fc,this.exObject=new fc,this.float=new fc,this.image=new fc,this.integer=new fc,this.text=new fc,this.time=new fc}}class nB extends dc{constructor(A){super(zc,"exclGroup",!0),this.access=LI(A.access,["open","nonInteractive","protected","readOnly"]),this.accessKey=A.accessKey||"",this.anchorType=LI(A.anchorType,["topLeft","bottomCenter","bottomLeft","bottomRight","middleCenter","middleLeft","middleRight","topCenter","topRight"]),this.colSpan=xI({data:A.colSpan,defaultValue:1,validate:A=>A>=1||-1===A}),this.h=A.h?JI(A.h):"",this.hAlign=LI(A.hAlign,["left","center","justify","justifyAll","radix","right"]),this.id=A.id||"",this.layout=LI(A.layout,["position","lr-tb","rl-row","rl-tb","row","table","tb"]),this.maxH=JI(A.maxH,"0pt"),this.maxW=JI(A.maxW,"0pt"),this.minH=JI(A.minH,"0pt"),this.minW=JI(A.minW,"0pt"),this.name=A.name||"",this.presence=LI(A.presence,["visible","hidden","inactive","invisible"]),this.relevant=YI(A.relevant),this.use=A.use||"",this.usehref=A.usehref||"",this.w=A.w?JI(A.w):"",this.x=JI(A.x,"0pt"),this.y=JI(A.y,"0pt"),this.assist=null,this.bind=null,this.border=null,this.calculate=null,this.caption=null,this.desc=null,this.extras=null,this.margin=null,this.para=null,this.traversal=null,this.validate=null,this.connect=new fc,this.event=new fc,this.field=new fc,this.setProperty=new fc}[jo](){return!0}[Wo](){return!0}[fI](A){for(const e of this.field.children){if(!e.value){const A=new uh({});e[Qo](A),e.value=A}e.value[fI](A)}}[eI](){return this.layout.endsWith("-tb")&&0===this[bo].attempt&&this[bo].numberInLine>0||this[qo]()[eI]()}[AI](){const A=this[Ko]();return!!A[AI]()&&(void 0!==this[bo]._isSplittable?this[bo]._isSplittable:"position"===this.layout||this.layout.includes("row")?(this[bo]._isSplittable=!1,!1):!(A.layout?.endsWith("-tb")&&0!==A[bo].numberInLine||(this[bo]._isSplittable=!0,0)))}[Fo](){return Oc(this)}[ho](A,e){Xc(this,A,e)}[Go](){return Vc(this)}[wI](A){if(gC(this),"hidden"===this.presence||"inactive"===this.presence||0===this.h||0===this.w)return vI.EMPTY;Mc(this);const e=[],t={id:this[kI],class:[]};vc(this,t.class),this[bo]||(this[bo]=Object.create(null)),Object.assign(this[bo],{children:e,attributes:t,attempt:0,line:null,numberInLine:0,availableSpace:{width:Math.min(this.w||1/0,A.width),height:Math.min(this.h||1/0,A.height)},width:0,height:0,prevHeight:0,currentWidth:0});const i=this[AI]();if(i||cC(this),!jc(this,A))return vI.FAILURE;const a=new Set(["field"]);if(this.layout.includes("row")){const A=this[Ko]().columnWidths;Array.isArray(A)&&A.length>0&&(this[bo].columnWidths=A,this[bo].currentColumn=0)}const s=Jc(this,"anchorType","dimensions","position","presence","border","margin","hAlign"),n=["xfaExclgroup"],g=Lc(this);g&&n.push(g),Kc(this)&&n.push("xfaPrintOnly"),t.style=s,t.class=n,this.name&&(t.xfaName=this.name),this[BI]();const r="lr-tb"===this.layout||"rl-tb"===this.layout,o=r?2:1;for(;this[bo].attemptA>=1||-1===A}),this.h=A.h?JI(A.h):"",this.hAlign=LI(A.hAlign,["left","center","justify","justifyAll","radix","right"]),this.id=A.id||"",this.locale=A.locale||"",this.maxH=JI(A.maxH,"0pt"),this.maxW=JI(A.maxW,"0pt"),this.minH=JI(A.minH,"0pt"),this.minW=JI(A.minW,"0pt"),this.name=A.name||"",this.presence=LI(A.presence,["visible","hidden","inactive","invisible"]),this.relevant=YI(A.relevant),this.rotate=xI({data:A.rotate,defaultValue:0,validate:A=>A%90==0}),this.use=A.use||"",this.usehref=A.usehref||"",this.w=A.w?JI(A.w):"",this.x=JI(A.x,"0pt"),this.y=JI(A.y,"0pt"),this.assist=null,this.bind=null,this.border=null,this.calculate=null,this.caption=null,this.desc=null,this.extras=null,this.font=null,this.format=null,this.items=new fc(2),this.keep=null,this.margin=null,this.para=null,this.traversal=null,this.ui=null,this.validate=null,this.value=null,this.bindItems=new fc,this.connect=new fc,this.event=new fc,this.setProperty=new fc}[jo](){return!0}[fI](A){aC(this,A)}[wI](A){if(gC(this),!this.ui){let A;switch(this.ui=new lh({}),this.ui[Po]=this[Po],this[Qo](this.ui),this.items.children.length){case 0:A=new Ih({}),this.ui.textEdit=A;break;case 1:A=new xC({}),this.ui.checkButton=A;break;case 2:A=new UC({}),this.ui.choiceList=A}this.ui[Qo](A)}if(!this.ui||"hidden"===this.presence||"inactive"===this.presence||0===this.h||0===this.w)return vI.EMPTY;this.caption&&delete this.caption[bo],this[BI]();const e=this.caption?this.caption[wI](A).html:null,t=this.w,i=this.h;let a=0,s=0;this.margin&&(a=this.margin.leftInset+this.margin.rightInset,s=this.margin.topInset+this.margin.bottomInset);let n=null;if(""===this.w||""===this.h){let e=null,t=null,i=0,g=0;if(this.ui.checkButton)i=g=this.ui.checkButton.size;else{const{w:e,h:t}=xc(this,A);null!==e?(i=e,g=t):g=function(A,e=!1){let t=null;if(A){const e=NI(A.typeface),i=A[Po].fontFinder.find(e);t=qI(A,i)}if(!t)return{lineHeight:12,lineGap:2,lineNoGap:10};const i=A.size||10,a=t.lineHeight?Math.max(e?0:1.2,t.lineHeight):1.2,s=void 0===t.lineGap?.2:t.lineGap;return{lineHeight:a*i,lineGap:s*i,lineNoGap:Math.max(1,a-s)*i}}(this.font,!0).lineNoGap}if(n=tC(this.ui[Lo]()),i+=n.w,g+=n.h,this.caption){const{w:a,h:s,isBroken:n}=this.caption[Lo](A);if(n&&this[Ko]()[eI]())return this[CI](),vI.FAILURE;switch(e=a,t=s,this.caption.placement){case"left":case"right":case"inline":e+=i;break;case"top":case"bottom":t+=g}}else e=i,t=g;e&&""===this.w&&(e+=a,this.w=Math.min(this.maxW<=0?1/0:this.maxW,this.minW+1A>=1&&A<=5}),this.appearanceFilter=null,this.certificates=null,this.digestMethods=null,this.encodings=null,this.encryptionMethods=null,this.handler=null,this.lockDocument=null,this.mdp=null,this.reasons=null,this.timeStamp=null}}class CB extends yc{constructor(A){super(zc,"float"),this.id=A.id||"",this.name=A.name||"",this.use=A.use||"",this.usehref=A.usehref||""}[ko](){const A=parseFloat(this[yo].trim());this[yo]=isNaN(A)?null:A}[wI](A){return IC(null!==this[yo]?this[yo].toString():"")}}class BB extends dc{constructor(A){super(zc,"font",!0),this.baselineShift=JI(A.baselineShift),this.fontHorizontalScale=UI({data:A.fontHorizontalScale,defaultValue:100,validate:A=>A>=0}),this.fontVerticalScale=UI({data:A.fontVerticalScale,defaultValue:100,validate:A=>A>=0}),this.id=A.id||"",this.kerningMode=LI(A.kerningMode,["none","pair"]),this.letterSpacing=JI(A.letterSpacing,"0"),this.lineThrough=xI({data:A.lineThrough,defaultValue:0,validate:A=>1===A||2===A}),this.lineThroughPeriod=LI(A.lineThroughPeriod,["all","word"]),this.overline=xI({data:A.overline,defaultValue:0,validate:A=>1===A||2===A}),this.overlinePeriod=LI(A.overlinePeriod,["all","word"]),this.posture=LI(A.posture,["normal","italic"]),this.size=JI(A.size,"10pt"),this.typeface=A.typeface||"Courier",this.underline=xI({data:A.underline,defaultValue:0,validate:A=>1===A||2===A}),this.underlinePeriod=LI(A.underlinePeriod,["all","word"]),this.use=A.use||"",this.usehref=A.usehref||"",this.weight=LI(A.weight,["normal","bold"]),this.extras=null,this.fill=null}[Eo](A){super[Eo](A),this[Po].usedTypefaces.add(this.typeface)}[bI](){const A=Jc(this,"fill"),e=A.color;return e&&("#000000"===e?delete A.color:e.startsWith("#")||(A.background=e,A.backgroundClip="text",A.color="transparent")),this.baselineShift&&(A.verticalAlign=Sc(this.baselineShift)),A.fontKerning="none"===this.kerningMode?"none":"normal",A.letterSpacing=Sc(this.letterSpacing),0!==this.lineThrough&&(A.textDecoration="line-through",2===this.lineThrough&&(A.textDecorationStyle="double")),0!==this.overline&&(A.textDecoration="overline",2===this.overline&&(A.textDecorationStyle="double")),A.fontStyle=this.posture,A.fontSize=Sc(.99*this.size),Pc(this,this,this[Po].fontFinder,A),0!==this.underline&&(A.textDecoration="underline",2===this.underline&&(A.textDecorationStyle="double")),A.fontWeight=this.weight,A}}class hB extends dc{constructor(A){super(zc,"format",!0),this.id=A.id||"",this.use=A.use||"",this.usehref=A.usehref||"",this.extras=null,this.picture=null}}class QB extends Dc{constructor(A){super(zc,"handler"),this.id=A.id||"",this.type=LI(A.type,["optional","required"]),this.use=A.use||"",this.usehref=A.usehref||""}}class lB extends dc{constructor(A){super(zc,"hyphenation"),this.excludeAllCaps=xI({data:A.excludeAllCaps,defaultValue:0,validate:A=>1===A}),this.excludeInitialCap=xI({data:A.excludeInitialCap,defaultValue:0,validate:A=>1===A}),this.hyphenate=xI({data:A.hyphenate,defaultValue:0,validate:A=>1===A}),this.id=A.id||"",this.pushCharacterCount=xI({data:A.pushCharacterCount,defaultValue:3,validate:A=>A>=0}),this.remainCharacterCount=xI({data:A.remainCharacterCount,defaultValue:3,validate:A=>A>=0}),this.use=A.use||"",this.usehref=A.usehref||"",this.wordCharacterCount=xI({data:A.wordCharacterCount,defaultValue:7,validate:A=>A>=0})}}class EB extends Dc{constructor(A){super(zc,"image"),this.aspect=LI(A.aspect,["fit","actual","height","none","width"]),this.contentType=A.contentType||"",this.href=A.href||"",this.id=A.id||"",this.name=A.name||"",this.transferEncoding=LI(A.transferEncoding,["base64","none","package"]),this.use=A.use||"",this.usehref=A.usehref||""}[wI](){if(this.contentType&&!AC.has(this.contentType.toLowerCase()))return vI.EMPTY;let A=this[Po].images&&this[Po].images.get(this.href);if(!A&&(this.href||!this[yo]))return vI.EMPTY;if(A||"base64"!==this.transferEncoding||(A=Z(atob(this[yo]))),!A)return vI.EMPTY;if(!this.contentType){for(const[e,t]of eC)if(A.length>e.length&&e.every(((e,t)=>e===A[t]))){this.contentType=t;break}if(!this.contentType)return vI.EMPTY}const e=new Blob([A],{type:this.contentType});let t;switch(this.aspect){case"fit":case"actual":break;case"height":t={height:"100%",objectFit:"fill"};break;case"none":t={width:"100%",height:"100%",objectFit:"fill"};break;case"width":t={width:"100%",objectFit:"fill"}}const i=this[qo]();return vI.success({name:"img",attributes:{class:["xfaImage"],style:t,src:URL.createObjectURL(e),alt:i?oC(i[qo]()):null}})}}class uB extends dc{constructor(A){super(zc,"imageEdit",!0),this.data=LI(A.data,["link","embed"]),this.id=A.id||"",this.use=A.use||"",this.usehref=A.usehref||"",this.border=null,this.extras=null,this.margin=null}[wI](A){return"embed"===this.data?vI.success({name:"div",children:[],attributes:{}}):vI.EMPTY}}class dB extends yc{constructor(A){super(zc,"integer"),this.id=A.id||"",this.name=A.name||"",this.use=A.use||"",this.usehref=A.usehref||""}[ko](){const A=parseInt(this[yo].trim(),10);this[yo]=isNaN(A)?null:A}[wI](A){return IC(null!==this[yo]?this[yo].toString():"")}}class fB extends dc{constructor(A){super(zc,"issuers",!0),this.id=A.id||"",this.type=LI(A.type,["optional","required"]),this.use=A.use||"",this.usehref=A.usehref||"",this.certificate=new fc}}class pB extends dc{constructor(A){super(zc,"items",!0),this.id=A.id||"",this.name=A.name||"",this.presence=LI(A.presence,["visible","hidden","inactive","invisible"]),this.ref=A.ref||"",this.save=xI({data:A.save,defaultValue:0,validate:A=>1===A}),this.use=A.use||"",this.usehref=A.usehref||"",this.boolean=new fc,this.date=new fc,this.dateTime=new fc,this.decimal=new fc,this.exData=new fc,this.float=new fc,this.image=new fc,this.integer=new fc,this.text=new fc,this.time=new fc}[wI](){const A=[];for(const e of this[Ho]())A.push(e[mI]());return vI.success(A)}}class mB extends dc{constructor(A){super(zc,"keep",!0),this.id=A.id||"";const e=["none","contentArea","pageArea"];this.intact=LI(A.intact,e),this.next=LI(A.next,e),this.previous=LI(A.previous,e),this.use=A.use||"",this.usehref=A.usehref||"",this.extras=null}}class yB extends dc{constructor(A){super(zc,"keyUsage");const e=["","yes","no"];this.crlSign=LI(A.crlSign,e),this.dataEncipherment=LI(A.dataEncipherment,e),this.decipherOnly=LI(A.decipherOnly,e),this.digitalSignature=LI(A.digitalSignature,e),this.encipherOnly=LI(A.encipherOnly,e),this.id=A.id||"",this.keyAgreement=LI(A.keyAgreement,e),this.keyCertSign=LI(A.keyCertSign,e),this.keyEncipherment=LI(A.keyEncipherment,e),this.nonRepudiation=LI(A.nonRepudiation,e),this.type=LI(A.type,["optional","required"]),this.use=A.use||"",this.usehref=A.usehref||""}}class wB extends dc{constructor(A){super(zc,"line",!0),this.hand=LI(A.hand,["even","left","right"]),this.id=A.id||"",this.slope=LI(A.slope,["\\","/"]),this.use=A.use||"",this.usehref=A.usehref||"",this.edge=null}[wI](){const A=this[qo]()[qo](),e=this.edge||new VC({}),t=e[bI](),i=Object.create(null),a="visible"===e.presence?e.thickness:0;let s,n,g,r;i.strokeWidth=Sc(a),i.stroke=t.color;let o="100%",I="100%";A.w<=a?([s,n,g,r]=["50%",0,"50%","100%"],o=i.strokeWidth):A.h<=a?([s,n,g,r]=[0,"50%","100%","50%"],I=i.strokeWidth):"\\"===this.slope?[s,n,g,r]=[0,0,"100%","100%"]:[s,n,g,r]=[0,"100%","100%",0];const c={name:"svg",children:[{name:"line",attributes:{xmlns:_c,x1:s,y1:n,x2:g,y2:r,style:i}}],attributes:{xmlns:_c,width:o,height:I,style:{overflow:"visible"}}};return iC(A)?vI.success({name:"div",attributes:{style:{display:"inline",width:"100%",height:"100%"}},children:[c]}):(c.attributes.style.position="absolute",vI.success(c))}}class DB extends dc{constructor(A){super(zc,"linear",!0),this.id=A.id||"",this.type=LI(A.type,["toRight","toBottom","toLeft","toTop"]),this.use=A.use||"",this.usehref=A.usehref||"",this.color=null,this.extras=null}[bI](A){return A=A?A[bI]():"#FFFFFF",`linear-gradient(${this.type.replace(/([RBLT])/," $1").toLowerCase()}, ${A}, ${this.color?this.color[bI]():"#000000"})`}}class bB extends yc{constructor(A){super(zc,"lockDocument"),this.id=A.id||"",this.type=LI(A.type,["optional","required"]),this.use=A.use||"",this.usehref=A.usehref||""}[ko](){this[yo]=LI(this[yo],["auto","0","1"])}}class kB extends dc{constructor(A){super(zc,"manifest",!0),this.action=LI(A.action,["include","all","exclude"]),this.id=A.id||"",this.name=A.name||"",this.use=A.use||"",this.usehref=A.usehref||"",this.extras=null,this.ref=new fc}}class FB extends dc{constructor(A){super(zc,"margin",!0),this.bottomInset=JI(A.bottomInset,"0"),this.id=A.id||"",this.leftInset=JI(A.leftInset,"0"),this.rightInset=JI(A.rightInset,"0"),this.topInset=JI(A.topInset,"0"),this.use=A.use||"",this.usehref=A.usehref||"",this.extras=null}[bI](){return{margin:Sc(this.topInset)+" "+Sc(this.rightInset)+" "+Sc(this.bottomInset)+" "+Sc(this.leftInset)}}}class SB extends dc{constructor(A){super(zc,"mdp"),this.id=A.id||"",this.permissions=xI({data:A.permissions,defaultValue:2,validate:A=>1===A||3===A}),this.signatureType=LI(A.signatureType,["filler","author"]),this.use=A.use||"",this.usehref=A.usehref||""}}class RB extends dc{constructor(A){super(zc,"medium"),this.id=A.id||"",this.imagingBBox=function(A){const e=-1;if(!A)return{x:e,y:e,width:e,height:e};const t=A.trim().split(/\s*,\s*/).map((A=>JI(A,"-1")));if(t.length<4||t[2]<0||t[3]<0)return{x:e,y:e,width:e,height:e};const[i,a,s,n]=t;return{x:i,y:a,width:s,height:n}}(A.imagingBBox),this.long=JI(A.long),this.orientation=LI(A.orientation,["portrait","landscape"]),this.short=JI(A.short),this.stock=A.stock||"",this.trayIn=LI(A.trayIn,["auto","delegate","pageFront"]),this.trayOut=LI(A.trayOut,["auto","delegate"]),this.use=A.use||"",this.usehref=A.usehref||""}}class GB extends dc{constructor(A){super(zc,"message",!0),this.id=A.id||"",this.use=A.use||"",this.usehref=A.usehref||"",this.text=new fc}}class NB extends dc{constructor(A){super(zc,"numericEdit",!0),this.hScrollPolicy=LI(A.hScrollPolicy,["auto","off","on"]),this.id=A.id||"",this.use=A.use||"",this.usehref=A.usehref||"",this.border=null,this.comb=null,this.extras=null,this.margin=null}[wI](A){const e=Jc(this,"border","font","margin"),t=this[qo]()[qo](),i={name:"input",attributes:{type:"text",fieldId:t[kI],dataId:t[wo]?.[kI]||t[kI],class:["xfaTextfield"],style:e,"aria-label":oC(t),"aria-required":!1}};return nC(t)&&(i.attributes["aria-required"]=!0,i.attributes.required=!0),vI.success({name:"label",attributes:{class:["xfaLabel"]},children:[i]})}}class xB extends dc{constructor(A){super(zc,"occur",!0),this.id=A.id||"",this.initial=""!==A.initial?xI({data:A.initial,defaultValue:"",validate:A=>!0}):"",this.max=""!==A.max?xI({data:A.max,defaultValue:1,validate:A=>!0}):"",this.min=""!==A.min?xI({data:A.min,defaultValue:1,validate:A=>!0}):"",this.use=A.use||"",this.usehref=A.usehref||"",this.extras=null}[Eo](){const A=this[qo](),e=this.min;""===this.min&&(this.min=A instanceof JB||A instanceof HB?0:1),""===this.max&&(this.max=""===e?A instanceof JB||A instanceof HB?-1:1:this.min),-1!==this.max&&this.max!0}),this.name=A.name||"",this.numbered=xI({data:A.numbered,defaultValue:1,validate:A=>!0}),this.oddOrEven=LI(A.oddOrEven,["any","even","odd"]),this.pagePosition=LI(A.pagePosition,["any","first","last","only","rest"]),this.relevant=YI(A.relevant),this.use=A.use||"",this.usehref=A.usehref||"",this.desc=null,this.extras=null,this.medium=null,this.occur=null,this.area=new fc,this.contentArea=new fc,this.draw=new fc,this.exclGroup=new fc,this.field=new fc,this.subform=new fc}[iI](){return this[bo]?!this.occur||-1===this.occur.max||this[bo].numberOfUseA.oddOrEven===e&&A.pagePosition===t));return i||(i=this.pageArea.children.find((A=>"any"===A.oddOrEven&&A.pagePosition===t)),i||(i=this.pageArea.children.find((A=>"any"===A.oddOrEven&&"any"===A.pagePosition)),i||this.pageArea.children[0]))}}class YB extends dc{constructor(A){super(zc,"para",!0),this.hAlign=LI(A.hAlign,["left","center","justify","justifyAll","radix","right"]),this.id=A.id||"",this.lineHeight=A.lineHeight?JI(A.lineHeight,"0pt"):"",this.marginLeft=A.marginLeft?JI(A.marginLeft,"0pt"):"",this.marginRight=A.marginRight?JI(A.marginRight,"0pt"):"",this.orphans=xI({data:A.orphans,defaultValue:0,validate:A=>A>=0}),this.preserve=A.preserve||"",this.radixOffset=A.radixOffset?JI(A.radixOffset,"0pt"):"",this.spaceAbove=A.spaceAbove?JI(A.spaceAbove,"0pt"):"",this.spaceBelow=A.spaceBelow?JI(A.spaceBelow,"0pt"):"",this.tabDefault=A.tabDefault?JI(this.tabDefault):"",this.tabStops=(A.tabStops||"").trim().split(/\s+/).map(((A,e)=>e%2==1?JI(A):A)),this.textIndent=A.textIndent?JI(A.textIndent,"0pt"):"",this.use=A.use||"",this.usehref=A.usehref||"",this.vAlign=LI(A.vAlign,["top","bottom","middle"]),this.widows=xI({data:A.widows,defaultValue:0,validate:A=>A>=0}),this.hyphenation=null}[bI](){const A=Jc(this,"hAlign");return""!==this.marginLeft&&(A.paddingLeft=Sc(this.marginLeft)),""!==this.marginRight&&(A.paddingight=Sc(this.marginRight)),""!==this.spaceAbove&&(A.paddingTop=Sc(this.spaceAbove)),""!==this.spaceBelow&&(A.paddingBottom=Sc(this.spaceBelow)),""!==this.textIndent&&(A.textIndent=Sc(this.textIndent),Yc(A)),this.lineHeight>0&&(A.lineHeight=Sc(this.lineHeight)),""!==this.tabDefault&&(A.tabSize=Sc(this.tabDefault)),this.tabStops.length,this.hyphenatation&&Object.assign(A,this.hyphenatation[bI]()),A}}class vB extends dc{constructor(A){super(zc,"passwordEdit",!0),this.hScrollPolicy=LI(A.hScrollPolicy,["auto","off","on"]),this.id=A.id||"",this.passwordChar=A.passwordChar||"*",this.use=A.use||"",this.usehref=A.usehref||"",this.border=null,this.extras=null,this.margin=null}}class KB extends dc{constructor(A){super(zc,"pattern",!0),this.id=A.id||"",this.type=LI(A.type,["crossHatch","crossDiagonal","diagonalLeft","diagonalRight","horizontal","vertical"]),this.use=A.use||"",this.usehref=A.usehref||"",this.color=null,this.extras=null}[bI](A){A=A?A[bI]():"#FFFFFF";const e=this.color?this.color[bI]():"#000000",t="repeating-linear-gradient",i=`${A},${A} 5px,${e} 5px,${e} 10px`;switch(this.type){case"crossHatch":return`${t}(to top,${i}) ${t}(to right,${i})`;case"crossDiagonal":return`${t}(45deg,${i}) ${t}(-45deg,${i})`;case"diagonalLeft":return`${t}(45deg,${i})`;case"diagonalRight":return`${t}(-45deg,${i})`;case"horizontal":return`${t}(to top,${i})`;case"vertical":return`${t}(to right,${i})`}return""}}class qB extends Dc{constructor(A){super(zc,"picture"),this.id=A.id||"",this.use=A.use||"",this.usehref=A.usehref||""}}class TB extends dc{constructor(A){super(zc,"proto",!0),this.appearanceFilter=new fc,this.arc=new fc,this.area=new fc,this.assist=new fc,this.barcode=new fc,this.bindItems=new fc,this.bookend=new fc,this.boolean=new fc,this.border=new fc,this.break=new fc,this.breakAfter=new fc,this.breakBefore=new fc,this.button=new fc,this.calculate=new fc,this.caption=new fc,this.certificate=new fc,this.certificates=new fc,this.checkButton=new fc,this.choiceList=new fc,this.color=new fc,this.comb=new fc,this.connect=new fc,this.contentArea=new fc,this.corner=new fc,this.date=new fc,this.dateTime=new fc,this.dateTimeEdit=new fc,this.decimal=new fc,this.defaultUi=new fc,this.desc=new fc,this.digestMethod=new fc,this.digestMethods=new fc,this.draw=new fc,this.edge=new fc,this.encoding=new fc,this.encodings=new fc,this.encrypt=new fc,this.encryptData=new fc,this.encryption=new fc,this.encryptionMethod=new fc,this.encryptionMethods=new fc,this.event=new fc,this.exData=new fc,this.exObject=new fc,this.exclGroup=new fc,this.execute=new fc,this.extras=new fc,this.field=new fc,this.fill=new fc,this.filter=new fc,this.float=new fc,this.font=new fc,this.format=new fc,this.handler=new fc,this.hyphenation=new fc,this.image=new fc,this.imageEdit=new fc,this.integer=new fc,this.issuers=new fc,this.items=new fc,this.keep=new fc,this.keyUsage=new fc,this.line=new fc,this.linear=new fc,this.lockDocument=new fc,this.manifest=new fc,this.margin=new fc,this.mdp=new fc,this.medium=new fc,this.message=new fc,this.numericEdit=new fc,this.occur=new fc,this.oid=new fc,this.oids=new fc,this.overflow=new fc,this.pageArea=new fc,this.pageSet=new fc,this.para=new fc,this.passwordEdit=new fc,this.pattern=new fc,this.picture=new fc,this.radial=new fc,this.reason=new fc,this.reasons=new fc,this.rectangle=new fc,this.ref=new fc,this.script=new fc,this.setProperty=new fc,this.signData=new fc,this.signature=new fc,this.signing=new fc,this.solid=new fc,this.speak=new fc,this.stipple=new fc,this.subform=new fc,this.subformSet=new fc,this.subjectDN=new fc,this.subjectDNs=new fc,this.submit=new fc,this.text=new fc,this.textEdit=new fc,this.time=new fc,this.timeStamp=new fc,this.toolTip=new fc,this.traversal=new fc,this.traverse=new fc,this.ui=new fc,this.validate=new fc,this.value=new fc,this.variables=new fc}}class PB extends dc{constructor(A){super(zc,"radial",!0),this.id=A.id||"",this.type=LI(A.type,["toEdge","toCenter"]),this.use=A.use||"",this.usehref=A.usehref||"",this.color=null,this.extras=null}[bI](A){A=A?A[bI]():"#FFFFFF";const e=this.color?this.color[bI]():"#000000";return`radial-gradient(circle at center, ${"toEdge"===this.type?`${A},${e}`:`${e},${A}`})`}}class WB extends Dc{constructor(A){super(zc,"reason"),this.id=A.id||"",this.name=A.name||"",this.use=A.use||"",this.usehref=A.usehref||""}}class ZB extends dc{constructor(A){super(zc,"reasons",!0),this.id=A.id||"",this.type=LI(A.type,["optional","required"]),this.use=A.use||"",this.usehref=A.usehref||"",this.reason=new fc}}class OB extends dc{constructor(A){super(zc,"rectangle",!0),this.hand=LI(A.hand,["even","left","right"]),this.id=A.id||"",this.use=A.use||"",this.usehref=A.usehref||"",this.corner=new fc(4),this.edge=new fc(4),this.fill=null}[wI](){const A=this.edge.children.length?this.edge.children[0]:new VC({}),e=A[bI](),t=Object.create(null);"visible"===this.fill?.presence?Object.assign(t,this.fill[bI]()):t.fill="transparent",t.strokeWidth=Sc("visible"===A.presence?A.thickness:0),t.stroke=e.color;const i=(this.corner.children.length?this.corner.children[0]:new YC({}))[bI](),a={name:"svg",children:[{name:"rect",attributes:{xmlns:_c,width:"100%",height:"100%",x:0,y:0,rx:i.radius,ry:i.radius,style:t}}],attributes:{xmlns:_c,style:{overflow:"visible"},width:"100%",height:"100%"}};return iC(this[qo]()[qo]())?vI.success({name:"div",attributes:{style:{display:"inline",width:"100%",height:"100%"}},children:[a]}):(a.attributes.style.position="absolute",vI.success(a))}}class XB extends Dc{constructor(A){super(zc,"ref"),this.id=A.id||"",this.use=A.use||"",this.usehref=A.usehref||""}}class VB extends Dc{constructor(A){super(zc,"script"),this.binding=A.binding||"",this.contentType=A.contentType||"",this.id=A.id||"",this.name=A.name||"",this.runAt=LI(A.runAt,["client","both","server"]),this.use=A.use||"",this.usehref=A.usehref||""}}class jB extends dc{constructor(A){super(zc,"setProperty"),this.connection=A.connection||"",this.ref=A.ref||"",this.target=A.target||""}}class zB extends dc{constructor(A){super(zc,"signData",!0),this.id=A.id||"",this.operation=LI(A.operation,["sign","clear","verify"]),this.ref=A.ref||"",this.target=A.target||"",this.use=A.use||"",this.usehref=A.usehref||"",this.filter=null,this.manifest=null}}class _B extends dc{constructor(A){super(zc,"signature",!0),this.id=A.id||"",this.type=LI(A.type,["PDF1.3","PDF1.6"]),this.use=A.use||"",this.usehref=A.usehref||"",this.border=null,this.extras=null,this.filter=null,this.manifest=null,this.margin=null}}class $B extends dc{constructor(A){super(zc,"signing",!0),this.id=A.id||"",this.type=LI(A.type,["optional","required"]),this.use=A.use||"",this.usehref=A.usehref||"",this.certificate=new fc}}class Ah extends dc{constructor(A){super(zc,"solid",!0),this.id=A.id||"",this.use=A.use||"",this.usehref=A.usehref||"",this.extras=null}[bI](A){return A?A[bI]():"#FFFFFF"}}class eh extends Dc{constructor(A){super(zc,"speak"),this.disable=xI({data:A.disable,defaultValue:0,validate:A=>1===A}),this.id=A.id||"",this.priority=LI(A.priority,["custom","caption","name","toolTip"]),this.rid=A.rid||"",this.use=A.use||"",this.usehref=A.usehref||""}}class th extends dc{constructor(A){super(zc,"stipple",!0),this.id=A.id||"",this.rate=xI({data:A.rate,defaultValue:50,validate:A=>A>=0&&A<=100}),this.use=A.use||"",this.usehref=A.usehref||"",this.color=null,this.extras=null}[bI](A){const e=this.rate/100;return z.makeHexColor(Math.round(A.value.r*(1-e)+this.value.r*e),Math.round(A.value.g*(1-e)+this.value.g*e),Math.round(A.value.b*(1-e)+this.value.b*e))}}class ih extends dc{constructor(A){super(zc,"subform",!0),this.access=LI(A.access,["open","nonInteractive","protected","readOnly"]),this.allowMacro=xI({data:A.allowMacro,defaultValue:0,validate:A=>1===A}),this.anchorType=LI(A.anchorType,["topLeft","bottomCenter","bottomLeft","bottomRight","middleCenter","middleLeft","middleRight","topCenter","topRight"]),this.colSpan=xI({data:A.colSpan,defaultValue:1,validate:A=>A>=1||-1===A}),this.columnWidths=(A.columnWidths||"").trim().split(/\s+/).map((A=>"-1"===A?-1:JI(A))),this.h=A.h?JI(A.h):"",this.hAlign=LI(A.hAlign,["left","center","justify","justifyAll","radix","right"]),this.id=A.id||"",this.layout=LI(A.layout,["position","lr-tb","rl-row","rl-tb","row","table","tb"]),this.locale=A.locale||"",this.maxH=JI(A.maxH,"0pt"),this.maxW=JI(A.maxW,"0pt"),this.mergeMode=LI(A.mergeMode,["consumeData","matchTemplate"]),this.minH=JI(A.minH,"0pt"),this.minW=JI(A.minW,"0pt"),this.name=A.name||"",this.presence=LI(A.presence,["visible","hidden","inactive","invisible"]),this.relevant=YI(A.relevant),this.restoreState=LI(A.restoreState,["manual","auto"]),this.scope=LI(A.scope,["name","none"]),this.use=A.use||"",this.usehref=A.usehref||"",this.w=A.w?JI(A.w):"",this.x=JI(A.x,"0pt"),this.y=JI(A.y,"0pt"),this.assist=null,this.bind=null,this.bookend=null,this.border=null,this.break=null,this.calculate=null,this.desc=null,this.extras=null,this.keep=null,this.margin=null,this.occur=null,this.overflow=null,this.pageSet=null,this.para=null,this.traversal=null,this.validate=null,this.variables=null,this.area=new fc,this.breakAfter=new fc,this.breakBefore=new fc,this.connect=new fc,this.draw=new fc,this.event=new fc,this.exObject=new fc,this.exclGroup=new fc,this.field=new fc,this.proto=new fc,this.setProperty=new fc,this.subform=new fc,this.subformSet=new fc}[Ko](){const A=this[qo]();return A instanceof ah?A[Ko]():A}[jo](){return!0}[eI](){return this.layout.endsWith("-tb")&&0===this[bo].attempt&&this[bo].numberInLine>0||this[qo]()[eI]()}*[Yo](){yield*sC(this)}[Fo](){return Oc(this)}[ho](A,e){Xc(this,A,e)}[Go](){return Vc(this)}[AI](){const A=this[Ko]();return!!A[AI]()&&(void 0!==this[bo]._isSplittable?this[bo]._isSplittable:"position"===this.layout||this.layout.includes("row")||this.keep&&"none"!==this.keep.intact?(this[bo]._isSplittable=!1,!1):!(A.layout?.endsWith("-tb")&&0!==A[bo].numberInLine||(this[bo]._isSplittable=!0,0)))}[wI](A){if(gC(this),this.break){if("auto"!==this.break.after||""!==this.break.afterTarget){const A=new bC({targetType:this.break.after,target:this.break.afterTarget,startNew:this.break.startNew.toString()});A[Po]=this[Po],this[Qo](A),this.breakAfter.push(A)}if("auto"!==this.break.before||""!==this.break.beforeTarget){const A=new kC({targetType:this.break.before,target:this.break.beforeTarget,startNew:this.break.startNew.toString()});A[Po]=this[Po],this[Qo](A),this.breakBefore.push(A)}if(""!==this.break.overflowTarget){const A=new LB({target:this.break.overflowTarget,leader:this.break.overflowLeader,trailer:this.break.overflowTrailer});A[Po]=this[Po],this[Qo](A),this.overflow.push(A)}this[hI](this.break),this.break=null}if("hidden"===this.presence||"inactive"===this.presence)return vI.EMPTY;if((this.breakBefore.children.length>1||this.breakAfter.children.length>1)&&N("XFA - Several breakBefore or breakAfter in subforms: please file a bug."),this.breakBefore.children.length>=1){const A=this.breakBefore.children[0];if(BC(A))return vI.breakNode(A)}if(this[bo]?.afterBreakAfter)return vI.EMPTY;Mc(this);const e=[],t={id:this[kI],class:[]};vc(this,t.class),this[bo]||(this[bo]=Object.create(null)),Object.assign(this[bo],{children:e,line:null,attributes:t,attempt:0,numberInLine:0,availableSpace:{width:Math.min(this.w||1/0,A.width),height:Math.min(this.h||1/0,A.height)},width:0,height:0,prevHeight:0,currentWidth:0});const i=this[To](),a=i[bo].noLayoutFailure,s=this[AI]();if(s||cC(this),!jc(this,A))return vI.FAILURE;const n=new Set(["area","draw","exclGroup","field","subform","subformSet"]);if(this.layout.includes("row")){const A=this[Ko]().columnWidths;Array.isArray(A)&&A.length>0&&(this[bo].columnWidths=A,this[bo].currentColumn=0)}const g=Jc(this,"anchorType","dimensions","position","presence","border","margin","hAlign"),r=["xfaSubform"],o=Lc(this);if(o&&r.push(o),t.style=g,t.class=r,this.name&&(t.xfaName=this.name),this.overflow){const e=this.overflow[Lo]();e.addLeader&&(e.addLeader=!1,hC(this,e.leader,A))}this[BI]();const I="lr-tb"===this.layout||"rl-tb"===this.layout,c=I?2:1;for(;this[bo].attempt=1){const A=this.breakAfter.children[0];if(BC(A))return this[bo].afterBreakAfter=u,vI.breakNode(A)}return delete this[bo],u}}class ah extends dc{constructor(A){super(zc,"subformSet",!0),this.id=A.id||"",this.name=A.name||"",this.relation=LI(A.relation,["ordered","choice","unordered"]),this.relevant=YI(A.relevant),this.use=A.use||"",this.usehref=A.usehref||"",this.bookend=null,this.break=null,this.desc=null,this.extras=null,this.occur=null,this.overflow=null,this.breakAfter=new fc,this.breakBefore=new fc,this.subform=new fc,this.subformSet=new fc}*[Yo](){yield*sC(this)}[Ko](){let A=this[qo]();for(;!(A instanceof ih);)A=A[qo]();return A}[jo](){return!0}}class sh extends yc{constructor(A){super(zc,"subjectDN"),this.delimiter=A.delimiter||",",this.id=A.id||"",this.name=A.name||"",this.use=A.use||"",this.usehref=A.usehref||""}[ko](){this[yo]=new Map(this[yo].split(this.delimiter).map((A=>((A=A.split("=",2))[0]=A[0].trim(),A))))}}class nh extends dc{constructor(A){super(zc,"subjectDNs",!0),this.id=A.id||"",this.type=LI(A.type,["optional","required"]),this.use=A.use||"",this.usehref=A.usehref||"",this.subjectDN=new fc}}class gh extends dc{constructor(A){super(zc,"submit",!0),this.embedPDF=xI({data:A.embedPDF,defaultValue:0,validate:A=>1===A}),this.format=LI(A.format,["xdp","formdata","pdf","urlencoded","xfd","xml"]),this.id=A.id||"",this.target=A.target||"",this.textEncoding=MI({data:A.textEncoding?A.textEncoding.toLowerCase():"",defaultValue:"",validate:A=>["utf-8","big-five","fontspecific","gbk","gb-18030","gb-2312","ksc-5601","none","shift-jis","ucs-2","utf-16"].includes(A)||A.match(/iso-8859-\d{2}/)}),this.use=A.use||"",this.usehref=A.usehref||"",this.xdpContent=A.xdpContent||"",this.encrypt=null,this.encryptData=new fc,this.signData=new fc}}class rh extends dc{constructor(A){super(zc,"template",!0),this.baseProfile=LI(A.baseProfile,["full","interactiveForms"]),this.extras=null,this.subform=new fc}[ko](){0===this.subform.children.length&&N("XFA - No subforms in template node."),this.subform.children.length>=2&&N("XFA - Several subforms in template node: please file a bug."),this[pI]=5e3}[AI](){return!0}[EI](A,e){return A.startsWith("#")?[this[Zo].get(A.slice(1))]:_I(this,e,A,!0,!0)}*[yI](){if(!this.subform.children.length)return vI.success({name:"div",children:[]});this[bo]={overflowNode:null,firstUnsplittable:null,currentContentArea:null,currentPageArea:null,noLayoutFailure:!1,pageNumber:1,pagePosition:"first",oddOrEven:"odd",blankOrNotBlank:"nonBlank",paraStack:[]};const A=this.subform.children[0];A.pageSet[uo]();const e=A.pageSet.pageArea.children,t={name:"div",children:[]};let i=null,a=null,s=null;if(A.breakBefore.children.length>=1?(a=A.breakBefore.children[0],s=a.target):A.subform.children.length>=1&&A.subform.children[0].breakBefore.children.length>=1?(a=A.subform.children[0].breakBefore.children[0],s=a.target):A.break?.beforeTarget?(a=A.break,s=a.beforeTarget):A.subform.children.length>=1&&A.subform.children[0].break?.beforeTarget&&(a=A.subform.children[0].break,s=a.beforeTarget),a){const A=this[EI](s,a[qo]());A instanceof JB&&(i=A,a[bo]={})}i||(i=e[0]),i[bo]={numberOfUse:1};const n=i[qo]();let g;n[bo]={numberOfUse:1,pageIndex:n.pageArea.children.indexOf(i),pageSetIndex:0};let r=null,o=null,I=!0,c=0,C=0;for(;;){if(I)c=0;else if(t.children.pop(),3==++c)return N("XFA - Something goes wrong: please file a bug."),t;g=null,this[bo].currentPageArea=i;const e=i[wI]().html;t.children.push(e),r&&(this[bo].noLayoutFailure=!0,e.children.push(r[wI](i[bo].space).html),r=null),o&&(this[bo].noLayoutFailure=!0,e.children.push(o[wI](i[bo].space).html),o=null);const a=i.contentArea.children,s=e.children.filter((A=>A.attributes.class.includes("xfaContentarea")));I=!1,this[bo].firstUnsplittable=null,this[bo].noLayoutFailure=!1;const n=e=>{const t=A[Fo]();t&&(I||=t.children?.length>0,s[e].children.push(t))};for(let e=C,i=a.length;e0,s[e].children.push(B.html)):!I&&t.children.length>1&&t.children.pop(),t;if(B.isBreak()){const A=B.breakNode;if(n(e),"auto"===A.targetType)continue;A.leader&&(r=this[EI](A.leader,A[qo]()),r=r?r[0]:null),A.trailer&&(o=this[EI](A.trailer,A[qo]()),o=o?o[0]:null),"pageArea"===A.targetType?(g=A[bo].target,e=1/0):A[bo].target?(g=A[bo].target,C=A[bo].index+1,e=1/0):e=A[bo].index}else if(this[bo].overflowNode){const A=this[bo].overflowNode;this[bo].overflowNode=null;const t=A[Lo](),i=t.target;t.addLeader=null!==t.leader,t.addTrailer=null!==t.trailer,n(e);const s=e;if(e=1/0,i instanceof JB)g=i;else if(i instanceof HC){const A=a.indexOf(i);-1!==A?A>s?e=A-1:C=A:(g=i[qo](),C=g.contentArea.children.indexOf(i))}}else n(e)}this[bo].pageNumber+=1,g&&(g[iI]()?g[bo].numberOfUse+=1:g=null),i=g||i[vo](),yield null}}}class oh extends yc{constructor(A){super(zc,"text"),this.id=A.id||"",this.maxChars=xI({data:A.maxChars,defaultValue:0,validate:A=>A>=0}),this.name=A.name||"",this.rid=A.rid||"",this.use=A.use||"",this.usehref=A.usehref||""}[Bo](){return!0}[rI](A){return A[sI]===SI.xhtml.id?(this[yo]=A,!0):(N(`XFA - Invalid content in Text: ${A[nI]}.`),!1)}[II](A){this[yo]instanceof dc||super[II](A)}[ko](){"string"==typeof this[yo]&&(this[yo]=this[yo].replaceAll("\r\n","\n"))}[Lo](){return"string"==typeof this[yo]?this[yo].split(/[\u2029\u2028\n]/).reduce(((A,e)=>(e&&A.push(e),A)),[]).join("\n"):this[yo][mI]()}[wI](A){if("string"==typeof this[yo]){const A=IC(this[yo]).html;return this[yo].includes("\u2029")?(A.name="div",A.children=[],this[yo].split("\u2029").map((A=>A.split(/[\u2028\n]/).reduce(((A,e)=>(A.push({name:"span",value:e},{name:"br"}),A)),[]))).forEach((e=>{A.children.push({name:"p",children:e})}))):/[\u2028\n]/.test(this[yo])&&(A.name="div",A.children=[],this[yo].split(/[\u2028\n]/).forEach((e=>{A.children.push({name:"span",value:e},{name:"br"})}))),vI.success(A)}return this[yo][wI](A)}}class Ih extends dc{constructor(A){super(zc,"textEdit",!0),this.allowRichText=xI({data:A.allowRichText,defaultValue:0,validate:A=>1===A}),this.hScrollPolicy=LI(A.hScrollPolicy,["auto","off","on"]),this.id=A.id||"",this.multiLine=xI({data:A.multiLine,defaultValue:"",validate:A=>0===A||1===A}),this.use=A.use||"",this.usehref=A.usehref||"",this.vScrollPolicy=LI(A.vScrollPolicy,["auto","off","on"]),this.border=null,this.comb=null,this.extras=null,this.margin=null}[wI](A){const e=Jc(this,"border","font","margin");let t;const i=this[qo]()[qo]();return""===this.multiLine&&(this.multiLine=i instanceof XC?1:0),t=1===this.multiLine?{name:"textarea",attributes:{dataId:i[wo]?.[kI]||i[kI],fieldId:i[kI],class:["xfaTextfield"],style:e,"aria-label":oC(i),"aria-required":!1}}:{name:"input",attributes:{type:"text",dataId:i[wo]?.[kI]||i[kI],fieldId:i[kI],class:["xfaTextfield"],style:e,"aria-label":oC(i),"aria-required":!1}},nC(i)&&(t.attributes["aria-required"]=!0,t.attributes.required=!0),vI.success({name:"label",attributes:{class:["xfaLabel"]},children:[t]})}}class ch extends Dc{constructor(A){super(zc,"time"),this.id=A.id||"",this.name=A.name||"",this.use=A.use||"",this.usehref=A.usehref||""}[ko](){const A=this[yo].trim();this[yo]=A?new Date(A):null}[wI](A){return IC(this[yo]?this[yo].toString():"")}}class Ch extends dc{constructor(A){super(zc,"timeStamp"),this.id=A.id||"",this.server=A.server||"",this.type=LI(A.type,["optional","required"]),this.use=A.use||"",this.usehref=A.usehref||""}}class Bh extends Dc{constructor(A){super(zc,"toolTip"),this.id=A.id||"",this.rid=A.rid||"",this.use=A.use||"",this.usehref=A.usehref||""}}class hh extends dc{constructor(A){super(zc,"traversal",!0),this.id=A.id||"",this.use=A.use||"",this.usehref=A.usehref||"",this.extras=null,this.traverse=new fc}}class Qh extends dc{constructor(A){super(zc,"traverse",!0),this.id=A.id||"",this.operation=LI(A.operation,["next","back","down","first","left","right","up"]),this.ref=A.ref||"",this.use=A.use||"",this.usehref=A.usehref||"",this.extras=null,this.script=null}get name(){return this.operation}[tI](){return!1}}class lh extends dc{constructor(A){super(zc,"ui",!0),this.id=A.id||"",this.use=A.use||"",this.usehref=A.usehref||"",this.extras=null,this.picture=null,this.barcode=null,this.button=null,this.checkButton=null,this.choiceList=null,this.dateTimeEdit=null,this.defaultUi=null,this.imageEdit=null,this.numericEdit=null,this.passwordEdit=null,this.signature=null,this.textEdit=null}[Lo](){if(void 0===this[bo]){for(const A of Object.getOwnPropertyNames(this)){if("extras"===A||"picture"===A)continue;const e=this[A];if(e instanceof dc)return this[bo]=e,e}this[bo]=null}return this[bo]}[wI](A){const e=this[Lo]();return e?e[wI](A):vI.EMPTY}}class Eh extends dc{constructor(A){super(zc,"validate",!0),this.formatTest=LI(A.formatTest,["warning","disabled","error"]),this.id=A.id||"",this.nullTest=LI(A.nullTest,["disabled","error","warning"]),this.scriptTest=LI(A.scriptTest,["error","disabled","warning"]),this.use=A.use||"",this.usehref=A.usehref||"",this.extras=null,this.message=null,this.picture=null,this.script=null}}class uh extends dc{constructor(A){super(zc,"value",!0),this.id=A.id||"",this.override=xI({data:A.override,defaultValue:0,validate:A=>1===A}),this.relevant=YI(A.relevant),this.use=A.use||"",this.usehref=A.usehref||"",this.arc=null,this.boolean=null,this.date=null,this.dateTime=null,this.decimal=null,this.exData=null,this.float=null,this.image=null,this.integer=null,this.line=null,this.rectangle=null,this.text=null,this.time=null}[fI](A){const e=this[qo]();if(e instanceof oB&&e.ui?.imageEdit)return this.image||(this.image=new EB({}),this[Qo](this.image)),void(this.image[yo]=A[yo]);const t=A[nI];if(null===this[t]){for(const A of Object.getOwnPropertyNames(this)){const e=this[A];e instanceof dc&&(this[A]=null,this[hI](e))}this[A[nI]]=A,this[Qo](A)}else this[t][yo]=A[yo]}[mI](){if(this.exData)return"string"==typeof this.exData[yo]?this.exData[yo].trim():this.exData[yo][mI]().trim();for(const A of Object.getOwnPropertyNames(this)){if("image"===A)continue;const e=this[A];if(e instanceof dc)return(e[yo]||"").toString().trim()}return null}[wI](A){for(const e of Object.getOwnPropertyNames(this)){const t=this[e];if(t instanceof dc)return t[wI](A)}return vI.EMPTY}}class dh extends dc{constructor(A){super(zc,"variables",!0),this.id=A.id||"",this.use=A.use||"",this.usehref=A.usehref||"",this.boolean=new fc,this.date=new fc,this.dateTime=new fc,this.decimal=new fc,this.exData=new fc,this.float=new fc,this.image=new fc,this.integer=new fc,this.manifest=new fc,this.script=new fc,this.text=new fc,this.time=new fc}[tI](){return!0}}class fh{static[FI](A,e){if(fh.hasOwnProperty(A)){const t=fh[A](e);return t[dI](e),t}}static appearanceFilter(A){return new QC(A)}static arc(A){return new lC(A)}static area(A){return new EC(A)}static assist(A){return new uC(A)}static barcode(A){return new dC(A)}static bind(A){return new fC(A)}static bindItems(A){return new pC(A)}static bookend(A){return new mC(A)}static boolean(A){return new yC(A)}static border(A){return new wC(A)}static break(A){return new DC(A)}static breakAfter(A){return new bC(A)}static breakBefore(A){return new kC(A)}static button(A){return new FC(A)}static calculate(A){return new SC(A)}static caption(A){return new RC(A)}static certificate(A){return new GC(A)}static certificates(A){return new NC(A)}static checkButton(A){return new xC(A)}static choiceList(A){return new UC(A)}static color(A){return new MC(A)}static comb(A){return new LC(A)}static connect(A){return new JC(A)}static contentArea(A){return new HC(A)}static corner(A){return new YC(A)}static date(A){return new vC(A)}static dateTime(A){return new KC(A)}static dateTimeEdit(A){return new qC(A)}static decimal(A){return new TC(A)}static defaultUi(A){return new PC(A)}static desc(A){return new WC(A)}static digestMethod(A){return new ZC(A)}static digestMethods(A){return new OC(A)}static draw(A){return new XC(A)}static edge(A){return new VC(A)}static encoding(A){return new jC(A)}static encodings(A){return new zC(A)}static encrypt(A){return new _C(A)}static encryptData(A){return new $C(A)}static encryption(A){return new AB(A)}static encryptionMethod(A){return new eB(A)}static encryptionMethods(A){return new tB(A)}static event(A){return new iB(A)}static exData(A){return new aB(A)}static exObject(A){return new sB(A)}static exclGroup(A){return new nB(A)}static execute(A){return new gB(A)}static extras(A){return new rB(A)}static field(A){return new oB(A)}static fill(A){return new IB(A)}static filter(A){return new cB(A)}static float(A){return new CB(A)}static font(A){return new BB(A)}static format(A){return new hB(A)}static handler(A){return new QB(A)}static hyphenation(A){return new lB(A)}static image(A){return new EB(A)}static imageEdit(A){return new uB(A)}static integer(A){return new dB(A)}static issuers(A){return new fB(A)}static items(A){return new pB(A)}static keep(A){return new mB(A)}static keyUsage(A){return new yB(A)}static line(A){return new wB(A)}static linear(A){return new DB(A)}static lockDocument(A){return new bB(A)}static manifest(A){return new kB(A)}static margin(A){return new FB(A)}static mdp(A){return new SB(A)}static medium(A){return new RB(A)}static message(A){return new GB(A)}static numericEdit(A){return new NB(A)}static occur(A){return new xB(A)}static oid(A){return new UB(A)}static oids(A){return new MB(A)}static overflow(A){return new LB(A)}static pageArea(A){return new JB(A)}static pageSet(A){return new HB(A)}static para(A){return new YB(A)}static passwordEdit(A){return new vB(A)}static pattern(A){return new KB(A)}static picture(A){return new qB(A)}static proto(A){return new TB(A)}static radial(A){return new PB(A)}static reason(A){return new WB(A)}static reasons(A){return new ZB(A)}static rectangle(A){return new OB(A)}static ref(A){return new XB(A)}static script(A){return new VB(A)}static setProperty(A){return new jB(A)}static signData(A){return new zB(A)}static signature(A){return new _B(A)}static signing(A){return new $B(A)}static solid(A){return new Ah(A)}static speak(A){return new eh(A)}static stipple(A){return new th(A)}static subform(A){return new ih(A)}static subformSet(A){return new ah(A)}static subjectDN(A){return new sh(A)}static subjectDNs(A){return new nh(A)}static submit(A){return new gh(A)}static template(A){return new rh(A)}static text(A){return new oh(A)}static textEdit(A){return new Ih(A)}static time(A){return new ch(A)}static timeStamp(A){return new Ch(A)}static toolTip(A){return new Bh(A)}static traversal(A){return new hh(A)}static traverse(A){return new Qh(A)}static ui(A){return new lh(A)}static validate(A){return new Eh(A)}static value(A){return new uh(A)}static variables(A){return new dh(A)}}const ph=SI.datasets.id;function mh(A){const e=new oh({});return e[yo]=A,e}class yh{constructor(A){this.root=A,this.datasets=A.datasets,this.data=A.datasets?.data||new mc(SI.datasets.id,"data"),this.emptyMerge=0===this.data[Ho]().length,this.root.form=this.form=A.template[po]()}_isConsumeData(){return!this.emptyMerge&&this._mergeMode}_isMatchTemplate(){return!this._isConsumeData()}bind(){return this._bindElement(this.form,this.data),this.form}getData(){return this.data}_bindValue(A,e,t){if(A[wo]=e,A[Wo]())if(e[zo]()){const t=e[Mo]();A[fI](mh(t))}else if(A instanceof oB&&"multiSelect"===A.ui?.choiceList?.open){const t=e[Ho]().map((A=>A[yo].trim())).join("\n");A[fI](mh(t))}else this._isConsumeData()&&N("XFA - Nodes haven't the same type.");else!e[zo]()||this._isMatchTemplate()?this._bindElement(A,e):N("XFA - Nodes haven't the same type.")}_findDataByNameToConsume(A,e,t,i){if(!A)return null;let a,s;for(let i=0;i<3;i++){for(a=t[Jo](A,!1,!0);s=a.next().value,s;)if(e===s[zo]())return s;if(t[sI]===SI.datasets.id&&"data"===t[nI])break;t=t[qo]()}return i?(a=this.data[Jo](A,!0,!1),s=a.next().value,s||(a=this.data[So](A,!0),s=a.next().value,s?.[zo]()?s:null)):null}_setProperties(A,e){if(A.hasOwnProperty("setProperty"))for(const{ref:t,target:i,connection:a}of A.setProperty.children){if(a)continue;if(!t)continue;const s=_I(this.root,e,t,!1,!1);if(!s){N(`XFA - Invalid reference: ${t}.`);continue}const[n]=s;if(!n[_o](this.data)){N("XFA - Invalid node: must be a data node.");continue}const g=_I(this.root,A,i,!1,!1);if(!g){N(`XFA - Invalid target: ${i}.`);continue}const[r]=g;if(!r[_o](A)){N("XFA - Invalid target: must be a property or subproperty.");continue}const o=r[qo]();if(r instanceof jB||o instanceof jB){N("XFA - Invalid target: cannot be a setProperty or one of its properties.");continue}if(r instanceof pC||o instanceof pC){N("XFA - Invalid target: cannot be a bindItems or one of its properties.");continue}const I=n[mI](),c=r[nI];if(r instanceof pc){const A=Object.create(null);A[c]=I;const e=Reflect.construct(Object.getPrototypeOf(o).constructor,[A]);o[c]=e[c]}else r.hasOwnProperty(yo)?(r[wo]=n,r[yo]=I,r[ko]()):N("XFA - Invalid node to use in setProperty")}}_bindItems(A,e){if(!A.hasOwnProperty("items")||!A.hasOwnProperty("bindItems")||A.bindItems.isEmpty())return;for(const e of A.items.children)A[hI](e);A.items.clear();const t=new pB({}),i=new pB({});A[Qo](t),A.items.push(t),A[Qo](i),A.items.push(i);for(const{ref:a,labelRef:s,valueRef:n,connection:g}of A.bindItems.children){if(g)continue;if(!a)continue;const A=_I(this.root,e,a,!1,!1);if(A)for(const e of A){if(!e[_o](this.datasets)){N(`XFA - Invalid ref (${a}): must be a datasets child.`);continue}const A=_I(this.root,e,s,!0,!1);if(!A){N(`XFA - Invalid label: ${s}.`);continue}const[g]=A;if(!g[_o](this.datasets)){N("XFA - Invalid label: must be a datasets child.");continue}const r=_I(this.root,e,n,!0,!1);if(!r){N(`XFA - Invalid value: ${n}.`);continue}const[o]=r;if(!o[_o](this.datasets)){N("XFA - Invalid value: must be a datasets child.");continue}const I=mh(g[mI]()),c=mh(o[mI]());t[Qo](I),t.text.push(I),i[Qo](c),i.text.push(c)}else N(`XFA - Invalid reference: ${a}.`)}}_bindOccurrences(A,e,t){let i;if(e.length>1&&(i=A[po](),i[hI](i.occur),i.occur=null),this._bindValue(A,e[0],t),this._setProperties(A,e[0]),this._bindItems(A,e[0]),1===e.length)return;const a=A[qo](),s=A[nI],n=a[Oo](A);for(let A=1,g=e.length;Ae.name===A.name)).length:t[i].children.length;const s=t[Oo](A)+1,n=e.initial-a;if(n){const e=A[po]();e[hI](e.occur),e.occur=null,t[i].push(e),t[Xo](s,e);for(let A=1;A0)this._bindOccurrences(i,[A[0]],null);else if(this.emptyMerge){const A=e[sI]===ph?-1:e[sI],t=i[wo]=new mc(A,i.name||"root");e[Qo](t),this._bindElement(i,t)}continue}if(!i[jo]())continue;let A=!1,a=null,s=null,n=null;if(i.bind){switch(i.bind.match){case"none":this._setAndBind(i,e);continue;case"global":A=!0;break;case"dataRef":if(!i.bind.ref){N(`XFA - ref is empty in node ${i[nI]}.`),this._setAndBind(i,e);continue}s=i.bind.ref}i.bind.picture&&(a=i.bind.picture[yo])}const[g,r]=this._getOccurInfo(i);if(s){if(n=_I(this.root,e,s,!0,!1),null===n){if(n=$I(this.data,e,s),!n)continue;this._isConsumeData()&&(n[mo]=!0),this._setAndBind(i,n);continue}this._isConsumeData()&&(n=n.filter((A=>!A[mo]))),n.length>r?n=n.slice(0,r):0===n.length&&(n=null),n&&this._isConsumeData()&&n.forEach((A=>{A[mo]=!0}))}else{if(!i.name){this._setAndBind(i,e);continue}if(this._isConsumeData()){const t=[];for(;t.length0?t:null}else{if(n=e[Jo](i.name,!1,this.emptyMerge).next().value,!n){if(0===g){t.push(i);continue}const A=e[sI]===ph?-1:e[sI];n=i[wo]=new mc(A,i.name),this.emptyMerge&&(n[mo]=!0),e[Qo](n),this._setAndBind(i,n);continue}this.emptyMerge&&(n[mo]=!0),n=[n]}}n?this._bindOccurrences(i,n,a):g>0?this._setAndBind(i,e):t.push(i)}t.forEach((A=>A[qo]()[hI](A)))}}class wh{constructor(A,e){this.data=e,this.dataset=A.datasets||null}serialize(A){const e=[[-1,this.data[Ho]()]];for(;e.length>0;){const t=e.at(-1),[i,a]=t;if(i+1===a.length){e.pop();continue}const s=a[++t[0]],n=A.get(s[kI]);if(n)s[fI](n);else{const e=s[Ro]();for(const t of e.values()){const e=A.get(t[kI]);if(e){t[fI](e);break}}}const g=s[Ho]();g.length>0&&e.push([-1,g])}const t=[''];if(this.dataset)for(const A of this.dataset[Ho]())"data"!==A[nI]&&A[DI](t);return this.data[DI](t),t.push(""),t.join("")}}const Dh=SI.config.id;class bh extends dc{constructor(A){super(Dh,"acrobat",!0),this.acrobat7=null,this.autoSave=null,this.common=null,this.validate=null,this.validateApprovalSignatures=null,this.submitUrl=new fc}}class kh extends dc{constructor(A){super(Dh,"acrobat7",!0),this.dynamicRender=null}}class Fh extends wc{constructor(A){super(Dh,"ADBE_JSConsole",["delegate","Enable","Disable"])}}class Sh extends wc{constructor(A){super(Dh,"ADBE_JSDebugger",["delegate","Enable","Disable"])}}class Rh extends kc{constructor(A){super(Dh,"addSilentPrint")}}class Gh extends kc{constructor(A){super(Dh,"addViewerPreferences")}}class Nh extends Fc{constructor(A){super(Dh,"adjustData")}}class xh extends bc{constructor(A){super(Dh,"adobeExtensionLevel",0,(A=>A>=1&&A<=8))}}class Uh extends dc{constructor(A){super(Dh,"agent",!0),this.name=A.name?A.name.trim():"",this.common=new fc}}class Mh extends yc{constructor(A){super(Dh,"alwaysEmbed")}}class Lh extends Dc{constructor(A){super(Dh,"amd")}}class Jh extends dc{constructor(A){super(Dh,"area"),this.level=xI({data:A.level,defaultValue:0,validate:A=>A>=1&&A<=3}),this.name=LI(A.name,["","barcode","coreinit","deviceDriver","font","general","layout","merge","script","signature","sourceSet","templateCache"])}}class Hh extends wc{constructor(A){super(Dh,"attributes",["preserve","delegate","ignore"])}}class Yh extends wc{constructor(A){super(Dh,"autoSave",["disabled","enabled"])}}class vh extends Dc{constructor(A){super(Dh,"base")}}class Kh extends dc{constructor(A){super(Dh,"batchOutput"),this.format=LI(A.format,["none","concat","zip","zipCompress"])}}class qh extends yc{constructor(A){super(Dh,"behaviorOverride")}[ko](){this[yo]=new Map(this[yo].trim().split(/\s+/).filter((A=>A.includes(":"))).map((A=>A.split(":",2))))}}class Th extends dc{constructor(A){super(Dh,"cache",!0),this.templateCache=null}}class Ph extends kc{constructor(A){super(Dh,"change")}}class Wh extends dc{constructor(A){super(Dh,"common",!0),this.data=null,this.locale=null,this.localeSet=null,this.messaging=null,this.suppressBanner=null,this.template=null,this.validationMessaging=null,this.versionControl=null,this.log=new fc}}class Zh extends dc{constructor(A){super(Dh,"compress"),this.scope=LI(A.scope,["imageOnly","document"])}}class Oh extends kc{constructor(A){super(Dh,"compressLogicalStructure")}}class Xh extends Fc{constructor(A){super(Dh,"compressObjectStream")}}class Vh extends dc{constructor(A){super(Dh,"compression",!0),this.compressLogicalStructure=null,this.compressObjectStream=null,this.level=null,this.type=null}}class jh extends dc{constructor(A){super(Dh,"config",!0),this.acrobat=null,this.present=null,this.trace=null,this.agent=new fc}}class zh extends wc{constructor(A){super(Dh,"conformance",["A","B"])}}class _h extends kc{constructor(A){super(Dh,"contentCopy")}}class $h extends bc{constructor(A){super(Dh,"copies",1,(A=>A>=1))}}class AQ extends Dc{constructor(A){super(Dh,"creator")}}class eQ extends bc{constructor(A){super(Dh,"currentPage",0,(A=>A>=0))}}class tQ extends dc{constructor(A){super(Dh,"data",!0),this.adjustData=null,this.attributes=null,this.incrementalLoad=null,this.outputXSL=null,this.range=null,this.record=null,this.startNode=null,this.uri=null,this.window=null,this.xsl=null,this.excludeNS=new fc,this.transform=new fc}}class iQ extends dc{constructor(A){super(Dh,"debug",!0),this.uri=null}}class aQ extends yc{constructor(A){super(Dh,"defaultTypeface"),this.writingScript=LI(A.writingScript,["*","Arabic","Cyrillic","EastEuropeanRoman","Greek","Hebrew","Japanese","Korean","Roman","SimplifiedChinese","Thai","TraditionalChinese","Vietnamese"])}}class sQ extends wc{constructor(A){super(Dh,"destination",["pdf","pcl","ps","webClient","zpl"])}}class nQ extends kc{constructor(A){super(Dh,"documentAssembly")}}class gQ extends dc{constructor(A){super(Dh,"driver",!0),this.name=A.name?A.name.trim():"",this.fontInfo=null,this.xdc=null}}class rQ extends wc{constructor(A){super(Dh,"duplexOption",["simplex","duplexFlipLongEdge","duplexFlipShortEdge"])}}class oQ extends wc{constructor(A){super(Dh,"dynamicRender",["forbidden","required"])}}class IQ extends kc{constructor(A){super(Dh,"embed")}}class cQ extends kc{constructor(A){super(Dh,"encrypt")}}class CQ extends dc{constructor(A){super(Dh,"encryption",!0),this.encrypt=null,this.encryptionLevel=null,this.permissions=null}}class BQ extends wc{constructor(A){super(Dh,"encryptionLevel",["40bit","128bit"])}}class hQ extends Dc{constructor(A){super(Dh,"enforce")}}class QQ extends dc{constructor(A){super(Dh,"equate"),this.force=xI({data:A.force,defaultValue:1,validate:A=>0===A}),this.from=A.from||"",this.to=A.to||""}}class lQ extends dc{constructor(A){super(Dh,"equateRange"),this.from=A.from||"",this.to=A.to||"",this._unicodeRange=A.unicodeRange||""}get unicodeRange(){const A=[],e=/U\+([0-9a-fA-F]+)/,t=this._unicodeRange;for(let i of t.split(",").map((A=>A.trim())).filter((A=>!!A)))i=i.split("-",2).map((A=>{const t=A.match(e);return t?parseInt(t[1],16):0})),1===i.length&&i.push(i[0]),A.push(i);return L(this,"unicodeRange",A)}}class EQ extends yc{constructor(A){super(Dh,"exclude")}[ko](){this[yo]=this[yo].trim().split(/\s+/).filter((A=>A&&["calculate","close","enter","exit","initialize","ready","validate"].includes(A)))}}class uQ extends Dc{constructor(A){super(Dh,"excludeNS")}}class dQ extends wc{constructor(A){super(Dh,"flipLabel",["usePrinterSetting","on","off"])}}class fQ extends dc{constructor(A){super(Dh,"fontInfo",!0),this.embed=null,this.map=null,this.subsetBelow=null,this.alwaysEmbed=new fc,this.defaultTypeface=new fc,this.neverEmbed=new fc}}class pQ extends kc{constructor(A){super(Dh,"formFieldFilling")}}class mQ extends Dc{constructor(A){super(Dh,"groupParent")}}class yQ extends wc{constructor(A){super(Dh,"ifEmpty",["dataValue","dataGroup","ignore","remove"])}}class wQ extends Dc{constructor(A){super(Dh,"includeXDPContent")}}class DQ extends wc{constructor(A){super(Dh,"incrementalLoad",["none","forwardOnly"])}}class bQ extends kc{constructor(A){super(Dh,"incrementalMerge")}}class kQ extends kc{constructor(A){super(Dh,"interactive")}}class FQ extends wc{constructor(A){super(Dh,"jog",["usePrinterSetting","none","pageSet"])}}class SQ extends dc{constructor(A){super(Dh,"labelPrinter",!0),this.name=LI(A.name,["zpl","dpl","ipl","tcpl"]),this.batchOutput=null,this.flipLabel=null,this.fontInfo=null,this.xdc=null}}class RQ extends wc{constructor(A){super(Dh,"layout",["paginate","panel"])}}class GQ extends bc{constructor(A){super(Dh,"level",0,(A=>A>0))}}class NQ extends kc{constructor(A){super(Dh,"linearized")}}class xQ extends Dc{constructor(A){super(Dh,"locale")}}class UQ extends Dc{constructor(A){super(Dh,"localeSet")}}class MQ extends dc{constructor(A){super(Dh,"log",!0),this.mode=null,this.threshold=null,this.to=null,this.uri=null}}class LQ extends dc{constructor(A){super(Dh,"map",!0),this.equate=new fc,this.equateRange=new fc}}class JQ extends dc{constructor(A){super(Dh,"mediumInfo",!0),this.map=null}}class HQ extends dc{constructor(A){super(Dh,"message",!0),this.msgId=null,this.severity=null}}class YQ extends dc{constructor(A){super(Dh,"messaging",!0),this.message=new fc}}class vQ extends wc{constructor(A){super(Dh,"mode",["append","overwrite"])}}class KQ extends kc{constructor(A){super(Dh,"modifyAnnots")}}class qQ extends bc{constructor(A){super(Dh,"msgId",1,(A=>A>=1))}}class TQ extends Dc{constructor(A){super(Dh,"nameAttr")}}class PQ extends yc{constructor(A){super(Dh,"neverEmbed")}}class WQ extends bc{constructor(A){super(Dh,"numberOfCopies",null,(A=>A>=2&&A<=5))}}class ZQ extends dc{constructor(A){super(Dh,"openAction",!0),this.destination=null}}class OQ extends dc{constructor(A){super(Dh,"output",!0),this.to=null,this.type=null,this.uri=null}}class XQ extends Dc{constructor(A){super(Dh,"outputBin")}}class VQ extends dc{constructor(A){super(Dh,"outputXSL",!0),this.uri=null}}class jQ extends wc{constructor(A){super(Dh,"overprint",["none","both","draw","field"])}}class zQ extends Dc{constructor(A){super(Dh,"packets")}[ko](){"*"!==this[yo]&&(this[yo]=this[yo].trim().split(/\s+/).filter((A=>["config","datasets","template","xfdf","xslt"].includes(A))))}}class _Q extends dc{constructor(A){super(Dh,"pageOffset"),this.x=xI({data:A.x,defaultValue:"useXDCSetting",validate:A=>!0}),this.y=xI({data:A.y,defaultValue:"useXDCSetting",validate:A=>!0})}}class $Q extends Dc{constructor(A){super(Dh,"pageRange")}[ko](){const A=this[yo].trim().split(/\s+/).map((A=>parseInt(A,10))),e=[];for(let t=0,i=A.length;t!1))}}class il extends dc{constructor(A){super(Dh,"pcl",!0),this.name=A.name||"",this.batchOutput=null,this.fontInfo=null,this.jog=null,this.mediumInfo=null,this.outputBin=null,this.pageOffset=null,this.staple=null,this.xdc=null}}class al extends dc{constructor(A){super(Dh,"pdf",!0),this.name=A.name||"",this.adobeExtensionLevel=null,this.batchOutput=null,this.compression=null,this.creator=null,this.encryption=null,this.fontInfo=null,this.interactive=null,this.linearized=null,this.openAction=null,this.pdfa=null,this.producer=null,this.renderPolicy=null,this.scriptModel=null,this.silentPrint=null,this.submitFormat=null,this.tagged=null,this.version=null,this.viewerPreferences=null,this.xdc=null}}class sl extends dc{constructor(A){super(Dh,"pdfa",!0),this.amd=null,this.conformance=null,this.includeXDPContent=null,this.part=null}}class nl extends dc{constructor(A){super(Dh,"permissions",!0),this.accessibleContent=null,this.change=null,this.contentCopy=null,this.documentAssembly=null,this.formFieldFilling=null,this.modifyAnnots=null,this.plaintextMetadata=null,this.print=null,this.printHighQuality=null}}class gl extends kc{constructor(A){super(Dh,"pickTrayByPDFSize")}}class rl extends Dc{constructor(A){super(Dh,"picture")}}class ol extends kc{constructor(A){super(Dh,"plaintextMetadata")}}class Il extends wc{constructor(A){super(Dh,"presence",["preserve","dissolve","dissolveStructure","ignore","remove"])}}class cl extends dc{constructor(A){super(Dh,"present",!0),this.behaviorOverride=null,this.cache=null,this.common=null,this.copies=null,this.destination=null,this.incrementalMerge=null,this.layout=null,this.output=null,this.overprint=null,this.pagination=null,this.paginationOverride=null,this.script=null,this.validate=null,this.xdp=null,this.driver=new fc,this.labelPrinter=new fc,this.pcl=new fc,this.pdf=new fc,this.ps=new fc,this.submitUrl=new fc,this.webClient=new fc,this.zpl=new fc}}class Cl extends kc{constructor(A){super(Dh,"print")}}class Bl extends kc{constructor(A){super(Dh,"printHighQuality")}}class hl extends wc{constructor(A){super(Dh,"printScaling",["appdefault","noScaling"])}}class Ql extends Dc{constructor(A){super(Dh,"printerName")}}class ll extends Dc{constructor(A){super(Dh,"producer")}}class El extends dc{constructor(A){super(Dh,"ps",!0),this.name=A.name||"",this.batchOutput=null,this.fontInfo=null,this.jog=null,this.mediumInfo=null,this.outputBin=null,this.staple=null,this.xdc=null}}class ul extends yc{constructor(A){super(Dh,"range")}[ko](){this[yo]=this[yo].trim().split(/\s*,\s*/,2).map((A=>A.split("-").map((A=>parseInt(A.trim(),10))))).filter((A=>A.every((A=>!isNaN(A))))).map((A=>(1===A.length&&A.push(A[0]),A)))}}class dl extends yc{constructor(A){super(Dh,"record")}[ko](){this[yo]=this[yo].trim();const A=parseInt(this[yo],10);!isNaN(A)&&A>=0&&(this[yo]=A)}}class fl extends yc{constructor(A){super(Dh,"relevant")}[ko](){this[yo]=this[yo].trim().split(/\s+/)}}class pl extends yc{constructor(A){super(Dh,"rename")}[ko](){this[yo]=this[yo].trim(),(this[yo].toLowerCase().startsWith("xml")||new RegExp("[\\p{L}_][\\p{L}\\d._\\p{M}-]*","u").test(this[yo]))&&N("XFA - Rename: invalid XFA name")}}class ml extends wc{constructor(A){super(Dh,"renderPolicy",["server","client"])}}class yl extends wc{constructor(A){super(Dh,"runScripts",["both","client","none","server"])}}class wl extends dc{constructor(A){super(Dh,"script",!0),this.currentPage=null,this.exclude=null,this.runScripts=null}}class Dl extends wc{constructor(A){super(Dh,"scriptModel",["XFA","none"])}}class bl extends wc{constructor(A){super(Dh,"severity",["ignore","error","information","trace","warning"])}}class kl extends dc{constructor(A){super(Dh,"silentPrint",!0),this.addSilentPrint=null,this.printerName=null}}class Fl extends dc{constructor(A){super(Dh,"staple"),this.mode=LI(A.mode,["usePrinterSetting","on","off"])}}class Sl extends Dc{constructor(A){super(Dh,"startNode")}}class Rl extends bc{constructor(A){super(Dh,"startPage",0,(A=>!0))}}class Gl extends wc{constructor(A){super(Dh,"submitFormat",["html","delegate","fdf","xml","pdf"])}}class Nl extends Dc{constructor(A){super(Dh,"submitUrl")}}class xl extends bc{constructor(A){super(Dh,"subsetBelow",100,(A=>A>=0&&A<=100))}}class Ul extends kc{constructor(A){super(Dh,"suppressBanner")}}class Ml extends kc{constructor(A){super(Dh,"tagged")}}class Ll extends dc{constructor(A){super(Dh,"template",!0),this.base=null,this.relevant=null,this.startPage=null,this.uri=null,this.xsl=null}}class Jl extends wc{constructor(A){super(Dh,"threshold",["trace","error","information","warning"])}}class Hl extends wc{constructor(A){super(Dh,"to",["null","memory","stderr","stdout","system","uri"])}}class Yl extends dc{constructor(A){super(Dh,"templateCache"),this.maxEntries=xI({data:A.maxEntries,defaultValue:5,validate:A=>A>=0})}}class vl extends dc{constructor(A){super(Dh,"trace",!0),this.area=new fc}}class Kl extends dc{constructor(A){super(Dh,"transform",!0),this.groupParent=null,this.ifEmpty=null,this.nameAttr=null,this.picture=null,this.presence=null,this.rename=null,this.whitespace=null}}class ql extends wc{constructor(A){super(Dh,"type",["none","ascii85","asciiHex","ccittfax","flate","lzw","runLength","native","xdp","mergedXDP"])}}class Tl extends Dc{constructor(A){super(Dh,"uri")}}class Pl extends wc{constructor(A){super(Dh,"validate",["preSubmit","prePrint","preExecute","preSave"])}}class Wl extends yc{constructor(A){super(Dh,"validateApprovalSignatures")}[ko](){this[yo]=this[yo].trim().split(/\s+/).filter((A=>["docReady","postSign"].includes(A)))}}class Zl extends wc{constructor(A){super(Dh,"validationMessaging",["allMessagesIndividually","allMessagesTogether","firstMessageOnly","noMessages"])}}class Ol extends wc{constructor(A){super(Dh,"version",["1.7","1.6","1.5","1.4","1.3","1.2"])}}class Xl extends dc{constructor(A){super(Dh,"VersionControl"),this.outputBelow=LI(A.outputBelow,["warn","error","update"]),this.sourceAbove=LI(A.sourceAbove,["warn","error"]),this.sourceBelow=LI(A.sourceBelow,["update","maintain"])}}class Vl extends dc{constructor(A){super(Dh,"viewerPreferences",!0),this.ADBE_JSConsole=null,this.ADBE_JSDebugger=null,this.addViewerPreferences=null,this.duplexOption=null,this.enforce=null,this.numberOfCopies=null,this.pageRange=null,this.pickTrayByPDFSize=null,this.printScaling=null}}class jl extends dc{constructor(A){super(Dh,"webClient",!0),this.name=A.name?A.name.trim():"",this.fontInfo=null,this.xdc=null}}class zl extends wc{constructor(A){super(Dh,"whitespace",["preserve","ltrim","normalize","rtrim","trim"])}}class _l extends yc{constructor(A){super(Dh,"window")}[ko](){const A=this[yo].trim().split(/\s*,\s*/,2).map((A=>parseInt(A,10)));A.some((A=>isNaN(A)))?this[yo]=[0,0]:(1===A.length&&A.push(A[0]),this[yo]=A)}}class $l extends dc{constructor(A){super(Dh,"xdc",!0),this.uri=new fc,this.xsl=new fc}}class AE extends dc{constructor(A){super(Dh,"xdp",!0),this.packets=null}}class eE extends dc{constructor(A){super(Dh,"xsl",!0),this.debug=null,this.uri=null}}class tE extends dc{constructor(A){super(Dh,"zpl",!0),this.name=A.name?A.name.trim():"",this.batchOutput=null,this.flipLabel=null,this.fontInfo=null,this.xdc=null}}class iE{static[FI](A,e){if(iE.hasOwnProperty(A))return iE[A](e)}static acrobat(A){return new bh(A)}static acrobat7(A){return new kh(A)}static ADBE_JSConsole(A){return new Fh(A)}static ADBE_JSDebugger(A){return new Sh(A)}static addSilentPrint(A){return new Rh(A)}static addViewerPreferences(A){return new Gh(A)}static adjustData(A){return new Nh(A)}static adobeExtensionLevel(A){return new xh(A)}static agent(A){return new Uh(A)}static alwaysEmbed(A){return new Mh(A)}static amd(A){return new Lh(A)}static area(A){return new Jh(A)}static attributes(A){return new Hh(A)}static autoSave(A){return new Yh(A)}static base(A){return new vh(A)}static batchOutput(A){return new Kh(A)}static behaviorOverride(A){return new qh(A)}static cache(A){return new Th(A)}static change(A){return new Ph(A)}static common(A){return new Wh(A)}static compress(A){return new Zh(A)}static compressLogicalStructure(A){return new Oh(A)}static compressObjectStream(A){return new Xh(A)}static compression(A){return new Vh(A)}static config(A){return new jh(A)}static conformance(A){return new zh(A)}static contentCopy(A){return new _h(A)}static copies(A){return new $h(A)}static creator(A){return new AQ(A)}static currentPage(A){return new eQ(A)}static data(A){return new tQ(A)}static debug(A){return new iQ(A)}static defaultTypeface(A){return new aQ(A)}static destination(A){return new sQ(A)}static documentAssembly(A){return new nQ(A)}static driver(A){return new gQ(A)}static duplexOption(A){return new rQ(A)}static dynamicRender(A){return new oQ(A)}static embed(A){return new IQ(A)}static encrypt(A){return new cQ(A)}static encryption(A){return new CQ(A)}static encryptionLevel(A){return new BQ(A)}static enforce(A){return new hQ(A)}static equate(A){return new QQ(A)}static equateRange(A){return new lQ(A)}static exclude(A){return new EQ(A)}static excludeNS(A){return new uQ(A)}static flipLabel(A){return new dQ(A)}static fontInfo(A){return new fQ(A)}static formFieldFilling(A){return new pQ(A)}static groupParent(A){return new mQ(A)}static ifEmpty(A){return new yQ(A)}static includeXDPContent(A){return new wQ(A)}static incrementalLoad(A){return new DQ(A)}static incrementalMerge(A){return new bQ(A)}static interactive(A){return new kQ(A)}static jog(A){return new FQ(A)}static labelPrinter(A){return new SQ(A)}static layout(A){return new RQ(A)}static level(A){return new GQ(A)}static linearized(A){return new NQ(A)}static locale(A){return new xQ(A)}static localeSet(A){return new UQ(A)}static log(A){return new MQ(A)}static map(A){return new LQ(A)}static mediumInfo(A){return new JQ(A)}static message(A){return new HQ(A)}static messaging(A){return new YQ(A)}static mode(A){return new vQ(A)}static modifyAnnots(A){return new KQ(A)}static msgId(A){return new qQ(A)}static nameAttr(A){return new TQ(A)}static neverEmbed(A){return new PQ(A)}static numberOfCopies(A){return new WQ(A)}static openAction(A){return new ZQ(A)}static output(A){return new OQ(A)}static outputBin(A){return new XQ(A)}static outputXSL(A){return new VQ(A)}static overprint(A){return new jQ(A)}static packets(A){return new zQ(A)}static pageOffset(A){return new _Q(A)}static pageRange(A){return new $Q(A)}static pagination(A){return new Al(A)}static paginationOverride(A){return new el(A)}static part(A){return new tl(A)}static pcl(A){return new il(A)}static pdf(A){return new al(A)}static pdfa(A){return new sl(A)}static permissions(A){return new nl(A)}static pickTrayByPDFSize(A){return new gl(A)}static picture(A){return new rl(A)}static plaintextMetadata(A){return new ol(A)}static presence(A){return new Il(A)}static present(A){return new cl(A)}static print(A){return new Cl(A)}static printHighQuality(A){return new Bl(A)}static printScaling(A){return new hl(A)}static printerName(A){return new Ql(A)}static producer(A){return new ll(A)}static ps(A){return new El(A)}static range(A){return new ul(A)}static record(A){return new dl(A)}static relevant(A){return new fl(A)}static rename(A){return new pl(A)}static renderPolicy(A){return new ml(A)}static runScripts(A){return new yl(A)}static script(A){return new wl(A)}static scriptModel(A){return new Dl(A)}static severity(A){return new bl(A)}static silentPrint(A){return new kl(A)}static staple(A){return new Fl(A)}static startNode(A){return new Sl(A)}static startPage(A){return new Rl(A)}static submitFormat(A){return new Gl(A)}static submitUrl(A){return new Nl(A)}static subsetBelow(A){return new xl(A)}static suppressBanner(A){return new Ul(A)}static tagged(A){return new Ml(A)}static template(A){return new Ll(A)}static templateCache(A){return new Yl(A)}static threshold(A){return new Jl(A)}static to(A){return new Hl(A)}static trace(A){return new vl(A)}static transform(A){return new Kl(A)}static type(A){return new ql(A)}static uri(A){return new Tl(A)}static validate(A){return new Pl(A)}static validateApprovalSignatures(A){return new Wl(A)}static validationMessaging(A){return new Zl(A)}static version(A){return new Ol(A)}static versionControl(A){return new Xl(A)}static viewerPreferences(A){return new Vl(A)}static webClient(A){return new jl(A)}static whitespace(A){return new zl(A)}static window(A){return new _l(A)}static xdc(A){return new $l(A)}static xdp(A){return new AE(A)}static xsl(A){return new eE(A)}static zpl(A){return new tE(A)}}const aE=SI.connectionSet.id;class sE extends dc{constructor(A){super(aE,"connectionSet",!0),this.wsdlConnection=new fc,this.xmlConnection=new fc,this.xsdConnection=new fc}}class nE extends dc{constructor(A){super(aE,"effectiveInputPolicy"),this.id=A.id||"",this.name=A.name||"",this.use=A.use||"",this.usehref=A.usehref||""}}class gE extends dc{constructor(A){super(aE,"effectiveOutputPolicy"),this.id=A.id||"",this.name=A.name||"",this.use=A.use||"",this.usehref=A.usehref||""}}class rE extends Dc{constructor(A){super(aE,"operation"),this.id=A.id||"",this.input=A.input||"",this.name=A.name||"",this.output=A.output||"",this.use=A.use||"",this.usehref=A.usehref||""}}class oE extends Dc{constructor(A){super(aE,"rootElement"),this.id=A.id||"",this.name=A.name||"",this.use=A.use||"",this.usehref=A.usehref||""}}class IE extends Dc{constructor(A){super(aE,"soapAction"),this.id=A.id||"",this.name=A.name||"",this.use=A.use||"",this.usehref=A.usehref||""}}class cE extends Dc{constructor(A){super(aE,"soapAddress"),this.id=A.id||"",this.name=A.name||"",this.use=A.use||"",this.usehref=A.usehref||""}}class CE extends Dc{constructor(A){super(aE,"uri"),this.id=A.id||"",this.name=A.name||"",this.use=A.use||"",this.usehref=A.usehref||""}}class BE extends Dc{constructor(A){super(aE,"wsdlAddress"),this.id=A.id||"",this.name=A.name||"",this.use=A.use||"",this.usehref=A.usehref||""}}class hE extends dc{constructor(A){super(aE,"wsdlConnection",!0),this.dataDescription=A.dataDescription||"",this.name=A.name||"",this.effectiveInputPolicy=null,this.effectiveOutputPolicy=null,this.operation=null,this.soapAction=null,this.soapAddress=null,this.wsdlAddress=null}}class QE extends dc{constructor(A){super(aE,"xmlConnection",!0),this.dataDescription=A.dataDescription||"",this.name=A.name||"",this.uri=null}}class lE extends dc{constructor(A){super(aE,"xsdConnection",!0),this.dataDescription=A.dataDescription||"",this.name=A.name||"",this.rootElement=null,this.uri=null}}class EE{static[FI](A,e){if(EE.hasOwnProperty(A))return EE[A](e)}static connectionSet(A){return new sE(A)}static effectiveInputPolicy(A){return new nE(A)}static effectiveOutputPolicy(A){return new gE(A)}static operation(A){return new rE(A)}static rootElement(A){return new oE(A)}static soapAction(A){return new IE(A)}static soapAddress(A){return new cE(A)}static uri(A){return new CE(A)}static wsdlAddress(A){return new BE(A)}static wsdlConnection(A){return new hE(A)}static xmlConnection(A){return new QE(A)}static xsdConnection(A){return new lE(A)}}const uE=SI.datasets.id;class dE extends mc{constructor(A){super(uE,"data",A)}[$o](){return!0}}class fE extends dc{constructor(A){super(uE,"datasets",!0),this.data=null,this.Signature=null}[rI](A){const e=A[nI];("data"===e&&A[sI]===uE||"Signature"===e&&A[sI]===SI.signature.id)&&(this[e]=A),this[Qo](A)}}class pE{static[FI](A,e){if(pE.hasOwnProperty(A))return pE[A](e)}static datasets(A){return new fE(A)}static data(A){return new dE(A)}}const mE=SI.localeSet.id;class yE extends dc{constructor(A){super(mE,"calendarSymbols",!0),this.name="gregorian",this.dayNames=new fc(2),this.eraNames=null,this.meridiemNames=null,this.monthNames=new fc(2)}}class wE extends Dc{constructor(A){super(mE,"currencySymbol"),this.name=LI(A.name,["symbol","isoname","decimal"])}}class DE extends dc{constructor(A){super(mE,"currencySymbols",!0),this.currencySymbol=new fc(3)}}class bE extends Dc{constructor(A){super(mE,"datePattern"),this.name=LI(A.name,["full","long","med","short"])}}class kE extends dc{constructor(A){super(mE,"datePatterns",!0),this.datePattern=new fc(4)}}class FE extends yc{constructor(A){super(mE,"dateTimeSymbols")}}class SE extends Dc{constructor(A){super(mE,"day")}}class RE extends dc{constructor(A){super(mE,"dayNames",!0),this.abbr=xI({data:A.abbr,defaultValue:0,validate:A=>1===A}),this.day=new fc(7)}}class GE extends Dc{constructor(A){super(mE,"era")}}class NE extends dc{constructor(A){super(mE,"eraNames",!0),this.era=new fc(2)}}class xE extends dc{constructor(A){super(mE,"locale",!0),this.desc=A.desc||"",this.name="isoname",this.calendarSymbols=null,this.currencySymbols=null,this.datePatterns=null,this.dateTimeSymbols=null,this.numberPatterns=null,this.numberSymbols=null,this.timePatterns=null,this.typeFaces=null}}class UE extends dc{constructor(A){super(mE,"localeSet",!0),this.locale=new fc}}class ME extends Dc{constructor(A){super(mE,"meridiem")}}class LE extends dc{constructor(A){super(mE,"meridiemNames",!0),this.meridiem=new fc(2)}}class JE extends Dc{constructor(A){super(mE,"month")}}class HE extends dc{constructor(A){super(mE,"monthNames",!0),this.abbr=xI({data:A.abbr,defaultValue:0,validate:A=>1===A}),this.month=new fc(12)}}class YE extends Dc{constructor(A){super(mE,"numberPattern"),this.name=LI(A.name,["full","long","med","short"])}}class vE extends dc{constructor(A){super(mE,"numberPatterns",!0),this.numberPattern=new fc(4)}}class KE extends Dc{constructor(A){super(mE,"numberSymbol"),this.name=LI(A.name,["decimal","grouping","percent","minus","zero"])}}class qE extends dc{constructor(A){super(mE,"numberSymbols",!0),this.numberSymbol=new fc(5)}}class TE extends Dc{constructor(A){super(mE,"timePattern"),this.name=LI(A.name,["full","long","med","short"])}}class PE extends dc{constructor(A){super(mE,"timePatterns",!0),this.timePattern=new fc(4)}}class WE extends dc{constructor(A){super(mE,"typeFace",!0),this.name=""|A.name}}class ZE extends dc{constructor(A){super(mE,"typeFaces",!0),this.typeFace=new fc}}class OE{static[FI](A,e){if(OE.hasOwnProperty(A))return OE[A](e)}static calendarSymbols(A){return new yE(A)}static currencySymbol(A){return new wE(A)}static currencySymbols(A){return new DE(A)}static datePattern(A){return new bE(A)}static datePatterns(A){return new kE(A)}static dateTimeSymbols(A){return new FE(A)}static day(A){return new SE(A)}static dayNames(A){return new RE(A)}static era(A){return new GE(A)}static eraNames(A){return new NE(A)}static locale(A){return new xE(A)}static localeSet(A){return new UE(A)}static meridiem(A){return new ME(A)}static meridiemNames(A){return new LE(A)}static month(A){return new JE(A)}static monthNames(A){return new HE(A)}static numberPattern(A){return new YE(A)}static numberPatterns(A){return new vE(A)}static numberSymbol(A){return new KE(A)}static numberSymbols(A){return new qE(A)}static timePattern(A){return new TE(A)}static timePatterns(A){return new PE(A)}static typeFace(A){return new WE(A)}static typeFaces(A){return new ZE(A)}}const XE=SI.signature.id;class VE extends dc{constructor(A){super(XE,"signature",!0)}}class jE{static[FI](A,e){if(jE.hasOwnProperty(A))return jE[A](e)}static signature(A){return new VE(A)}}const zE=SI.stylesheet.id;class _E extends dc{constructor(A){super(zE,"stylesheet",!0)}}class $E{static[FI](A,e){if($E.hasOwnProperty(A))return $E[A](e)}static stylesheet(A){return new _E(A)}}const Au=SI.xdp.id;class eu extends dc{constructor(A){super(Au,"xdp",!0),this.uuid=A.uuid||"",this.timeStamp=A.timeStamp||"",this.config=null,this.connectionSet=null,this.datasets=null,this.localeSet=null,this.stylesheet=new fc,this.template=null}[oI](A){const e=SI[A[nI]];return e&&A[sI]===e.id}}class tu{static[FI](A,e){if(tu.hasOwnProperty(A))return tu[A](e)}static xdp(A){return new eu(A)}}const iu=SI.xhtml.id,au=Symbol(),su=new Set(["color","font","font-family","font-size","font-stretch","font-style","font-weight","margin","margin-bottom","margin-left","margin-right","margin-top","letter-spacing","line-height","orphans","page-break-after","page-break-before","page-break-inside","tab-interval","tab-stop","text-align","text-decoration","text-indent","vertical-align","widows","kerning-mode","xfa-font-horizontal-scale","xfa-font-vertical-scale","xfa-spacerun","xfa-tab-stops"]),nu=new Map([["page-break-after","breakAfter"],["page-break-before","breakBefore"],["page-break-inside","breakInside"],["kerning-mode",A=>"none"===A?"none":"normal"],["xfa-font-horizontal-scale",A=>`scaleX(${Math.max(0,Math.min(parseInt(A)/100)).toFixed(2)})`],["xfa-font-vertical-scale",A=>`scaleY(${Math.max(0,Math.min(parseInt(A)/100)).toFixed(2)})`],["xfa-spacerun",""],["xfa-tab-stops",""],["font-size",(A,e)=>Sc(.99*(A=e.fontSize=JI(A)))],["letter-spacing",A=>Sc(JI(A))],["line-height",A=>Sc(JI(A))],["margin",A=>Sc(JI(A))],["margin-bottom",A=>Sc(JI(A))],["margin-left",A=>Sc(JI(A))],["margin-right",A=>Sc(JI(A))],["margin-top",A=>Sc(JI(A))],["text-indent",A=>Sc(JI(A))],["font-family",A=>A],["vertical-align",A=>Sc(JI(A))]]),gu=/\s+/g,ru=/[\r\n]+/g,ou=/\r\n?/g;function Iu(A,e,t){const i=Object.create(null);if(!A)return i;const a=Object.create(null);for(const[e,t]of A.split(";").map((A=>A.split(":",2)))){const A=nu.get(e);if(""===A)continue;let s=t;A&&(s="string"==typeof A?A:A(t,a)),e.endsWith("scale")?i.transform=i.transform?`${i[e]} ${s}`:s:i[e.replaceAll(/-([a-zA-Z])/g,((A,e)=>e.toUpperCase()))]=s}if(i.fontFamily&&Pc({typeface:i.fontFamily,weight:i.fontWeight||"normal",posture:i.fontStyle||"normal",size:a.fontSize||0},e,e[Po].fontFinder,i),t&&i.verticalAlign&&"0px"!==i.verticalAlign&&i.fontSize){const A=.583,e=.333,t=JI(i.fontSize);i.fontSize=Sc(t*A),i.verticalAlign=Sc(Math.sign(JI(i.verticalAlign))*t*e)}return t&&i.fontSize&&(i.fontSize=`calc(${i.fontSize} * var(--scale-factor))`),Yc(i),i}const cu=new Set(["body","html"]);class Cu extends mc{constructor(A,e){super(iu,e),this[au]=!1,this.style=A.style||""}[Eo](A){var e;super[Eo](A),this.style=(e=this).style?e.style.trim().split(/\s*;\s*/).filter((A=>!!A)).map((A=>A.split(/\s*:\s*/,2))).filter((([A,t])=>("font-family"===A&&e[Po].usedTypefaces.add(t),su.has(A)))).map((A=>A.join(":"))).join(";"):""}[Bo](){return!cu.has(this[nI])}[II](A,e=!1){e?this[au]=!0:(A=A.replaceAll(ru,""),this.style.includes("xfa-spacerun:yes")||(A=A.replaceAll(gu," "))),A&&(this[yo]+=A)}[cI](A,e=!0){const t=Object.create(null),i={top:NaN,bottom:NaN,left:NaN,right:NaN};let a=null;for(const[A,e]of this.style.split(";").map((A=>A.split(":",2))))switch(A){case"font-family":t.typeface=NI(e);break;case"font-size":t.size=JI(e);break;case"font-weight":t.weight=e;break;case"font-style":t.posture=e;break;case"letter-spacing":t.letterSpacing=JI(e);break;case"margin":const A=e.split(/ \t/).map((A=>JI(A)));switch(A.length){case 1:i.top=i.bottom=i.left=i.right=A[0];break;case 2:i.top=i.bottom=A[0],i.left=i.right=A[1];break;case 3:i.top=A[0],i.bottom=A[2],i.left=i.right=A[1];break;case 4:i.top=A[0],i.left=A[1],i.bottom=A[2],i.right=A[3]}break;case"margin-top":i.top=JI(e);break;case"margin-bottom":i.bottom=JI(e);break;case"margin-left":i.left=JI(e);break;case"margin-right":i.right=JI(e);break;case"line-height":a=JI(e)}if(A.pushData(t,i,a),this[yo])A.addString(this[yo]);else for(const e of this[Ho]())"#text"!==e[nI]?e[cI](A):A.addString(e[yo]);e&&A.popFont()}[wI](A){const e=[];if(this[bo]={children:e},this[lo]({}),0===e.length&&!this[yo])return vI.EMPTY;let t;return t=this[au]?this[yo]?this[yo].replaceAll(ou,"\n"):void 0:this[yo]||void 0,vI.success({name:this[nI],attributes:{href:this.href,style:Iu(this.style,this,this[au])},children:e,value:t})}}class Bu extends Cu{constructor(A){super(A,"a"),this.href=Wc(A.href)||""}}class hu extends Cu{constructor(A){super(A,"b")}[cI](A){A.pushFont({weight:"bold"}),super[cI](A),A.popFont()}}class Qu extends Cu{constructor(A){super(A,"body")}[wI](A){const e=super[wI](A),{html:t}=e;return t?(t.name="div",t.attributes.class=["xfaRich"],e):vI.EMPTY}}class lu extends Cu{constructor(A){super(A,"br")}[mI](){return"\n"}[cI](A){A.addString("\n")}[wI](A){return vI.success({name:"br"})}}class Eu extends Cu{constructor(A){super(A,"html")}[wI](A){const e=[];if(this[bo]={children:e},this[lo]({}),0===e.length)return vI.success({name:"div",attributes:{class:["xfaRich"],style:{}},value:this[yo]||""});if(1===e.length){const A=e[0];if(A.attributes?.class.includes("xfaRich"))return vI.success(A)}return vI.success({name:"div",attributes:{class:["xfaRich"],style:{}},children:e})}}class uu extends Cu{constructor(A){super(A,"i")}[cI](A){A.pushFont({posture:"italic"}),super[cI](A),A.popFont()}}class du extends Cu{constructor(A){super(A,"li")}}class fu extends Cu{constructor(A){super(A,"ol")}}class pu extends Cu{constructor(A){super(A,"p")}[cI](A){super[cI](A,!1),A.addString("\n"),A.addPara(),A.popFont()}[mI](){return this[qo]()[Ho]().at(-1)===this?super[mI]():super[mI]()+"\n"}}class mu extends Cu{constructor(A){super(A,"span")}}class yu extends Cu{constructor(A){super(A,"sub")}}class wu extends Cu{constructor(A){super(A,"sup")}}class Du extends Cu{constructor(A){super(A,"ul")}}class bu{static[FI](A,e){if(bu.hasOwnProperty(A))return bu[A](e)}static a(A){return new Bu(A)}static b(A){return new hu(A)}static body(A){return new Qu(A)}static br(A){return new lu(A)}static html(A){return new Eu(A)}static i(A){return new uu(A)}static li(A){return new du(A)}static ol(A){return new fu(A)}static p(A){return new pu(A)}static span(A){return new mu(A)}static sub(A){return new yu(A)}static sup(A){return new wu(A)}static ul(A){return new Du(A)}}const ku={config:iE,connection:EE,datasets:pE,localeSet:OE,signature:jE,stylesheet:$E,template:fh,xdp:tu,xhtml:bu};class Fu{constructor(A){this.namespaceId=A}[FI](A,e){return new mc(this.namespaceId,A,e)}}class Su extends dc{constructor(A){super(-1,"root",Object.create(null)),this.element=null,this[Zo]=A}[rI](A){return this.element=A,!0}[ko](){super[ko](),this.element.template instanceof rh&&(this[Zo].set(QI,this.element),this.element.template[lI](this[Zo]),this.element.template[Zo]=this[Zo])}}class Ru extends dc{constructor(){super(-1,"",Object.create(null))}[rI](A){return!1}}class Gu{constructor(A=null){this._namespaceStack=[],this._nsAgnosticLevel=0,this._namespacePrefixes=new Map,this._namespaces=new Map,this._nextNsId=Math.max(...Object.values(SI).map((({id:A})=>A))),this._currentNamespace=A||new Fu(++this._nextNsId)}buildRoot(A){return new Su(A)}build({nsPrefix:A,name:e,attributes:t,namespace:i,prefixes:a}){const s=null!==i;if(s&&(this._namespaceStack.push(this._currentNamespace),this._currentNamespace=this._searchNamespace(i)),a&&this._addNamespacePrefix(a),t.hasOwnProperty(gI)){const A=ku.datasets,e=t[gI];let i=null;for(const[t,a]of Object.entries(e))if(this._getNamespaceToUse(t)===A){i={xfa:a};break}i?t[gI]=i:delete t[gI]}const n=this._getNamespaceToUse(A),g=n?.[FI](e,t)||new Ru;return g[$o]()&&this._nsAgnosticLevel++,(s||a||g[$o]())&&(g[fo]={hasNamespace:s,prefixes:a,nsAgnostic:g[$o]()}),g}isNsAgnostic(){return this._nsAgnosticLevel>0}_searchNamespace(A){let e=this._namespaces.get(A);if(e)return e;for(const[t,{check:i}]of Object.entries(SI))if(i(A)){if(e=ku[t],e)return this._namespaces.set(A,e),e;break}return e=new Fu(++this._nextNsId),this._namespaces.set(A,e),e}_addNamespacePrefix(A){for(const{prefix:e,value:t}of A){const A=this._searchNamespace(t);let i=this._namespacePrefixes.get(e);i||(i=[],this._namespacePrefixes.set(e,i)),i.push(A)}}_getNamespaceToUse(A){if(!A)return this._currentNamespace;const e=this._namespacePrefixes.get(A);return e?.length>0?e.at(-1):(N(`Unknown namespace prefix: ${A}.`),null)}clean(A){const{hasNamespace:e,prefixes:t,nsAgnostic:i}=A;e&&(this._currentNamespace=this._namespaceStack.pop()),t&&t.forEach((({prefix:A})=>{this._namespacePrefixes.get(A).pop()})),i&&this._nsAgnosticLevel--}}class Nu extends Sr{constructor(A=null,e=!1){super(),this._builder=new Gu(A),this._stack=[],this._globalData={usedTypefaces:new Set},this._ids=new Map,this._current=this._builder.buildRoot(this._ids),this._errorCode=0,this._whiteRegex=/^\s+$/,this._nbsps=/\xa0+/g,this._richText=e}parse(A){if(this.parseXml(A),0===this._errorCode)return this._current[ko](),this._current.element}onText(A){A=A.replace(this._nbsps,(A=>A.slice(1)+" ")),this._richText||this._current[Bo]()?this._current[II](A,this._richText):this._whiteRegex.test(A)||this._current[II](A.trim())}onCdata(A){this._current[II](A)}_mkAttributes(A,e){let t=null,i=null;const a=Object.create({});for(const{name:s,value:n}of A)if("xmlns"===s)t?N(`XFA - multiple namespace definition in <${e}>`):t=n;else if(s.startsWith("xmlns:")){const A=s.substring(6);i||(i=[]),i.push({prefix:A,value:n})}else{const A=s.indexOf(":");if(-1===A)a[s]=n;else{let e=a[gI];e||(e=a[gI]=Object.create(null));const[t,i]=[s.slice(0,A),s.slice(A+1)];(e[t]||=Object.create(null))[i]=n}}return[t,i,a]}_getNameAndPrefix(A,e){const t=A.indexOf(":");return-1===t?[A,null]:[A.substring(t+1),e?"":A.substring(0,t)]}onBeginElement(A,e,t){const[i,a,s]=this._mkAttributes(e,A),[n,g]=this._getNameAndPrefix(A,this._builder.isNsAgnostic()),r=this._builder.build({nsPrefix:g,name:n,attributes:s,namespace:i,prefixes:a});if(r[Po]=this._globalData,t)return r[ko](),this._current[rI](r)&&r[uI](this._ids),void r[Eo](this._builder);this._stack.push(this._current),this._current=r}onEndElement(A){const e=this._current;if(e[Vo]()&&"string"==typeof e[yo]){const A=new Nu;A._globalData=this._globalData;const t=A.parse(e[yo]);e[yo]=null,e[rI](t)}e[ko](),this._current=this._stack.pop(),this._current[rI](e)&&e[uI](this._ids),e[Eo](this._builder)}onError(A){this._errorCode=A}}class xu{constructor(A){try{this.root=(new Nu).parse(xu._createDocument(A));const e=new yh(this.root);this.form=e.bind(),this.dataHandler=new wh(this.root,e.getData()),this.form[Po].template=this.form}catch(A){N(`XFA - an error occurred during parsing and binding: ${A}`)}}isValid(){return this.root&&this.form}_createPagesHelper(){const A=this.form[yI]();return new Promise(((e,t)=>{const i=()=>{try{const t=A.next();t.done?e(t.value):setTimeout(i,0)}catch(A){t(A)}};setTimeout(i,0)}))}async _createPages(){try{this.pages=await this._createPagesHelper(),this.dims=this.pages.children.map((A=>{const{width:e,height:t}=A.attributes.style;return[0,0,parseInt(e),parseInt(t)]}))}catch(A){N(`XFA - an error occurred during layout: ${A}`)}}getBoundingBox(A){return this.dims[A]}async getNumPages(){return this.pages||await this._createPages(),this.dims.length}setImages(A){this.form[Po].images=A}setFonts(A){this.form[Po].fontFinder=new KI(A);const e=[];for(let A of this.form[Po].usedTypefaces)A=NI(A),this.form[Po].fontFinder.find(A)||e.push(A);return e.length>0?e:null}appendFonts(A,e){this.form[Po].fontFinder.add(A,e)}async getPages(){this.pages||await this._createPages();const A=this.pages;return this.pages=null,A}serializeData(A){return this.dataHandler.serialize(A)}static _createDocument(A){return A["/xdp:xdp"]?Object.values(A).join(""):A["xdp:xdp"]}static getRichTextAsHtml(A){if(!A||"string"!=typeof A)return null;try{let e=new Nu(bu,!0).parse(A);if(!["body","xhtml"].includes(e[nI])){const A=bu.body({});A[Qo](e),e=A}const t=e[wI]();if(!t.success)return null;const{html:i}=t,{attributes:a}=i;return a&&(a.class&&(a.class=a.class.filter((A=>!A.startsWith("xfa")))),a.dir="auto"),{html:i,str:e[mI]()}}catch(A){N(`XFA - an error occurred during parsing of rich text: ${A}`)}return null}}class Uu{static createGlobals(A){return Promise.all([A.ensureCatalog("acroForm"),A.ensureDoc("xfaDatasets"),A.ensureCatalog("structTreeRoot"),A.ensureCatalog("baseUrl"),A.ensureCatalog("attachments")]).then((([e,t,i,a,s])=>({pdfManager:A,acroForm:e instanceof hA?e:hA.empty,xfaDatasets:t,structTreeRoot:i,baseUrl:a,attachments:s})),(A=>(N(`createGlobals: "${A}".`),null)))}static async create(A,e,t,i,a,s,n){const g=a?await this._getPageIndex(A,e,t.pdfManager):null;return t.pdfManager.ensure(this,"_create",[A,e,t,i,a,s,g,n])}static _create(A,e,t,i,a=!1,s=null,n=null,g=null){const r=A.fetchIfRef(e);if(!(r instanceof hA))return;const{acroForm:o,pdfManager:I}=t,c=e instanceof QA?e.toString():`annot_${i.createObjId()}`;let C=r.get("Subtype");C=C instanceof cA?C.name:null;const B={xref:A,ref:e,dict:r,subtype:C,id:c,annotationGlobals:t,collectFields:a,orphanFields:s,needAppearances:!a&&!0===o.get("NeedAppearances"),pageIndex:n,evaluatorOptions:I.evaluatorOptions,pageRef:g};switch(C){case"Link":return new Xu(B);case"Text":return new Ou(B);case"Widget":let A=RA({dict:r,key:"FT"});switch(A=A instanceof cA?A.name:null,A){case"Tx":return new Tu(B);case"Btn":return new Pu(B);case"Ch":return new Wu(B);case"Sig":return new Zu(B)}return N(`Unimplemented widget field type "${A}", falling back to base field type.`),new qu(B);case"Popup":return new Vu(B);case"FreeText":return new ju(B);case"Line":return new zu(B);case"Square":return new _u(B);case"Circle":return new $u(B);case"PolyLine":return new Ad(B);case"Polygon":return new ed(B);case"Caret":return new td(B);case"Ink":return new id(B);case"Highlight":return new ad(B);case"Underline":return new sd(B);case"Squiggly":return new nd(B);case"StrikeOut":return new gd(B);case"Stamp":return new rd(B);case"FileAttachment":return new od(B);default:return a||N(C?`Unimplemented annotation type "${C}", falling back to base annotation.`:"Annotation is missing the required /Subtype."),new Yu(B)}}static async _getPageIndex(A,e,t){try{const i=await A.fetchIfRefAsync(e);if(!(i instanceof hA))return-1;const a=i.getRaw("P");if(a instanceof QA)try{return await t.ensureCatalog("getPageIndex",[a])}catch(A){G(`_getPageIndex -- not a valid page reference: "${A}".`)}if(i.has("Kids"))return-1;const s=await t.ensureDoc("numPages");for(let A=0;AA/255))}function Ju(A,e){const t=A.getArray("QuadPoints");if(!HA(t,null)||0===t.length||t.length%8>0)return null;const i=new Float32Array(t.length);for(let A=0,a=t.length;Ae[2]||he[3]))return null;i.set([C,Q,B,Q,C,h,B,h],A)}return i}function Hu(A,e,t){const[i,a,s,n]=z.getAxialAlignedBoundingBox(e,t);if(i===s||a===n)return[1,0,0,1,A[0],A[1]];const g=(A[2]-A[0])/(s-i),r=(A[3]-A[1])/(n-a);return[g,0,0,r,A[0]-i*g,A[1]-a*r]}class Yu{constructor(A){const{dict:e,xref:t,annotationGlobals:i,ref:a,orphanFields:s}=A,n=s?.get(a);n&&e.set("Parent",n),this.setTitle(e.get("T")),this.setContents(e.get("Contents")),this.setModificationDate(e.get("M")),this.setFlags(e.get("F")),this.setRectangle(e.getArray("Rect")),this.setColor(e.getArray("C")),this.setBorderStyle(e),this.setAppearance(e),this.setOptionalContent(e);const g=e.get("MK");this.setBorderAndBackgroundColors(g),this.setRotation(g,e),this.ref=A.ref instanceof QA?A.ref:null,this._streams=[],this.appearance&&this._streams.push(this.appearance);const r=!!(128&this.flags),o=!!(512&this.flags);if(this.data={annotationFlags:this.flags,borderStyle:this.borderStyle,color:this.color,backgroundColor:this.backgroundColor,borderColor:this.borderColor,rotation:this.rotation,contentsObj:this._contents,hasAppearance:!!this.appearance,id:A.id,modificationDate:this.modificationDate,rect:this.rectangle,subtype:A.subtype,hasOwnCanvas:!1,noRotate:!!(16&this.flags),noHTML:r&&o,isEditable:!1,structParent:-1},i.structTreeRoot){let t=e.get("StructParent");this.data.structParent=t=Number.isInteger(t)&&t>=0?t:-1,i.structTreeRoot.addAnnotationIdToPage(A.pageRef,t)}if(A.collectFields){const i=e.get("Kids");if(Array.isArray(i)){const A=[];for(const e of i)e instanceof QA&&A.push(e.toString());0!==A.length&&(this.data.kidIds=A)}this.data.actions=ZA(t,e,B),this.data.fieldName=this._constructFieldName(e),this.data.pageIndex=A.pageIndex}const I=e.get("IT");I instanceof cA&&(this.data.it=I.name),this._isOffscreenCanvasSupported=A.evaluatorOptions.isOffscreenCanvasSupported,this._fallbackFontDict=null,this._needAppearances=!1}_hasFlag(A,e){return!!(A&e)}_buildFlags(A,e){let{flags:t}=this;if(void 0===A){if(void 0===e)return;return e?-5&t:-3&t|4}return A?(t|=4,e?-33&t|2:-3&t|I):(t&=-35,e?-5&t:4|t)}_isViewable(A){return!this._hasFlag(A,1)&&!this._hasFlag(A,I)}_isPrintable(A){return this._hasFlag(A,4)&&!this._hasFlag(A,2)&&!this._hasFlag(A,1)}mustBeViewed(A,e){const t=A?.get(this.data.id)?.noView;return void 0!==t?!t:this.viewable&&!this._hasFlag(this.flags,2)}mustBePrinted(A){const e=A?.get(this.data.id)?.noPrint;return void 0!==e?!e:this.printable}mustBeViewedWhenEditing(A,e=null){return A?!this.data.isEditable:!e?.has(this.data.id)}get viewable(){return null!==this.data.quadPoints&&(0===this.flags||this._isViewable(this.flags))}get printable(){return null!==this.data.quadPoints&&0!==this.flags&&this._isPrintable(this.flags)}_parseStringHelper(A){const e="string"==typeof A?$(A):"";return{str:e,dir:e&&"rtl"===Jg(e).dir?"rtl":"ltr"}}setDefaultAppearance(A){const{dict:e,annotationGlobals:t}=A,i=RA({dict:e,key:"DA"})||t.acroForm.get("DA");this._defaultAppearance="string"==typeof i?i:"",this.data.defaultAppearanceData=ur(this._defaultAppearance)}setTitle(A){this._title=this._parseStringHelper(A)}setContents(A){this._contents=this._parseStringHelper(A)}setModificationDate(A){this.modificationDate="string"==typeof A?A:null}setFlags(A){this.flags=Number.isInteger(A)&&A>0?A:0,1&this.flags&&"Annotation"!==this.constructor.name&&(this.flags^=1)}hasFlag(A){return this._hasFlag(this.flags,A)}setRectangle(A){this.rectangle=KA(A,[0,0,0,0])}setColor(A){this.color=Mu(A)}setLineEndings(A){if(this.lineEndings=["None","None"],Array.isArray(A)&&2===A.length)for(let e=0;e<2;e++){const t=A[e];if(t instanceof cA)switch(t.name){case"None":continue;case"Square":case"Circle":case"Diamond":case"OpenArrow":case"ClosedArrow":case"Butt":case"ROpenArrow":case"RClosedArrow":case"Slash":this.lineEndings[e]=t.name;continue}N(`Ignoring invalid lineEnding: ${t}`)}}setRotation(A,e){this.rotation=0;let t=A instanceof hA?A.get("R")||0:e.get("Rotate")||0;Number.isInteger(t)&&0!==t&&(t%=360,t<0&&(t+=360),t%90==0&&(this.rotation=t))}setBorderAndBackgroundColors(A){A instanceof hA?(this.borderColor=Mu(A.getArray("BC"),null),this.backgroundColor=Mu(A.getArray("BG"),null)):this.borderColor=this.backgroundColor=null}setBorderStyle(A){if(this.borderStyle=new vu,A instanceof hA)if(A.has("BS")){const e=A.get("BS");if(e instanceof hA){const A=e.get("Type");A&&!uA(A,"Border")||(this.borderStyle.setWidth(e.get("W"),this.rectangle),this.borderStyle.setStyle(e.get("S")),this.borderStyle.setDashArray(e.getArray("D")))}}else if(A.has("Border")){const e=A.getArray("Border");Array.isArray(e)&&e.length>=3&&(this.borderStyle.setHorizontalCornerRadius(e[0]),this.borderStyle.setVerticalCornerRadius(e[1]),this.borderStyle.setWidth(e[2],this.rectangle),4===e.length&&this.borderStyle.setDashArray(e[3],!0))}else this.borderStyle.setWidth(0)}setAppearance(A){this.appearance=null;const e=A.get("AP");if(!(e instanceof hA))return;const t=e.get("N");if(t instanceof mA)return void(this.appearance=t);if(!(t instanceof hA))return;const i=A.get("AS");if(!(i instanceof cA&&t.has(i.name)))return;const a=t.get(i.name);a instanceof mA&&(this.appearance=a)}setOptionalContent(A){this.oc=null;const e=A.get("OC");e instanceof cA?N("setOptionalContent: Support for /Name-entry is not implemented."):e instanceof hA&&(this.oc=e)}loadResources(A,e){return e.dict.getAsync("Resources").then((e=>{if(e)return new Co(e,A,e.xref).load().then((function(){return e}))}))}async getOperatorList(A,e,t,a){const{hasOwnCanvas:s,id:n,rect:g}=this.data;let r=this.appearance;const o=!!(s&&2&t);if(o&&(g[0]===g[2]||g[1]===g[3]))return this.data.hasOwnCanvas=!1,{opList:new tr,separateForm:!1,separateCanvas:!1};if(!r){if(!o)return{opList:new tr,separateForm:!1,separateCanvas:!1};r=new ge(""),r.dict=new hA}const I=r.dict,c=await this.loadResources(["ExtGState","ColorSpace","Pattern","Shading","XObject","Font"],r),C=vA(I.getArray("BBox"),[0,0,1,1]),B=YA(I.getArray("Matrix"),i),h=Hu(g,C,B),Q=new tr;let l;return this.oc&&(l=await A.parseMarkedContentProps(this.oc,null)),void 0!==l&&Q.addOp(D,["OC",l]),Q.addOp(80,[n,g,h,B,o]),await A.getOperatorList({stream:r,task:e,resources:c,operatorList:Q,fallbackFontDict:this._fallbackFontDict}),Q.addOp(81,[]),void 0!==l&&Q.addOp(b,[]),this.reset(),{opList:Q,separateForm:!1,separateCanvas:o}}async save(A,e,t){return null}get hasTextContent(){return!1}async extractTextContent(A,e,t){if(!this.appearance)return;const i=await this.loadResources(["ExtGState","Font","Properties","XObject"],this.appearance),a=[],s=[];let n=null;const g={desiredSize:Math.Infinity,ready:!0,enqueue(A,e){for(const e of A.items)void 0!==e.str&&(n||=e.transform.slice(-2),s.push(e.str),e.hasEOL&&(a.push(s.join("").trimEnd()),s.length=0))}};if(await A.getTextContent({stream:this.appearance,task:e,resources:i,includeMarkedContent:!0,keepWhiteSpace:!0,sink:g,viewBox:t}),this.reset(),s.length&&a.push(s.join("").trimEnd()),a.length>1||a[0]){const A=this.appearance.dict,e=vA(A.getArray("BBox"),null),t=YA(A.getArray("Matrix"),null);this.data.textPosition=this._transformPoint(n,e,t),this.data.textContent=a}}_transformPoint(A,e,t){const{rect:i}=this.data;e||=[0,0,1,1],t||=[1,0,0,1,0,0];const a=Hu(i,e,t);return a[4]-=i[0],a[5]-=i[1],A=z.applyTransform(A,a),z.applyTransform(A,t)}getFieldObject(){return this.data.kidIds?{id:this.data.id,actions:this.data.actions,name:this.data.fieldName,strokeColor:this.data.borderColor,fillColor:this.data.backgroundColor,type:"",kidIds:this.data.kidIds,page:this.data.pageIndex,rotation:this.rotation}:null}reset(){for(const A of this._streams)A.reset()}_constructFieldName(A){if(!A.has("T")&&!A.has("Parent"))return N("Unknown field name, falling back to empty field name."),"";if(!A.has("Parent"))return $(A.get("T"));const e=[];A.has("T")&&e.unshift($(A.get("T")));let t=A;const i=new lA;for(A.objId&&i.put(A.objId);t.has("Parent")&&(t=t.get("Parent"),t instanceof hA&&(!t.objId||!i.has(t.objId)));)t.objId&&i.put(t.objId),t.has("T")&&e.unshift($(t.get("T")));return e.join(".")}}class vu{constructor(){this.width=1,this.rawWidth=1,this.style=1,this.dashArray=[3],this.horizontalCornerRadius=0,this.verticalCornerRadius=0}setWidth(A,e=[0,0,0,0]){if(A instanceof cA)this.width=0;else if("number"==typeof A){if(A>0){this.rawWidth=A;const t=(e[2]-e[0])/2,i=(e[3]-e[1])/2;t>0&&i>0&&(A>t||A>i)&&(N(`AnnotationBorderStyle.setWidth - ignoring width: ${A}`),A=1)}this.width=A}}setStyle(A){if(A instanceof cA)switch(A.name){case"S":this.style=1;break;case"D":this.style=2;break;case"B":this.style=3;break;case"I":this.style=4;break;case"U":this.style=5}}setDashArray(A,e=!1){if(Array.isArray(A)){let t=!0,i=!0;for(const e of A){if(!(+e>=0)){t=!1;break}e>0&&(i=!1)}0===A.length||t&&!i?(this.dashArray=A,e&&this.setStyle(cA.get("D"))):this.width=0}else A&&(this.width=0)}setHorizontalCornerRadius(A){Number.isInteger(A)&&(this.horizontalCornerRadius=A)}setVerticalCornerRadius(A){Number.isInteger(A)&&(this.verticalCornerRadius=A)}}class Ku extends Yu{constructor(A){super(A);const{dict:e}=A;if(e.has("IRT")){const A=e.getRaw("IRT");this.data.inReplyTo=A instanceof QA?A.toString():null;const t=e.get("RT");this.data.replyType=t instanceof cA?t.name:"R"}let t=null;if(this.data.replyType===o){const A=e.get("IRT");this.setTitle(A.get("T")),this.data.titleObj=this._title,this.setContents(A.get("Contents")),this.data.contentsObj=this._contents,A.has("CreationDate")?(this.setCreationDate(A.get("CreationDate")),this.data.creationDate=this.creationDate):this.data.creationDate=null,A.has("M")?(this.setModificationDate(A.get("M")),this.data.modificationDate=this.modificationDate):this.data.modificationDate=null,t=A.getRaw("Popup"),A.has("C")?(this.setColor(A.getArray("C")),this.data.color=this.color):this.data.color=null}else this.data.titleObj=this._title,this.setCreationDate(e.get("CreationDate")),this.data.creationDate=this.creationDate,t=e.getRaw("Popup"),e.has("C")||(this.data.color=null);this.data.popupRef=t instanceof QA?t.toString():null,e.has("RC")&&(this.data.richText=xu.getRichTextAsHtml(e.get("RC")))}setCreationDate(A){this.creationDate="string"==typeof A?A:null}_setDefaultAppearance({xref:A,extra:e,strokeColor:t,fillColor:i,blendMode:a,strokeAlpha:s,fillAlpha:n,pointsCallback:g}){let r=Number.MAX_VALUE,o=Number.MAX_VALUE,I=Number.MIN_VALUE,c=Number.MIN_VALUE;const C=["q"];e&&C.push(e),t&&C.push(`${t[0]} ${t[1]} ${t[2]} RG`),i&&C.push(`${i[0]} ${i[1]} ${i[2]} rg`);let B=this.data.quadPoints;B||(B=Float32Array.from([this.rectangle[0],this.rectangle[3],this.rectangle[2],this.rectangle[3],this.rectangle[0],this.rectangle[1],this.rectangle[2],this.rectangle[1]]));for(let A=0,e=B.length;A"string"==typeof A)).map((A=>$(A))):A instanceof cA?$(A.name):"string"==typeof A?$(A):null}hasFieldFlag(A){return!!(this.data.fieldFlags&A)}_isViewable(A){return!0}mustBeViewed(A,e){return e?this.viewable:super.mustBeViewed(A,e)&&!this._hasFlag(this.flags,I)}getRotationMatrix(A){let e=A?.get(this.data.id)?.rotation;return void 0===e&&(e=this.rotation),0===e?i:ae(e,this.data.rect[2]-this.data.rect[0],this.data.rect[3]-this.data.rect[1])}getBorderAndBackgroundAppearances(A){let e=A?.get(this.data.id)?.rotation;if(void 0===e&&(e=this.rotation),!this.backgroundColor&&!this.borderColor)return"";const t=this.data.rect[2]-this.data.rect[0],i=this.data.rect[3]-this.data.rect[1],a=0===e||180===e?`0 0 ${t} ${i} re`:`0 0 ${i} ${t} re`;let s="";return this.backgroundColor&&(s=`${fr(this.backgroundColor,!0)} ${a} f `),this.borderColor&&(s+=`${this.borderStyle.width||1} w ${fr(this.borderColor,!1)} ${a} S `),s}async getOperatorList(A,e,t,i){if(16&t&&!(this instanceof Zu)&&!this.data.noHTML&&!this.data.hasOwnCanvas)return{opList:new tr,separateForm:!0,separateCanvas:!1};if(!this._hasText)return super.getOperatorList(A,e,t,i);const a=await this._getAppearance(A,e,t,i);if(this.appearance&&null===a)return super.getOperatorList(A,e,t,i);const s=new tr;if(!this._defaultAppearance||null===a)return{opList:s,separateForm:!1,separateCanvas:!1};const n=!!(this.data.hasOwnCanvas&&2&t),g=[0,0,this.data.rect[2]-this.data.rect[0],this.data.rect[3]-this.data.rect[1]],r=Hu(this.data.rect,g,[1,0,0,1,0,0]);let o;this.oc&&(o=await A.parseMarkedContentProps(this.oc,null)),void 0!==o&&s.addOp(D,["OC",o]),s.addOp(80,[this.data.id,this.data.rect,r,this.getRotationMatrix(i),n]);const I=new ge(a);return await A.getOperatorList({stream:I,task:e,resources:this._fieldResources.mergedResources,operatorList:s}),s.addOp(81,[]),void 0!==o&&s.addOp(b,[]),{opList:s,separateForm:!1,separateCanvas:n}}_getMKDict(A){const e=new hA(null);return A&&e.set("R",A),this.borderColor&&e.set("BC",Lu(this.borderColor)),this.backgroundColor&&e.set("BG",Lu(this.backgroundColor)),e.size>0?e:null}amendSavedDict(A,e){}async save(A,e,t){const a=t?.get(this.data.id),s=this._buildFlags(a?.noView,a?.noPrint);let n=a?.value,g=a?.rotation;if(n===this.data.fieldValue||void 0===n){if(!this._hasValueFromXFA&&void 0===g&&void 0===s)return null;n||=this.data.fieldValue}if(void 0===g&&!this._hasValueFromXFA&&Array.isArray(n)&&Array.isArray(this.data.fieldValue)&&tA(n,this.data.fieldValue)&&void 0===s)return null;void 0===g&&(g=this.rotation);let r=null;if(!this._needAppearances&&(r=await this._getAppearance(A,e,8,t),null===r&&void 0===s))return null;let o=!1;r?.needAppearances&&(o=!0,r=null);const{xref:I}=A,c=I.fetchIfRef(this.ref);if(!(c instanceof hA))return null;const C=new hA(I);for(const A of c.getKeys())"AP"!==A&&C.set(A,c.getRaw(A));if(void 0!==s&&(C.set("F",s),null===r&&!o)){const A=c.getRaw("AP");A&&C.set("AP",A)}const B={path:this.data.fieldName,value:n};C.set("V",Array.isArray(n)?n.map(ee):ee(n)),this.amendSavedDict(t,C);const h=this._getMKDict(g);h&&C.set("MK",h);const Q=[],l=[{ref:this.ref,data:"",xfa:B,needAppearances:o}];if(null!==r){const A=I.getNewTemporaryRef(),e=new hA(I);C.set("AP",e),e.set("N",A);const a=this._getSaveFieldResources(I),s=new ge(r),n=s.dict=new hA(I);n.set("Subtype",cA.get("Form")),n.set("Resources",a),n.set("BBox",[0,0,this.data.rect[2]-this.data.rect[0],this.data.rect[3]-this.data.rect[1]]);const g=this.getRotationMatrix(t);g!==i&&n.set("Matrix",g),await Or(A,s,Q,I),l.push({ref:A,data:Q.join(""),xfa:null,needAppearances:!1}),Q.length=0}return C.set("M",`D:${iA()}`),await Or(this.ref,C,Q,I),l[0].data=Q.join(""),l}async _getAppearance(A,e,t,i){if(this.hasFieldFlag(c))return null;const a=i?.get(this.data.id);let s,g;if(a&&(s=a.formattedValue||a.value,g=a.rotation),void 0===g&&void 0===s&&!this._needAppearances&&(!this._hasValueFromXFA||this.appearance))return null;const r=this.getBorderAndBackgroundAppearances(i);if(void 0===s&&(s=this.data.fieldValue,!s))return`/Tx BMC q ${r}Q EMC`;if(Array.isArray(s)&&1===s.length&&(s=s[0]),U("string"==typeof s,"Expected `value` to be a string."),s=s.trimEnd(),this.data.combo){const A=this.data.options.find((({exportValue:A})=>s===A));s=A?.displayValue||s}if(""===s)return`/Tx BMC q ${r}Q EMC`;void 0===g&&(g=this.rotation);let o,I=-1;this.data.multiLine?(o=s.split(/\r\n?|\n/).map((A=>A.normalize("NFC"))),I=o.length):o=[s.replace(/\r\n?|\n/,"").normalize("NFC")];let C=this.data.rect[3]-this.data.rect[1],B=this.data.rect[2]-this.data.rect[0];90!==g&&270!==g||([B,C]=[C,B]),this._defaultAppearance||(this.data.defaultAppearanceData=ur(this._defaultAppearance="/Helvetica 0 Tf 0 g"));let h,Q,l,E=await qu._getFontData(A,e,this.data.defaultAppearanceData,this._fieldResources.mergedResources);const u=[];let d=!1;for(const A of o){const e=E.encodeString(A);e.length>1&&(d=!0),u.push(e.join(""))}if(d&&8&t)return{needAppearances:!0};if(d&&this._isOffscreenCanvasSupported){const t=this.data.comb?"monospace":"sans-serif",i=new pr(A.xref,t),a=i.createFontResources(o.join("")),n=a.getRaw("Font");if(this._fieldResources.mergedResources.has("Font")){const A=this._fieldResources.mergedResources.get("Font");for(const e of n.getKeys())A.set(e,n.getRaw(e))}else this._fieldResources.mergedResources.set("Font",n);const g=i.fontName.name;E=await qu._getFontData(A,e,{fontName:g,fontSize:0},a);for(let A=0,e=u.length;A2?`/Tx BMC q ${r}BT `+h+` 1 0 0 1 ${$A(2)} ${$A(y)} Tm (${PA(u[0])}) Tj ET Q EMC`:`/Tx BMC q ${r}BT `+h+` 1 0 0 1 0 0 Tm ${this._renderText(u[0],E,Q,B,m,{shift:0},2,y)} ET Q EMC`}static async _getFontData(A,e,t,i){const a=new tr,s={font:null,clone(){return this}},{fontName:n,fontSize:g}=t;return await A.handleSetFont(i,[n&&cA.get(n),g],null,a,e,s,null),s.font}_getTextWidth(A,e){return e.charsToGlyphs(A).reduce(((A,e)=>A+e.width),0)/1e3}_computeFontSize(A,e,t,i,a){let{fontSize:n}=this.data.defaultAppearanceData,g=(n||12)*s,r=Math.round(A/g);if(!n){const o=A=>Math.floor(100*A)/100;if(-1===a){const a=this._getTextWidth(t,i);n=o(Math.min(A/s,e/a)),r=1}else{const I=t.split(/\r\n?|\n/),c=[];for(const A of I){const e=i.encodeString(A).join(""),t=i.charsToGlyphs(e),a=i.getCharPositions(e);c.push({line:e,glyphs:t,positions:a})}const C=t=>{let a=0;for(const s of c)if(a+=this._splitLine(null,i,t,e,s).length*t,a>A)return!0;return!1};for(r=Math.max(r,a);g=A/r,n=o(g/s),C(n);)r++}const{fontName:I,fontColor:c}=this.data.defaultAppearanceData;this._defaultAppearance=function({fontSize:A,fontName:e,fontColor:t}){return`/${TA(e)} ${A} Tf ${fr(t,!0)}`}({fontSize:n,fontName:I,fontColor:c})}return[this._defaultAppearance,n,A/r]}_renderText(A,e,t,i,a,s,n,g){let r;r=1===a?(i-this._getTextWidth(A,e)*t)/2:2===a?i-this._getTextWidth(A,e)*t-n:n;const o=$A(r-s.shift);return s.shift=r,`${o} ${g=$A(g)} Td (${PA(A)}) Tj`}_getSaveFieldResources(A){const{localResources:e,appearanceResources:t,acroFormResources:i}=this._fieldResources,a=this.data.defaultAppearanceData?.fontName;if(!a)return e||hA.empty;for(const A of[e,t])if(A instanceof hA){const e=A.get("Font");if(e instanceof hA&&e.has(a))return A}if(i instanceof hA){const t=i.get("Font");if(t instanceof hA&&t.has(a)){const i=new hA(A);i.set(a,t.getRaw(a));const s=new hA(A);return s.set("Font",i),hA.merge({xref:A,dictArray:[s,e],mergeSubDicts:!0})}}return e||hA.empty}getFieldObject(){return null}}class Tu extends qu{constructor(A){super(A);const{dict:e}=A;e.has("PMD")&&(this.flags|=2,this.data.hidden=!0,N("Barcodes are not supported")),this.data.hasOwnCanvas=this.data.readOnly&&!this.data.noHTML,this._hasText=!0,"string"!=typeof this.data.fieldValue&&(this.data.fieldValue="");let t=RA({dict:e,key:"Q"});(!Number.isInteger(t)||t<0||t>2)&&(t=null),this.data.textAlignment=t;let i=RA({dict:e,key:"MaxLen"});(!Number.isInteger(i)||i<0)&&(i=0),this.data.maxLen=i,this.data.multiLine=this.hasFieldFlag(4096),this.data.comb=this.hasFieldFlag(16777216)&&!this.hasFieldFlag(4096)&&!this.hasFieldFlag(c)&&!this.hasFieldFlag(1048576)&&0!==this.data.maxLen,this.data.doNotScroll=this.hasFieldFlag(8388608)}get hasTextContent(){return!!this.appearance&&!this._needAppearances}_getCombAppearance(A,e,t,i,a,s,n,g,r,o,I){const c=a/this.data.maxLen,C=this.getBorderAndBackgroundAppearances(I),B=[],h=e.getCharPositions(t);for(const[A,e]of h)B.push(`(${PA(t.substring(A,e))}) Tj`);const Q=B.join(` ${$A(c)} 0 Td `);return`/Tx BMC q ${C}BT `+A+` 1 0 0 1 ${$A(n)} ${$A(g+r)} Tm ${Q} ET Q EMC`}_getMultilineAppearance(A,e,t,i,a,s,n,g,r,o,I,c){const C=[],B=a-2*g,h={shift:0};for(let A=0,s=e.length;Ai?(r.push(A.substring(C,t)),C=t,B=Q,o=-1,c=-1):(B+=Q,o=t,I=a,c=e):B+Q>i?-1!==o?(r.push(A.substring(C,I)),C=I,e=c+1,o=-1,B=0):(r.push(A.substring(C,t)),C=t,B=Q):B+=Q}return Ce?`\\${e}`:"\\s+"));new RegExp(`^\\s*${s}\\s*$`).test(this.data.fieldValue)&&(this.data.textContent=this.data.fieldValue.split("\n"))}getFieldObject(){return{id:this.data.id,value:this.data.fieldValue,defaultValue:this.data.defaultFieldValue||"",multiline:this.data.multiLine,password:this.hasFieldFlag(c),charLimit:this.data.maxLen,comb:this.data.comb,editable:!this.data.readOnly,hidden:this.data.hidden,name:this.data.fieldName,rect:this.data.rect,actions:this.data.actions,page:this.data.pageIndex,strokeColor:this.data.borderColor,fillColor:this.data.backgroundColor,rotation:this.rotation,type:"text"}}}class Pu extends qu{constructor(A){super(A),this.checkedAppearance=null,this.uncheckedAppearance=null,this.data.checkBox=!this.hasFieldFlag(32768)&&!this.hasFieldFlag(C),this.data.radioButton=this.hasFieldFlag(32768)&&!this.hasFieldFlag(C),this.data.pushButton=this.hasFieldFlag(C),this.data.isTooltipOnly=!1,this.data.checkBox?this._processCheckBox(A):this.data.radioButton?this._processRadioButton(A):this.data.pushButton?(this.data.hasOwnCanvas=!0,this.data.noHTML=!1,this._processPushButton(A)):N("Invalid field flags for button widget annotation")}async getOperatorList(A,e,t,a){if(this.data.pushButton)return super.getOperatorList(A,e,t,!1,a);let s=null,n=null;if(a){const A=a.get(this.data.id);s=A?A.value:null,n=A?A.rotation:null}if(null===s&&this.appearance)return super.getOperatorList(A,e,t,a);null==s&&(s=this.data.checkBox?this.data.fieldValue===this.data.exportValue:this.data.fieldValue===this.data.buttonValue);const g=s?this.checkedAppearance:this.uncheckedAppearance;if(g){const s=this.appearance,r=YA(g.dict.getArray("Matrix"),i);n&&g.dict.set("Matrix",this.getRotationMatrix(a)),this.appearance=g;const o=super.getOperatorList(A,e,t,a);return this.appearance=s,g.dict.set("Matrix",r),o}return{opList:new tr,separateForm:!1,separateCanvas:!1}}async save(A,e,t){return this.data.checkBox?this._saveCheckbox(A,e,t):this.data.radioButton?this._saveRadioButton(A,e,t):null}async _saveCheckbox(A,e,t){if(!t)return null;const i=t.get(this.data.id),a=this._buildFlags(i?.noView,i?.noPrint);let s=i?.rotation,n=i?.value;if(void 0===s&&void 0===a){if(void 0===n)return null;if(this.data.fieldValue===this.data.exportValue===n)return null}let g=A.xref.fetchIfRef(this.ref);if(!(g instanceof hA))return null;g=g.clone(),void 0===s&&(s=this.rotation),void 0===n&&(n=this.data.fieldValue===this.data.exportValue);const r={path:this.data.fieldName,value:n?this.data.exportValue:""},o=cA.get(n?this.data.exportValue:"Off");g.set("V",o),g.set("AS",o),g.set("M",`D:${iA()}`),void 0!==a&&g.set("F",a);const I=this._getMKDict(s);I&&g.set("MK",I);const c=[];return await Or(this.ref,g,c,A.xref),[{ref:this.ref,data:c.join(""),xfa:r}]}async _saveRadioButton(A,e,t){if(!t)return null;const i=t.get(this.data.id),a=this._buildFlags(i?.noView,i?.noPrint);let s=i?.rotation,n=i?.value;if(void 0===s&&void 0===a){if(void 0===n)return null;if(this.data.fieldValue===this.data.buttonValue===n)return null}let g=A.xref.fetchIfRef(this.ref);if(!(g instanceof hA))return null;g=g.clone(),void 0===n&&(n=this.data.fieldValue===this.data.buttonValue),void 0===s&&(s=this.rotation);const r={path:this.data.fieldName,value:n?this.data.buttonValue:""},o=cA.get(n?this.data.buttonValue:"Off"),I=[];let c=null;if(n)if(this.parent instanceof QA){const e=A.xref.fetch(this.parent);e.set("V",o),await Or(this.parent,e,I,A.xref),c=I.join(""),I.length=0}else this.parent instanceof hA&&this.parent.set("V",o);this.parent||g.set("V",o),g.set("AS",o),g.set("M",`D:${iA()}`),void 0!==a&&g.set("F",a);const C=this._getMKDict(s);C&&g.set("MK",C),await Or(this.ref,g,I,A.xref);const B=[{ref:this.ref,data:I.join(""),xfa:r}];return c&&B.push({ref:this.parent,data:c,xfa:null}),B}_getDefaultCheckedAppearance(A,e){const t=this.data.rect[2]-this.data.rect[0],i=this.data.rect[3]-this.data.rect[1],a=[0,0,t,i],s=.8*Math.min(t,i);let n,g;"check"===e?(n={width:.755*s,height:.705*s},g="3"):"disc"===e?(n={width:.791*s,height:.705*s},g="l"):x(`_getDefaultCheckedAppearance - unsupported type: ${e}`);const r=`q BT /PdfJsZaDb ${s} Tf 0 g ${$A((t-n.width)/2)} ${$A((i-n.height)/2)} Td (${g}) Tj ET Q`,o=new hA(A.xref);o.set("FormType",1),o.set("Subtype",cA.get("Form")),o.set("Type",cA.get("XObject")),o.set("BBox",a),o.set("Matrix",[1,0,0,1,0,0]),o.set("Length",r.length);const I=new hA(A.xref),c=new hA(A.xref);c.set("PdfJsZaDb",this.fallbackFontDict),I.set("Font",c),o.set("Resources",I),this.checkedAppearance=new ge(r),this.checkedAppearance.dict=o,this._streams.push(this.checkedAppearance)}_processCheckBox(A){const e=A.dict.get("AP");if(!(e instanceof hA))return;const t=e.get("N");if(!(t instanceof hA))return;const i=this._decodeFormValue(A.dict.get("AS"));"string"==typeof i&&(this.data.fieldValue=i);const a=null!==this.data.fieldValue&&"Off"!==this.data.fieldValue?this.data.fieldValue:"Yes",s=t.getKeys();if(0===s.length)s.push("Off",a);else if(1===s.length)"Off"===s[0]?s.push(a):s.unshift("Off");else if(s.includes(a))s.length=0,s.push("Off",a);else{const A=s.find((A=>"Off"!==A));s.length=0,s.push("Off",A)}s.includes(this.data.fieldValue)||(this.data.fieldValue="Off"),this.data.exportValue=s[1];const n=t.get(this.data.exportValue);this.checkedAppearance=n instanceof mA?n:null;const g=t.get("Off");this.uncheckedAppearance=g instanceof mA?g:null,this.checkedAppearance?this._streams.push(this.checkedAppearance):this._getDefaultCheckedAppearance(A,"check"),this.uncheckedAppearance&&this._streams.push(this.uncheckedAppearance),this._fallbackFontDict=this.fallbackFontDict,null===this.data.defaultFieldValue&&(this.data.defaultFieldValue="Off")}_processRadioButton(A){this.data.buttonValue=null;const e=A.dict.get("Parent");if(e instanceof hA){this.parent=A.dict.getRaw("Parent");const t=e.get("V");t instanceof cA&&(this.data.fieldValue=this._decodeFormValue(t))}const t=A.dict.get("AP");if(!(t instanceof hA))return;const i=t.get("N");if(!(i instanceof hA))return;for(const A of i.getKeys())if("Off"!==A){this.data.buttonValue=this._decodeFormValue(A);break}const a=i.get(this.data.buttonValue);this.checkedAppearance=a instanceof mA?a:null;const s=i.get("Off");this.uncheckedAppearance=s instanceof mA?s:null,this.checkedAppearance?this._streams.push(this.checkedAppearance):this._getDefaultCheckedAppearance(A,"disc"),this.uncheckedAppearance&&this._streams.push(this.uncheckedAppearance),this._fallbackFontDict=this.fallbackFontDict,null===this.data.defaultFieldValue&&(this.data.defaultFieldValue="Off")}_processPushButton(A){const{dict:e,annotationGlobals:t}=A;e.has("A")||e.has("AA")||this.data.alternativeText?(this.data.isTooltipOnly=!e.has("A")&&!e.has("AA"),Io.parseDestDictionary({destDict:e,resultObj:this.data,docBaseUrl:t.baseUrl,docAttachments:t.attachments})):N("Push buttons without action dictionaries are not supported")}getFieldObject(){let A,e="button";return this.data.checkBox?(e="checkbox",A=this.data.exportValue):this.data.radioButton&&(e="radiobutton",A=this.data.buttonValue),{id:this.data.id,value:this.data.fieldValue||"Off",defaultValue:this.data.defaultFieldValue,exportValues:A,editable:!this.data.readOnly,name:this.data.fieldName,rect:this.data.rect,hidden:this.data.hidden,actions:this.data.actions,page:this.data.pageIndex,strokeColor:this.data.borderColor,fillColor:this.data.backgroundColor,rotation:this.rotation,type:e}}get fallbackFontDict(){const A=new hA;return A.set("BaseFont",cA.get("ZapfDingbats")),A.set("Type",cA.get("FallbackType")),A.set("Subtype",cA.get("FallbackType")),A.set("Encoding",cA.get("ZapfDingbatsEncoding")),L(this,"fallbackFontDict",A)}}class Wu extends qu{constructor(A){super(A);const{dict:e,xref:t}=A;this.indices=e.getArray("I"),this.hasIndices=Array.isArray(this.indices)&&this.indices.length>0,this.data.options=[];const i=RA({dict:e,key:"Opt"});if(Array.isArray(i))for(let A=0,e=i.length;A=0&&e0?this.data.fieldValue[0]:null;return{id:this.data.id,value:e,defaultValue:this.data.defaultFieldValue,editable:!this.data.readOnly,name:this.data.fieldName,rect:this.data.rect,numItems:this.data.fieldValue.length,multipleSelection:this.data.multiSelect,hidden:this.data.hidden,actions:this.data.actions,items:this.data.options,page:this.data.pageIndex,strokeColor:this.data.borderColor,fillColor:this.data.backgroundColor,rotation:this.rotation,type:A}}amendSavedDict(A,e){if(!this.hasIndices)return;let t=A?.get(this.data.id)?.value;Array.isArray(t)||(t=[t]);const i=[],{options:a}=this.data;for(let A=0,e=0,s=a.length;At&&(t=i,e=A)}[B,h]=this._computeFontSize(A,o-4,e,C,-1)}const Q=h*s,l=(Q-h)/2,E=Math.floor(r/Q);let u=0;if(c.length>0){const A=Math.min(...c),e=Math.max(...c);u=Math.max(0,e-E+1),u>A&&(u=A)}const d=Math.min(u+E+1,I),f=["/Tx BMC q",`1 1 ${o} ${r} re W n`];if(c.length){f.push("0.600006 0.756866 0.854904 rg");for(const A of c)u<=A&&AA.trimEnd()));const{coords:A,bbox:e,matrix:t}=pr.getFirstPositionInfo(this.rectangle,this.rotation,i);this.data.textPosition=this._transformPoint(A,e,t)}if(this._isOffscreenCanvasSupported){const a=A.dict.get("CA"),s=new pr(t,"sans-serif");this.appearance=s.createAppearance(this._contents.str,this.rectangle,this.rotation,i,e,a),this._streams.push(this.appearance)}else N("FreeTextAnnotation: OffscreenCanvas is not supported, annotation may not render correctly.")}}get hasTextContent(){return this._hasAppearance}static createNewDict(A,e,{apRef:t,ap:i}){const{color:a,fontSize:s,oldAnnotation:n,rect:g,rotation:r,user:o,value:I}=A,c=n||new hA(e);c.set("Type",cA.get("Annot")),c.set("Subtype",cA.get("FreeText")),n?(c.set("M",`D:${iA()}`),c.delete("RC")):c.set("CreationDate",`D:${iA()}`),c.set("Rect",g);const C=`/Helv ${s} Tf ${fr(a,!0)}`;if(c.set("DA",C),c.set("Contents",ee(I)),c.set("F",4),c.set("Border",[0,0,0]),c.set("Rotate",r),o&&c.set("T",ee(o)),t||i){const A=new hA(e);c.set("AP",A),t?A.set("N",t):A.set("N",i)}return c}static async createNewAppearanceStream(A,e,t){const{baseFontRef:i,evaluator:a,task:n}=t,{color:g,fontSize:r,rect:o,rotation:I,value:c}=A,C=new hA(e),B=new hA(e);if(i)B.set("Helv",i);else{const A=new hA(e);A.set("BaseFont",cA.get("Helvetica")),A.set("Type",cA.get("Font")),A.set("Subtype",cA.get("Type1")),A.set("Encoding",cA.get("WinAnsiEncoding")),B.set("Helv",A)}C.set("Font",B);const h=await qu._getFontData(a,n,{fontName:"Helv",fontSize:r},C),[Q,l,E,u]=o;let d=E-Q,f=u-l;I%180!=0&&([d,f]=[f,d]);const p=c.split("\n"),m=r/1e3;let y=-1/0;const w=[];for(let A of p){const e=h.encodeString(A);if(e.length>1)return null;A=e.join(""),w.push(A);let t=0;const i=h.charsToGlyphs(A);for(const A of i)t+=A.width*m;y=Math.max(y,t)}let D=1;y>d&&(D=d/y);let b=1;const k=s*r,F=1*r,S=k*p.length;S>f&&(b=f/S);const R=r*Math.min(D,b);let G,N,x;switch(I){case 0:x=[1,0,0,1],N=[o[0],o[1],d,f],G=[o[0],o[3]-F];break;case 90:x=[0,1,-1,0],N=[o[1],-o[2],d,f],G=[o[1],-o[0]-F];break;case 180:x=[-1,0,0,-1],N=[-o[2],-o[3],d,f],G=[-o[2],-o[1]-F];break;case 270:x=[0,-1,1,0],N=[-o[3],o[0],d,f],G=[-o[3],o[2]-F]}const U=["q",`${x.join(" ")} 0 0 cm`,`${N.join(" ")} re W n`,"BT",`${fr(g,!0)}`,`0 Tc /Helv ${$A(R)} Tf`];U.push(`${G.join(" ")} Td (${PA(w[0])}) Tj`);const M=$A(k);for(let A=1,e=w.length;A(A.push(`${i[0]} ${i[1]} m`,`${i[2]} ${i[3]} l`,"S"),[e[0]-r,e[2]+r,e[7]-r,e[3]+r])})}}}class _u extends Ku{constructor(A){super(A);const{dict:e,xref:t}=A;if(this.data.annotationType=5,this.data.hasOwnCanvas=this.data.noRotate,this.data.noHTML=!1,!this.appearance){const A=this.color?Lu(this.color):[0,0,0],i=e.get("CA"),a=Mu(e.getArray("IC"),null),s=a?Lu(a):null,n=s?i:null;if(0===this.borderStyle.width&&!s)return;this._setDefaultAppearance({xref:t,extra:`${this.borderStyle.width} w`,strokeColor:A,fillColor:s,strokeAlpha:i,fillAlpha:n,pointsCallback:(A,e)=>{const t=e[4]+this.borderStyle.width/2,i=e[5]+this.borderStyle.width/2,a=e[6]-e[4]-this.borderStyle.width,n=e[3]-e[7]-this.borderStyle.width;return A.push(`${t} ${i} ${a} ${n} re`),s?A.push("B"):A.push("S"),[e[0],e[2],e[7],e[3]]}})}}}class $u extends Ku{constructor(A){super(A);const{dict:e,xref:t}=A;if(this.data.annotationType=6,!this.appearance){const A=this.color?Lu(this.color):[0,0,0],i=e.get("CA"),a=Mu(e.getArray("IC"),null),s=a?Lu(a):null,n=s?i:null;if(0===this.borderStyle.width&&!s)return;const g=4/3*Math.tan(Math.PI/8);this._setDefaultAppearance({xref:t,extra:`${this.borderStyle.width} w`,strokeColor:A,fillColor:s,strokeAlpha:i,fillAlpha:n,pointsCallback:(A,e)=>{const t=e[0]+this.borderStyle.width/2,i=e[1]-this.borderStyle.width/2,a=e[6]-this.borderStyle.width/2,n=e[7]+this.borderStyle.width/2,r=t+(a-t)/2,o=i+(n-i)/2,I=(a-t)/2*g,c=(n-i)/2*g;return A.push(`${r} ${n} m`,`${r+I} ${n} ${a} ${o+c} ${a} ${o} c`,`${a} ${o-c} ${r+I} ${i} ${r} ${i} c`,`${r-I} ${i} ${t} ${o-c} ${t} ${o} c`,`${t} ${o+c} ${r-I} ${n} ${r} ${n} c`,"h"),s?A.push("B"):A.push("S"),[e[0],e[2],e[7],e[3]]}})}}}class Ad extends Ku{constructor(A){super(A);const{dict:e,xref:t}=A;this.data.annotationType=8,this.data.hasOwnCanvas=this.data.noRotate,this.data.noHTML=!1,this.data.vertices=null,this instanceof ed||(this.setLineEndings(e.getArray("LE")),this.data.lineEndings=this.lineEndings);const i=e.getArray("Vertices");if(!HA(i,null))return;const a=this.data.vertices=Float32Array.from(i);if(!this.appearance){const A=this.color?Lu(this.color):[0,0,0],i=e.get("CA"),s=this.borderStyle.width||1,n=2*s,g=[1/0,1/0,-1/0,-1/0];for(let A=0,e=a.length;A{for(let e=0,t=a.length;e{for(const e of this.data.inkLists){for(let t=0,i=e.length;tA.points))),c.set("F",4),c.set("Rotate",o),g&&c.set("IT",cA.get("InkHighlight"));const C=new hA(e);c.set("BS",C),C.set("W",I),c.set("C",Array.from(a,(A=>A/255))),c.set("CA",s);const B=new hA(e);return c.set("AP",B),t?B.set("N",t):B.set("N",i),c}static async createNewAppearanceStream(A,e,t){if(A.outlines)return this.createNewAppearanceStreamForHighlight(A,e,t);const{color:i,rect:a,paths:s,thickness:n,opacity:g}=A,r=[`${n} w 1 J 1 j`,`${fr(i,!1)}`];1!==g&&r.push("/R0 gs");const o=[];for(const{bezier:A}of s){if(o.length=0,o.push(`${$A(A[0])} ${$A(A[1])} m`),2===A.length)o.push(`${$A(A[0])} ${$A(A[1])} l S`);else{for(let e=2,t=A.length;e(A.push(`${e[0]} ${e[1]} m`,`${e[2]} ${e[3]} l`,`${e[6]} ${e[7]} l`,`${e[4]} ${e[5]} l`,"f"),[e[0],e[2],e[7],e[3]])})}}else this.data.popupRef=null}static createNewDict(A,e,{apRef:t,ap:i}){const{color:a,oldAnnotation:s,opacity:n,rect:g,rotation:r,user:o,quadPoints:I}=A,c=s||new hA(e);if(c.set("Type",cA.get("Annot")),c.set("Subtype",cA.get("Highlight")),c.set(s?"M":"CreationDate",`D:${iA()}`),c.set("CreationDate",`D:${iA()}`),c.set("Rect",g),c.set("F",4),c.set("Border",[0,0,0]),c.set("Rotate",r),c.set("QuadPoints",I),c.set("C",Array.from(a,(A=>A/255))),c.set("CA",n),o&&c.set("T",ee(o)),t||i){const A=new hA(e);c.set("AP",A),A.set("N",t||i)}return c}static async createNewAppearanceStream(A,e,t){const{color:i,rect:a,outlines:s,opacity:n}=A,g=[`${fr(i,!0)}`,"/R0 gs"],r=[];for(const A of s){r.length=0,r.push(`${$A(A[0])} ${$A(A[1])} m`);for(let e=2,t=A.length;e(A.push(`${e[4]} ${e[5]+1.3} m`,`${e[6]} ${e[7]+1.3} l`,"S"),[e[0],e[2],e[7],e[3]])})}}else this.data.popupRef=null}}class nd extends Ku{constructor(A){super(A);const{dict:e,xref:t}=A;if(this.data.annotationType=11,this.data.quadPoints=Ju(e,null)){if(!this.appearance){const A=this.color?Lu(this.color):[0,0,0],i=e.get("CA");this._setDefaultAppearance({xref:t,extra:"[] 0 d 1 w",strokeColor:A,strokeAlpha:i,pointsCallback:(A,e)=>{const t=(e[1]-e[5])/6;let i=t,a=e[4];const s=e[5],n=e[6];A.push(`${a} ${s+i} m`);do{a+=2,i=0===i?t:0,A.push(`${a} ${s+i} l`)}while(a(A.push((e[0]+e[4])/2+" "+(e[1]+e[5])/2+" m",(e[2]+e[6])/2+" "+(e[3]+e[7])/2+" l","S"),[e[0],e[2],e[7],e[3]])})}}else this.data.popupRef=null}}class rd extends Ku{#q;constructor(A){super(A),this.data.annotationType=13,this.#q=this.data.hasOwnCanvas=this.data.noRotate,this.data.isEditable=!this.data.noHTML,this.data.noHTML=!1}mustBeViewedWhenEditing(A,e=null){return A?!!this.data.isEditable&&(this.#q=this.data.hasOwnCanvas,this.data.hasOwnCanvas=!0,!0):(this.data.hasOwnCanvas=this.#q,!e?.has(this.data.id))}static async createImage(A,e){const{width:t,height:i}=A,a=new OffscreenCanvas(t,i),s=a.getContext("2d",{alpha:!0});s.drawImage(A,0,0);const n=s.getImageData(0,0,t,i).data,g=new Uint32Array(n.buffer),r=g.some(V.isLittleEndian?A=>A>>>24!=255:A=>!!(255&~A));r&&(s.fillStyle="white",s.fillRect(0,0,t,i),s.drawImage(A,0,0));const o=a.convertToBlob({type:"image/jpeg",quality:1}).then((A=>A.arrayBuffer())),I=cA.get("XObject"),c=cA.get("Image"),C=new hA(e);C.set("Type",I),C.set("Subtype",c),C.set("BitsPerComponent",8),C.set("ColorSpace",cA.get("DeviceRGB")),C.set("Filter",cA.get("DCTDecode")),C.set("BBox",[0,0,t,i]),C.set("Width",t),C.set("Height",i);let B=null;if(r){const A=new Uint8Array(g.length);if(V.isLittleEndian)for(let e=0,t=g.length;e>>24;else for(let e=0,t=g.length;e=0&&s<=1?s:null}}function Id(A){try{return AA(A)}catch(e){return N(`UTF-8 decoding failed: "${e}".`),A}}class cd extends Gr{constructor(A){super(A),this.node=null}onEndElement(A){const e=super.onEndElement(A);if(e&&"xfa:datasets"===A)throw this.node=e,new Error("Aborting DatasetXMLParser.")}}class Cd{constructor(A){if(A.datasets)this.node=new Gr({hasAttributes:!0}).parseFromString(A.datasets).documentElement;else{const e=new cd({hasAttributes:!0});try{e.parseFromString(A["xdp:xdp"])}catch{}this.node=e.node}}getValue(A){if(!this.node||!A)return"";const e=this.node.searchNode(qA(A),0);if(!e)return"";const t=e.firstChild;return"value"===t?.nodeName?e.children.map((A=>Id(A.textContent))):Id(e.textContent)}}class Bd{#T=null;constructor(A,e){this.stream=A,this.pdfManager=e,this.entries=[],this._xrefStms=new Set,this._cacheMap=new Map,this._pendingRefs=new lA,this._newPersistentRefNum=null,this._newTemporaryRefNum=null,this._persistentRefsCache=null}getNewPersistentRef(A){null===this._newPersistentRefNum&&(this._newPersistentRefNum=this.entries.length||1);const e=this._newPersistentRefNum++;return this._cacheMap.set(e,A),QA.get(e,0)}getNewTemporaryRef(){if(null===this._newTemporaryRefNum&&(this._newTemporaryRefNum=this.entries.length||1,this._newPersistentRefNum)){this._persistentRefsCache=new Map;for(let A=this._newTemporaryRefNum;A0;){const[n,g]=s;if(!Number.isInteger(n)||!Number.isInteger(g))throw new T(`Invalid XRef range fields: ${n}, ${g}`);if(!Number.isInteger(t)||!Number.isInteger(i)||!Number.isInteger(a))throw new T(`Invalid XRef entry fields length: ${n}, ${g}`);for(let s=e.entryNum;s=A.length);)t+=String.fromCharCode(i),i=A[e];return t}function e(A,e,t){const i=t.length,a=A.length;let s=0;for(;e=i)break;e++,s++}return s}const t=/\b(endobj|\d+\s+\d+\s+obj|xref|trailer\s*<<)\b/g,i=/\b(startxref|\d+\s+\d+\s+obj)\b/g,a=/^(\d+)\s+(\d+)\s+obj\b/,s=new Uint8Array([116,114,97,105,108,101,114]),n=new Uint8Array([115,116,97,114,116,120,114,101,102]),g=new Uint8Array([47,88,82,101,102]);this.entries.length=0,this._cacheMap.clear();const r=this.stream;r.pos=0;const o=r.getBytes(),I=W(o),c=o.length;let C=r.start;const B=[],h=[];for(;C=c)break;Q=o[C]}while(10!==Q&&13!==Q);continue}const l=A(o,C);let E;if(l.startsWith("xref")&&(4===l.length||/\s/.test(l[4])))C+=e(o,C,s),B.push(C),C+=e(o,C,n);else if(E=a.exec(l)){const A=0|E[1],i=0|E[2],a=C+l.length;let s,n=!1;if(this.entries[A]){if(this.entries[A].gen===i)try{new ni({lexer:new oi(r.makeSubStream(a))}).getObj(),n=!0}catch(A){A instanceof bA?N(`indexObjects -- checking object (${l}): "${A}".`):n=!0}}else n=!0;n&&(this.entries[A]={offset:C-r.start,gen:i,uncompressed:!0}),t.lastIndex=a;const B=t.exec(I);B?(s=t.lastIndex+1-C,"endobj"!==B[1]&&(N(`indexObjects: Found "${B[1]}" inside of another "obj", caused by missing "endobj" -- trying to recover.`),s-=B[1].length+1)):s=c-C;const Q=o.subarray(C,C+s),u=e(Q,0,g);u0?Math.max(...this._xrefStms):null)}getEntry(A){const e=this.entries[A];return e&&!e.free&&e.offset?e:null}fetchIfRef(A,e=!1){return A instanceof QA?this.fetch(A,e):A}fetch(A,e=!1){if(!(A instanceof QA))throw new Error("ref object is not a reference");const t=A.num,i=this._cacheMap.get(t);if(void 0!==i)return i instanceof hA&&!i.objId&&(i.objId=A.toString()),i;let a=this.getEntry(t);if(null===a)return this._cacheMap.set(t,a),a;if(this._pendingRefs.has(A))return this._pendingRefs.remove(A),N(`Ignoring circular reference: ${A}.`),nA;this._pendingRefs.put(A);try{a=a.uncompressed?this.fetchUncompressed(A,a,e):this.fetchCompressed(A,a,e),this._pendingRefs.remove(A)}catch(e){throw this._pendingRefs.remove(A),e}return a instanceof hA?a.objId=A.toString():a instanceof mA&&(a.dict.objId=A.toString()),a}fetchUncompressed(A,e,t=!1){const i=A.gen;let a=A.num;if(e.gen!==i){const s=`Inconsistent generation in XRef: ${A}`;if(this._generationFallback&&e.gen0&&e[3]-e[1]>0)return e;N(`Empty, or invalid, /${A} entry.`)}return null}get mediaBox(){return L(this,"mediaBox",this._getBoundingBox("MediaBox")||hd)}get cropBox(){return L(this,"cropBox",this._getBoundingBox("CropBox")||this.mediaBox)}get userUnit(){let A=this.pageDict.get("UserUnit");return("number"!=typeof A||A<=0)&&(A=1),L(this,"userUnit",A)}get view(){const{cropBox:A,mediaBox:e}=this;if(A!==e&&!tA(A,e)){const t=z.intersect(A,e);if(t&&t[2]-t[0]>0&&t[3]-t[1]>0)return L(this,"view",t);N("Empty /CropBox and /MediaBox intersection.")}return L(this,"view",e)}get rotate(){let A=this._getInheritableProperty("Rotate")||0;return A%90!=0?A=0:A>=360?A%=360:A<0&&(A=(A%360+360)%360),L(this,"rotate",A)}_onSubStreamError(A,e){if(!this.evaluatorOptions.ignoreErrors)throw A;N(`getContentStream - ignoring sub-stream (${e}): "${A}".`)}getContentStream(){return this.pdfManager.ensure(this,"content").then((A=>A instanceof mA?A:Array.isArray(A)?new Ge(A,this._onSubStreamError.bind(this)):new re))}get xfaData(){return L(this,"xfaData",this.xfaFactory?{bbox:this.xfaFactory.getBoundingBox(this.pageIndex)}:null)}async#P(A,e,t){const i=[];for(const a of A)if(a.id){const A=QA.fromString(a.id);if(!A){N(`A non-linked annotation cannot be modified: ${a.id}`);continue}if(a.deleted){if(e.put(A,A),a.popupRef){const A=QA.fromString(a.popupRef);A&&e.put(A,A)}continue}t?.put(A),a.ref=A,i.push(this.xref.fetchAsync(A).then((A=>{A instanceof hA&&(a.oldAnnotation=A.clone())}),(()=>{N(`Cannot fetch \`oldAnnotation\` for: ${A}.`)}))),delete a.id}await Promise.all(i)}async saveNewAnnotations(A,e,t,i){if(this.xfaFactory)throw new Error("XFA: Cannot save new annotations.");const a=new cr({xref:this.xref,handler:A,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions}),s=new EA,n=new lA;await this.#P(t,s,n);const g=this.pageDict,r=this.annotations.filter((A=>!(A instanceof QA&&s.has(A)))),o=await Uu.saveNewAnnotations(a,e,t,i);for(const{ref:A}of o.annotations)A instanceof QA&&!n.has(A)&&r.push(A);const I=g.get("Annots");g.set("Annots",r);const c=[];await Or(this.ref,g,c,this.xref),I&&g.set("Annots",I);const C=o.dependencies;C.push({ref:this.ref,data:c.join("")},...o.annotations);for(const A of s)C.push({ref:A,data:null});return C}save(A,e,t){const i=new cr({xref:this.xref,handler:A,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions});return this._parsedAnnotations.then((function(A){const a=[];for(const s of A)a.push(s.save(i,e,t).catch((function(A){return N(`save - ignoring annotation data during "${e.name}" task: "${A}".`),null})));return Promise.all(a).then((function(A){return A.filter((A=>!!A))}))}))}loadResources(A){return this.resourcesPromise||=this.pdfManager.ensure(this,"resources"),this.resourcesPromise.then((()=>new Co(this.resources,A,this.xref).load()))}getOperatorList({handler:A,sink:e,task:t,intent:i,cacheKey:a,annotationStorage:s=null,modifiedIds:n=null}){const r=this.getContentStream(),o=this.loadResources(["ColorSpace","ExtGState","Font","Pattern","Properties","Shading","XObject"]),I=new cr({xref:this.xref,handler:A,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions}),c=this.xfaFactory?null:Ae(s),C=c?.get(this.pageIndex);let B=Promise.resolve(null),h=null;if(C){const A=this.pdfManager.ensureDoc("annotationGlobals");let e;const i=new Set;for(const{bitmapId:A,bitmap:e}of C)!A||e||i.has(A)||i.add(A);const{isOffscreenCanvasSupported:a}=this.evaluatorOptions;if(i.size>0){const A=C.slice();for(const[e,t]of s)e.startsWith(g)&&t.bitmap&&i.has(t.bitmapId)&&A.push(t);e=Uu.generateImages(A,this.xref,a)}else e=Uu.generateImages(C,this.xref,a);h=new lA,B=Promise.all([A,this.#P(C,h,null)]).then((([A])=>A?Uu.printNewAnnotations(A,I,t,C,e):null))}const Q=Promise.all([r,o]).then((([s])=>{const n=new tr(i,e);return A.send("StartRenderPage",{transparency:I.hasBlendModes(this.resources,this.nonBlendModesSet),pageIndex:this.pageIndex,cacheKey:a}),I.getOperatorList({stream:s,task:t,resources:this.resources,operatorList:n}).then((function(){return n}))}));return Promise.all([Q,this._parsedAnnotations,B]).then((function([A,e,a]){if(a){e=e.filter((A=>!(A.ref&&h.has(A.ref))));for(let A=0,t=a.length;AA.ref&&pA(A.ref,i.refToReplace)));s>=0&&(e.splice(s,1,i),a.splice(A--,1),t--)}}e=e.concat(a)}if(0===e.length||64&i)return A.flush(!0),{length:A.totalLength};const g=!!(16&i),r=!!(128&i),o=!!(1&i),c=!!(2&i),C=!!(4&i),B=[];for(const A of e)(o||c&&A.mustBeViewed(s,g)&&A.mustBeViewedWhenEditing(r,n)||C&&A.mustBePrinted(s))&&B.push(A.getOperatorList(I,t,i,s).catch((function(A){return N(`getOperatorList - ignoring annotation data during "${t.name}" task: "${A}".`),{opList:null,separateForm:!1,separateCanvas:!1}})));return Promise.all(B).then((function(e){let t=!1,i=!1;for(const{opList:a,separateForm:s,separateCanvas:n}of e)A.addOpList(a),t||=s,i||=n;return A.flush(!0,{form:t,canvas:i}),{length:A.totalLength}}))}))}async extractTextContent({handler:A,task:e,includeMarkedContent:t,disableNormalization:i,sink:a}){const s=this.getContentStream(),n=this.loadResources(["ExtGState","Font","Properties","XObject"]),g=this.pdfManager.ensureCatalog("lang"),[r,,o]=await Promise.all([s,n,g]);return new cr({xref:this.xref,handler:A,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions}).getTextContent({stream:r,task:e,resources:this.resources,includeMarkedContent:t,disableNormalization:i,sink:a,viewBox:this.view,lang:o})}async getStructTree(){const A=await this.pdfManager.ensureCatalog("structTreeRoot");return A?(await this._parsedAnnotations,(await this.pdfManager.ensure(this,"_parseStructTree",[A])).serializable):null}_parseStructTree(A){const e=new no(A,this.pageDict);return e.parse(this.ref),e}async getAnnotationsData(A,e,t){const i=await this._parsedAnnotations;if(0===i.length)return i;const a=[],s=[];let n;const g=!!(1&t),r=!!(2&t),o=!!(4&t);for(const t of i){const i=g||r&&t.viewable;(i||o&&t.printable)&&a.push(t.data),t.hasTextContent&&i&&(n||=new cr({xref:this.xref,handler:A,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions}),s.push(t.extractTextContent(n,e,[-1/0,-1/0,1/0,1/0]).catch((function(A){N(`getAnnotationsData - ignoring textContent during "${e.name}" task: "${A}".`)}))))}return await Promise.all(s),a}get annotations(){const A=this._getInheritableProperty("Annots");return L(this,"annotations",Array.isArray(A)?A:[])}get _parsedAnnotations(){return L(this,"_parsedAnnotations",this.pdfManager.ensure(this,"annotations").then((async A=>{if(0===A.length)return A;const[e,t]=await Promise.all([this.pdfManager.ensureDoc("annotationGlobals"),this.pdfManager.ensureDoc("fieldObjects")]);if(!e)return[];const i=t?.orphanFields,a=[];for(const t of A)a.push(Uu.create(this.xref,t,e,this._localIdFactory,!1,i,this.ref).catch((function(A){return N(`_parsedAnnotations: "${A}".`),null})));const s=[];let n,g;for(const A of await Promise.all(a))A&&(A instanceof qu?(g||=[]).push(A):A instanceof Vu?(n||=[]).push(A):s.push(A));return g&&s.push(...g),n&&s.push(...n),s})))}get jsActions(){return L(this,"jsActions",ZA(this.xref,this.pageDict,Q))}}const ld=new Uint8Array([37,80,68,70,45]),Ed=new Uint8Array([115,116,97,114,116,120,114,101,102]),ud=new Uint8Array([101,110,100,111,98,106]);function dd(A,e,t=1024,i=!1){const a=e.length,s=A.peekBytes(t),n=s.length-a;if(n<=0)return!1;if(i){const t=a-1;let i=s.length-1;for(;i>=t;){let n=0;for(;n=a)return A.pos+=i-t,!0;i--}}else{let t=0;for(;t<=n;){let i=0;for(;i=a)return A.pos+=t,!0;t++}}return!1}class fd{constructor(A,e){if(e.length<=0)throw new v("The PDF file is empty, i.e. its size is zero bytes.");this.pdfManager=A,this.stream=e,this.xref=new Bd(e,A),this._pagePromises=new Map,this._version=null;const t={font:0};this._globalIdFactory=class{static getDocId(){return`g_${A.docId}`}static createFontId(){return"f"+ ++t.font}static createObjId(){x("Abstract method `createObjId` called.")}static getPageObjId(){x("Abstract method `getPageObjId` called.")}}}parse(A){this.xref.parse(A),this.catalog=new Io(this.pdfManager,this.xref)}get linearization(){let A=null;try{A=Ii.create(this.stream)}catch(A){if(A instanceof DA)throw A;G(A)}return L(this,"linearization",A)}get startXRef(){const A=this.stream;let e=0;if(this.linearization){if(A.reset(),dd(A,ud)){A.skip(6);let t=A.peekByte();for(;JA(t);)A.pos++,t=A.peekByte();e=A.pos-A.start}}else{const t=1024,i=Ed.length;let a=!1,s=A.end;for(;!a&&s>0;)s-=t-i,s<0&&(s=0),A.pos=s,a=dd(A,Ed,t,!0);if(a){let t;A.skip(9);do{t=A.getByte()}while(JA(t));let i="";for(;t>=32&&t<=57;)i+=String.fromCharCode(t),t=A.getByte();e=parseInt(i,10),isNaN(e)&&(e=0)}}return L(this,"startXRef",e)}checkHeader(){const A=this.stream;if(A.reset(),!dd(A,ld))return;A.moveStart(),A.skip(ld.length);let e,t="";for(;(e=A.getByte())>32&&t.length<7;)t+=String.fromCharCode(e);yA.test(t)?this._version=t:N(`Invalid PDF header version: ${t}`)}parseStartXRef(){this.xref.setStartXRef(this.startXRef)}get numPages(){let A=0;return A=this.catalog.hasActualNumPages?this.catalog.numPages:this.xfaFactory?this.xfaFactory.getNumPages():this.linearization?this.linearization.numPages:this.catalog.numPages,L(this,"numPages",A)}_hasOnlyDocumentSignatures(A,e=0){return!!Array.isArray(A)&&A.every((A=>{if(!((A=this.xref.fetchIfRef(A))instanceof hA))return!1;if(A.has("Kids"))return++e>10?(N("_hasOnlyDocumentSignatures: maximum recursion depth reached"),!1):this._hasOnlyDocumentSignatures(A.get("Kids"),e);const t=uA(A.get("FT"),"Sig"),i=A.get("Rect"),a=Array.isArray(i)&&i.every((A=>0===A));return t&&a}))}get _xfaStreams(){const A=this.catalog.acroForm;if(!A)return null;const e=A.get("XFA"),t={"xdp:xdp":"",template:"",datasets:"",config:"",connectionSet:"",localeSet:"",stylesheet:"","/xdp:xdp":""};if(e instanceof mA&&!e.isEmpty)return t["xdp:xdp"]=e,t;if(!Array.isArray(e)||0===e.length)return null;for(let A=0,i=e.length;A{c.set(A,e)}));const C=[];for(const[A,t]of c){const a=t.get("FontDescriptor");if(!(a instanceof hA))continue;let s=a.get("FontFamily");s=s.replaceAll(/[ ]+(\d)/g,"$1");const n={fontFamily:s,fontWeight:a.get("FontWeight"),italicAngle:-a.get("ItalicAngle")};zA(n)&&C.push(g.handleSetFont(i,[cA.get(A),1],null,r,e,I,null,n).catch((function(A){return N(`loadXfaFonts: "${A}".`),null})))}await Promise.all(C);const B=this.xfaFactory.setFonts(o);if(!B)return;n.ignoreErrors=!0,C.length=0,o.length=0;const h=new Set;for(const A of B)Xn(`${A}-Regular`)||h.add(A);h.size&&B.push("PdfJS-Fallback");for(const A of B)if(!h.has(A))for(const t of[{name:"Regular",fontWeight:400,italicAngle:0},{name:"Bold",fontWeight:700,italicAngle:0},{name:"Italic",fontWeight:400,italicAngle:12},{name:"BoldItalic",fontWeight:700,italicAngle:12}]){const a=`${A}-${t.name}`,s=Vn(a);C.push(g.handleSetFont(i,[cA.get(a),1],null,r,e,I,s,{fontFamily:A,fontWeight:t.fontWeight,italicAngle:t.italicAngle}).catch((function(A){return N(`loadXfaFonts: "${A}".`),null})))}await Promise.all(C),this.xfaFactory.appendFonts(o,h)}async serializeXfaData(A){return this.xfaFactory?this.xfaFactory.serializeData(A):null}get version(){return this.catalog.version||this._version}get formInfo(){const A={hasFields:!1,hasAcroForm:!1,hasXfa:!1,hasSignatures:!1},e=this.catalog.acroForm;if(!e)return L(this,"formInfo",A);try{const t=e.get("Fields"),i=Array.isArray(t)&&t.length>0;A.hasFields=i;const a=e.get("XFA");A.hasXfa=Array.isArray(a)&&a.length>0||a instanceof mA&&!a.isEmpty;const s=!!(1&e.get("SigFlags")),n=s&&this._hasOnlyDocumentSignatures(t);A.hasAcroForm=i&&!n,A.hasSignatures=s}catch(A){if(A instanceof DA)throw A;N(`Cannot fetch form information: "${A}".`)}return L(this,"formInfo",A)}get documentInfo(){const A={PDFFormatVersion:this.version,Language:this.catalog.lang,EncryptFilterName:this.xref.encrypt?this.xref.encrypt.filterName:null,IsLinearized:!!this.linearization,IsAcroFormPresent:this.formInfo.hasAcroForm,IsXFAPresent:this.formInfo.hasXfa,IsCollectionPresent:!!this.catalog.collection,IsSignaturesPresent:this.formInfo.hasSignatures};let e;try{e=this.xref.trailer.get("Info")}catch(A){if(A instanceof DA)throw A;G("The document information dictionary is invalid.")}if(!(e instanceof hA))return L(this,"documentInfo",A);for(const t of e.getKeys()){const i=e.get(t);switch(t){case"Title":case"Author":case"Subject":case"Keywords":case"Creator":case"Producer":case"CreationDate":case"ModDate":if("string"==typeof i){A[t]=$(i);continue}break;case"Trapped":if(i instanceof cA){A[t]=i;continue}break;default:let e;switch(typeof i){case"string":e=$(i);break;case"number":case"boolean":e=i;break;default:i instanceof cA&&(e=i)}if(void 0===e){N(`Bad value, for custom key "${t}", in Info: ${i}.`);continue}A.Custom||(A.Custom=Object.create(null)),A.Custom[t]=e;continue}N(`Bad value, for key "${t}", in Info: ${i}.`)}return L(this,"documentInfo",A)}get fingerprints(){function A(A){return"string"==typeof A&&A.length>0&&"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"!==A}function e(A){const e=[];for(const t of A){const A=t.toString(16);e.push(A.padStart(2,"0"))}return e.join("")}const t=this.xref.trailer.get("ID");let i,a;return Array.isArray(t)&&A(t[0])?(i=Z(t[0]),t[1]!==t[0]&&A(t[1])&&(a=Z(t[1]))):i=Mr(this.stream.getByteRange(0,1024),0,1024),L(this,"fingerprints",[e(i),a?e(a):null])}async _getLinearizationPage(A){const{catalog:e,linearization:t,xref:i}=this,a=QA.get(t.objectNumberFirst,0);try{const A=await i.fetchAsync(a);if(A instanceof hA){let t=A.getRaw("Type");if(t instanceof QA&&(t=await i.fetchAsync(t)),uA(t,"Page")||!A.has("Type")&&!A.has("Kids")&&A.has("Contents"))return e.pageKidsCountCache.has(a)||e.pageKidsCountCache.put(a,1),e.pageIndexCache.has(a)||e.pageIndexCache.put(a,0),[A,a]}throw new T("The Linearization dictionary doesn't point to a valid Page dictionary.")}catch(t){return N(`_getLinearizationPage: "${t.message}".`),e.getPageDict(A)}}getPage(A){const e=this._pagePromises.get(A);if(e)return e;const{catalog:t,linearization:i,xfaFactory:a}=this;let s;return s=a?Promise.resolve([hA.empty,null]):i?.pageFirst===A?this._getLinearizationPage(A):t.getPageDict(A),s=s.then((([e,i])=>new Qd({pdfManager:this.pdfManager,xref:this.xref,pageIndex:A,pageDict:e,ref:i,globalIdFactory:this._globalIdFactory,fontCache:t.fontCache,builtInCMapCache:t.builtInCMapCache,standardFontDataCache:t.standardFontDataCache,globalImageCache:t.globalImageCache,systemFontCache:t.systemFontCache,nonBlendModesSet:t.nonBlendModesSet,xfaFactory:a}))),this._pagePromises.set(A,s),s}async checkFirstPage(A=!1){if(!A)try{await this.getPage(0)}catch(A){if(A instanceof kA)throw this._pagePromises.delete(0),await this.cleanup(),new FA}}async checkLastPage(A=!1){const{catalog:e,pdfManager:t}=this;let i;e.setActualNumPages();try{if(await Promise.all([t.ensureDoc("xfaFactory"),t.ensureDoc("linearization"),t.ensureCatalog("numPages")]),this.xfaFactory)return;if(i=this.linearization?this.linearization.numPages:e.numPages,!Number.isInteger(i))throw new T("Page count is not an integer.");if(i<=1)return;await this.getPage(i-1)}catch(a){if(this._pagePromises.delete(i-1),await this.cleanup(),a instanceof kA&&!A)throw new FA;let s;N(`checkLastPage - invalid /Pages tree /Count: ${i}.`);try{s=await e.getAllPageDicts(A)}catch(t){if(t instanceof kA&&!A)throw new FA;return void e.setActualNumPages(1)}for(const[A,[i,a]]of s){let s;i instanceof Error?(s=Promise.reject(i),s.catch((()=>{}))):s=Promise.resolve(new Qd({pdfManager:t,xref:this.xref,pageIndex:A,pageDict:i,ref:a,globalIdFactory:this._globalIdFactory,fontCache:e.fontCache,builtInCMapCache:e.builtInCMapCache,standardFontDataCache:e.standardFontDataCache,globalImageCache:e.globalImageCache,systemFontCache:e.systemFontCache,nonBlendModesSet:e.nonBlendModesSet,xfaFactory:null})),this._pagePromises.set(A,s)}e.setActualNumPages(s.size)}}fontFallback(A,e){return this.catalog.fontFallback(A,e)}async cleanup(A=!1){return this.catalog?this.catalog.cleanup(A):Dr()}async#W(A,e,t,i,a,s,n){const{xref:g}=this;if(!(t instanceof QA)||s.has(t))return;s.put(t);const r=await g.fetchAsync(t);if(!(r instanceof hA))return;if(r.has("T")){const e=$(await r.getAsync("T"));A=""===A?e:`${A}.${e}`}else{let t=r;for(;;){if(t=t.getRaw("Parent")||e,t instanceof QA){if(s.has(t))break;t=await g.fetchAsync(t)}if(!(t instanceof hA))break;if(t.has("T")){const e=$(await t.getAsync("T"));A=""===A?e:`${A}.${e}`;break}}}if(e&&!r.has("Parent")&&uA(r.get("Subtype"),"Widget")&&n.put(t,e),i.has(A)||i.set(A,[]),i.get(A).push(Uu.create(g,t,a,null,!0,n,null).then((A=>A?.getFieldObject())).catch((function(A){return N(`#collectFieldObjects: "${A}".`),null}))),!r.has("Kids"))return;const o=await r.getAsync("Kids");if(Array.isArray(o))for(const e of o)await this.#W(A,t,e,i,a,s,n)}get fieldObjects(){return this.formInfo.hasFields?L(this,"fieldObjects",Promise.all([this.pdfManager.ensureDoc("annotationGlobals"),this.pdfManager.ensureCatalog("acroForm")]).then((async([A,e])=>{if(!A)return null;const t=new lA,i=Object.create(null),a=new Map,s=new EA;for(const i of await e.getAsync("Fields"))await this.#W("",null,i,a,A,t,s);const n=[];for(const[A,e]of a)n.push(Promise.all(e).then((e=>{(e=e.filter((A=>!!A))).length>0&&(i[A]=e)})));return await Promise.all(n),{allFields:i,orphanFields:s}}))):L(this,"fieldObjects",Promise.resolve(null))}get hasJSActions(){return L(this,"hasJSActions",this.pdfManager.ensureDoc("_parseHasJSActions"))}async _parseHasJSActions(){const[A,e]=await Promise.all([this.pdfManager.ensureCatalog("jsActions"),this.pdfManager.ensureDoc("fieldObjects")]);return!!A||!!e&&Object.values(e.allFields).some((A=>A.some((A=>null!==A.actions))))}get calculationOrderIds(){const A=this.catalog.acroForm;if(!A?.has("CO"))return L(this,"calculationOrderIds",null);const e=A.get("CO");if(!Array.isArray(e)||0===e.length)return L(this,"calculationOrderIds",null);const t=[];for(const A of e)A instanceof QA&&t.push(A.toString());return 0===t.length?L(this,"calculationOrderIds",null):L(this,"calculationOrderIds",t)}get annotationGlobals(){return L(this,"annotationGlobals",Uu.createGlobals(this.pdfManager))}}class pd{constructor(A){this._docBaseUrl=function(A){if(A){const e=M(A);if(e)return e.href;N(`Invalid absolute docBaseUrl: "${A}".`)}return null}(A.docBaseUrl),this._docId=A.docId,this._password=A.password,this.enableXfa=A.enableXfa,A.evaluatorOptions.isOffscreenCanvasSupported&&=V.isOffscreenCanvasSupported,this.evaluatorOptions=Object.freeze(A.evaluatorOptions)}get docId(){return this._docId}get password(){return this._password}get docBaseUrl(){return this._docBaseUrl}get catalog(){return this.pdfDocument.catalog}ensureDoc(A,e){return this.ensure(this.pdfDocument,A,e)}ensureXRef(A,e){return this.ensure(this.pdfDocument.xref,A,e)}ensureCatalog(A,e){return this.ensure(this.pdfDocument.catalog,A,e)}getPage(A){return this.pdfDocument.getPage(A)}fontFallback(A,e){return this.pdfDocument.fontFallback(A,e)}loadXfaFonts(A,e){return this.pdfDocument.loadXfaFonts(A,e)}loadXfaImages(){return this.pdfDocument.loadXfaImages()}serializeXfaData(A){return this.pdfDocument.serializeXfaData(A)}cleanup(A=!1){return this.pdfDocument.cleanup(A)}async ensure(A,e,t){x("Abstract method `ensure` called")}requestRange(A,e){x("Abstract method `requestRange` called")}requestLoadedStream(A=!1){x("Abstract method `requestLoadedStream` called")}sendProgressiveData(A){x("Abstract method `sendProgressiveData` called")}updatePassword(A){this._password=A}terminate(A){x("Abstract method `terminate` called")}}class md extends pd{constructor(A){super(A);const e=new ne(A.source);this.pdfDocument=new fd(this,e),this._loadedStreamPromise=Promise.resolve(e)}async ensure(A,e,t){const i=A[e];return"function"==typeof i?i.apply(A,t):i}requestRange(A,e){return Promise.resolve()}requestLoadedStream(A=!1){return this._loadedStreamPromise}terminate(A){}}class yd extends pd{constructor(A){super(A),this.streamManager=new Ie(A.source,{msgHandler:A.handler,length:A.length,disableAutoFetch:A.disableAutoFetch,rangeChunkSize:A.rangeChunkSize}),this.pdfDocument=new fd(this,this.streamManager.getStream())}async ensure(A,e,t){try{const i=A[e];return"function"==typeof i?i.apply(A,t):i}catch(i){if(!(i instanceof DA))throw i;return await this.requestRange(i.begin,i.end),this.ensure(A,e,t)}}requestRange(A,e){return this.streamManager.requestRange(A,e)}requestLoadedStream(A=!1){return this.streamManager.requestAllChunks(A)}sendProgressiveData(A){this.streamManager.onReceiveData({chunk:A})}terminate(A){this.streamManager.abort(A)}}function wd(A){switch(A instanceof Error||"object"==typeof A&&null!==A||x('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),A.name){case"AbortException":return new P(A.message);case"MissingPDFException":return new K(A.message);case"PasswordException":return new H(A.message,A.code);case"UnexpectedResponseException":return new q(A.message,A.status);case"UnknownErrorException":return new Y(A.message,A.details);default:return new Y(A.message,A.toString())}}class Dd{constructor(A,e,t){this.sourceName=A,this.targetName=e,this.comObj=t,this.callbackId=1,this.streamId=1,this.streamSinks=Object.create(null),this.streamControllers=Object.create(null),this.callbackCapabilities=Object.create(null),this.actionHandler=Object.create(null),this._onComObjOnMessage=A=>{const e=A.data;if(e.targetName!==this.sourceName)return;if(e.stream)return void this.#Z(e);if(e.callback){const A=e.callbackId,t=this.callbackCapabilities[A];if(!t)throw new Error(`Cannot resolve callback ${A}`);if(delete this.callbackCapabilities[A],1===e.callback)t.resolve(e.data);else{if(2!==e.callback)throw new Error("Unexpected callback case");t.reject(wd(e.reason))}return}const i=this.actionHandler[e.action];if(!i)throw new Error(`Unknown action from worker: ${e.action}`);if(e.callbackId){const A=this.sourceName,a=e.sourceName;new Promise((function(A){A(i(e.data))})).then((function(i){t.postMessage({sourceName:A,targetName:a,callback:1,callbackId:e.callbackId,data:i})}),(function(i){t.postMessage({sourceName:A,targetName:a,callback:2,callbackId:e.callbackId,reason:wd(i)})}))}else e.streamId?this.#O(e):i(e.data)},t.addEventListener("message",this._onComObjOnMessage)}on(A,e){const t=this.actionHandler;if(t[A])throw new Error(`There is already an actionName called "${A}"`);t[A]=e}send(A,e,t){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:A,data:e},t)}sendWithPromise(A,e,t){const i=this.callbackId++,a=Promise.withResolvers();this.callbackCapabilities[i]=a;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:A,callbackId:i,data:e},t)}catch(A){a.reject(A)}return a.promise}sendWithStream(A,e,t,i){const a=this.streamId++,s=this.sourceName,n=this.targetName,g=this.comObj;return new ReadableStream({start:t=>{const r=Promise.withResolvers();return this.streamControllers[a]={controller:t,startCall:r,pullCall:null,cancelCall:null,isClosed:!1},g.postMessage({sourceName:s,targetName:n,action:A,streamId:a,data:e,desiredSize:t.desiredSize},i),r.promise},pull:A=>{const e=Promise.withResolvers();return this.streamControllers[a].pullCall=e,g.postMessage({sourceName:s,targetName:n,stream:6,streamId:a,desiredSize:A.desiredSize}),e.promise},cancel:A=>{U(A instanceof Error,"cancel must have a valid reason");const e=Promise.withResolvers();return this.streamControllers[a].cancelCall=e,this.streamControllers[a].isClosed=!0,g.postMessage({sourceName:s,targetName:n,stream:1,streamId:a,reason:wd(A)}),e.promise}},t)}#O(A){const e=A.streamId,t=this.sourceName,i=A.sourceName,a=this.comObj,s=this,n=this.actionHandler[A.action],g={enqueue(A,s=1,n){if(this.isCancelled)return;const g=this.desiredSize;this.desiredSize-=s,g>0&&this.desiredSize<=0&&(this.sinkCapability=Promise.withResolvers(),this.ready=this.sinkCapability.promise),a.postMessage({sourceName:t,targetName:i,stream:4,streamId:e,chunk:A},n)},close(){this.isCancelled||(this.isCancelled=!0,a.postMessage({sourceName:t,targetName:i,stream:3,streamId:e}),delete s.streamSinks[e])},error(A){U(A instanceof Error,"error must have a valid reason"),this.isCancelled||(this.isCancelled=!0,a.postMessage({sourceName:t,targetName:i,stream:5,streamId:e,reason:wd(A)}))},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:A.desiredSize,ready:null};g.sinkCapability.resolve(),g.ready=g.sinkCapability.promise,this.streamSinks[e]=g,new Promise((function(e){e(n(A.data,g))})).then((function(){a.postMessage({sourceName:t,targetName:i,stream:8,streamId:e,success:!0})}),(function(A){a.postMessage({sourceName:t,targetName:i,stream:8,streamId:e,reason:wd(A)})}))}#Z(A){const e=A.streamId,t=this.sourceName,i=A.sourceName,a=this.comObj,s=this.streamControllers[e],n=this.streamSinks[e];switch(A.stream){case 8:A.success?s.startCall.resolve():s.startCall.reject(wd(A.reason));break;case 7:A.success?s.pullCall.resolve():s.pullCall.reject(wd(A.reason));break;case 6:if(!n){a.postMessage({sourceName:t,targetName:i,stream:7,streamId:e,success:!0});break}n.desiredSize<=0&&A.desiredSize>0&&n.sinkCapability.resolve(),n.desiredSize=A.desiredSize,new Promise((function(A){A(n.onPull?.())})).then((function(){a.postMessage({sourceName:t,targetName:i,stream:7,streamId:e,success:!0})}),(function(A){a.postMessage({sourceName:t,targetName:i,stream:7,streamId:e,reason:wd(A)})}));break;case 4:if(U(s,"enqueue should have stream controller"),s.isClosed)break;s.controller.enqueue(A.chunk);break;case 3:if(U(s,"close should have stream controller"),s.isClosed)break;s.isClosed=!0,s.controller.close(),this.#X(s,e);break;case 5:U(s,"error should have stream controller"),s.controller.error(wd(A.reason)),this.#X(s,e);break;case 2:A.success?s.cancelCall.resolve():s.cancelCall.reject(wd(A.reason)),this.#X(s,e);break;case 1:if(!n)break;new Promise((function(e){e(n.onCancel?.(wd(A.reason)))})).then((function(){a.postMessage({sourceName:t,targetName:i,stream:2,streamId:e,success:!0})}),(function(A){a.postMessage({sourceName:t,targetName:i,stream:2,streamId:e,reason:wd(A)})})),n.sinkCapability.reject(wd(A.reason)),n.isCancelled=!0,delete this.streamSinks[e];break;default:throw new Error("Unexpected stream case")}}async#X(A,e){await Promise.allSettled([A.startCall?.promise,A.pullCall?.promise,A.cancelCall?.promise]),delete this.streamControllers[e]}destroy(){this.comObj.removeEventListener("message",this._onComObjOnMessage)}}class bd{constructor(A){this._msgHandler=A,this._contentLength=null,this._fullRequestReader=null,this._rangeRequestReaders=[]}getFullReader(){return U(!this._fullRequestReader,"PDFWorkerStream.getFullReader can only be called once."),this._fullRequestReader=new kd(this._msgHandler),this._fullRequestReader}getRangeReader(A,e){const t=new Fd(A,e,this._msgHandler);return this._rangeRequestReaders.push(t),t}cancelAllRequests(A){this._fullRequestReader?.cancel(A);for(const e of this._rangeRequestReaders.slice(0))e.cancel(A)}}class kd{constructor(A){this._msgHandler=A,this.onProgress=null,this._contentLength=null,this._isRangeSupported=!1,this._isStreamingSupported=!1;const e=this._msgHandler.sendWithStream("GetReader");this._reader=e.getReader(),this._headersReady=this._msgHandler.sendWithPromise("ReaderHeadersReady").then((A=>{this._isStreamingSupported=A.isStreamingSupported,this._isRangeSupported=A.isRangeSupported,this._contentLength=A.contentLength}))}get headersReady(){return this._headersReady}get contentLength(){return this._contentLength}get isStreamingSupported(){return this._isStreamingSupported}get isRangeSupported(){return this._isRangeSupported}async read(){const{value:A,done:e}=await this._reader.read();return e?{value:void 0,done:!0}:{value:A.buffer,done:!1}}cancel(A){this._reader.cancel(A)}}class Fd{constructor(A,e,t){this._msgHandler=t,this.onProgress=null;const i=this._msgHandler.sendWithStream("GetRangeReader",{begin:A,end:e});this._reader=i.getReader()}get isStreamingSupported(){return!1}async read(){const{value:A,done:e}=await this._reader.read();return e?{value:void 0,done:!0}:{value:A.buffer,done:!1}}cancel(A){this._reader.cancel(A)}}class Sd{constructor(A){this.name=A,this.terminated=!1,this._capability=Promise.withResolvers()}get finished(){return this._capability.promise}finish(){this._capability.resolve()}terminate(){this.terminated=!0}ensureNotTerminated(){if(this.terminated)throw new Error("Worker task was terminated")}}class Rd{static setup(A,e){let t=!1;A.on("test",(function(e){t||(t=!0,A.send("test",e instanceof Uint8Array))})),A.on("configure",(function(A){var e;e=A.verbosity,Number.isInteger(e)&&(S=e)})),A.on("GetDocRequest",(function(A){return Rd.createDocumentHandler(A,e)}))}static createDocumentHandler(A,e){let t,i=!1,a=null;const s=new Set,n=R(),{docId:g,apiVersion:r}=A,o="4.7.76";if(r!==o)throw new Error(`The API version "${r}" does not match the Worker version "${o}".`);const I=[];for(const A in[])I.push(A);if(I.length)throw new Error("The `Array.prototype` contains unexpected enumerable properties: "+I.join(", ")+"; thus breaking e.g. `for...in` iteration of `Array`s.");const c=g+"_worker";let C=new Dd(c,g,e);function B(){if(i)throw new Error("Worker was terminated")}function h(A){s.add(A)}function Q(A){A.finish(),s.delete(A)}async function E(A){await t.ensureDoc("checkHeader"),await t.ensureDoc("parseStartXRef"),await t.ensureDoc("parse",[A]),await t.ensureDoc("checkFirstPage",[A]),await t.ensureDoc("checkLastPage",[A]);const e=await t.ensureDoc("isPureXfa");if(e){const A=new Sd("loadXfaFonts");h(A),await Promise.all([t.loadXfaFonts(C,A).catch((A=>{})).then((()=>Q(A))),t.loadXfaImages()])}const[i,a]=await Promise.all([t.ensureDoc("numPages"),t.ensureDoc("fingerprints")]);return{numPages:i,fingerprints:a,htmlForXfa:e?await t.ensureDoc("htmlForXfa"):null}}return C.on("GetPage",(function(A){return t.getPage(A.pageIndex).then((function(A){return Promise.all([t.ensure(A,"rotate"),t.ensure(A,"ref"),t.ensure(A,"userUnit"),t.ensure(A,"view")]).then((function([A,e,t,i]){return{rotate:A,ref:e,refStr:e?.toString()??null,userUnit:t,view:i}}))}))})),C.on("GetPageIndex",(function(A){const e=QA.get(A.num,A.gen);return t.ensureCatalog("getPageIndex",[e])})),C.on("GetDestinations",(function(A){return t.ensureCatalog("destinations")})),C.on("GetDestination",(function(A){return t.ensureCatalog("getDestination",[A.id])})),C.on("GetPageLabels",(function(A){return t.ensureCatalog("pageLabels")})),C.on("GetPageLayout",(function(A){return t.ensureCatalog("pageLayout")})),C.on("GetPageMode",(function(A){return t.ensureCatalog("pageMode")})),C.on("GetViewerPreferences",(function(A){return t.ensureCatalog("viewerPreferences")})),C.on("GetOpenAction",(function(A){return t.ensureCatalog("openAction")})),C.on("GetAttachments",(function(A){return t.ensureCatalog("attachments")})),C.on("GetDocJSActions",(function(A){return t.ensureCatalog("jsActions")})),C.on("GetPageJSActions",(function({pageIndex:A}){return t.getPage(A).then((function(A){return t.ensure(A,"jsActions")}))})),C.on("GetOutline",(function(A){return t.ensureCatalog("documentOutline")})),C.on("GetOptionalContentConfig",(function(A){return t.ensureCatalog("optionalContentConfig")})),C.on("GetPermissions",(function(A){return t.ensureCatalog("permissions")})),C.on("GetMetadata",(function(A){return Promise.all([t.ensureDoc("documentInfo"),t.ensureCatalog("metadata")])})),C.on("GetMarkInfo",(function(A){return t.ensureCatalog("markInfo")})),C.on("GetData",(function(A){return t.requestLoadedStream().then((function(A){return A.bytes}))})),C.on("GetAnnotations",(function({pageIndex:A,intent:e}){return t.getPage(A).then((function(t){const i=new Sd(`GetAnnotations: page ${A}`);return h(i),t.getAnnotationsData(C,i,e).then((A=>(Q(i),A)),(A=>{throw Q(i),A}))}))})),C.on("GetFieldObjects",(function(A){return t.ensureDoc("fieldObjects").then((A=>A?.allFields||null))})),C.on("HasJSActions",(function(A){return t.ensureDoc("hasJSActions")})),C.on("GetCalculationOrderIds",(function(A){return t.ensureDoc("calculationOrderIds")})),C.on("SaveDocument",(async function({isPureXfa:A,numPages:e,annotationStorage:i,filename:a}){const s=[t.requestLoadedStream(),t.ensureCatalog("acroForm"),t.ensureCatalog("acroFormRef"),t.ensureDoc("startXRef"),t.ensureDoc("xref"),t.ensureDoc("linearization"),t.ensureCatalog("structTreeRoot")],n=[],g=A?null:Ae(i),[r,o,I,c,B,h,l]=await Promise.all(s),E=B.trailer.getRaw("Root")||null;let u;if(g){l?await l.canUpdateStructTree({pdfManager:t,xref:B,newAnnotationsByPage:g})&&(u=l):await io.canCreateStructureTree({catalogRef:E,pdfManager:t,newAnnotationsByPage:g})&&(u=null);const A=Uu.generateImages(i.values(),B,t.evaluatorOptions.isOffscreenCanvasSupported),e=void 0===u?n:[];for(const[i,a]of g)e.push(t.getPage(i).then((e=>{const t=new Sd(`Save (editor): page ${i}`);return e.saveNewAnnotations(C,t,a,A).finally((function(){Q(t)}))})));null===u?n.push(Promise.all(e).then((async A=>(await io.createStructureTree({newAnnotationsByPage:g,xref:B,catalogRef:E,pdfManager:t,newRefs:A}),A)))):u&&n.push(Promise.all(e).then((async A=>(await u.updateStructureTree({newAnnotationsByPage:g,pdfManager:t,newRefs:A}),A))))}if(A)n.push(t.serializeXfaData(i));else for(let A=0;AA.needAppearances)),y=o instanceof hA&&o.get("XFA")||null;let w=null,D=!1;if(Array.isArray(y)){for(let A=0,e=y.length;A{"string"==typeof t&&(A[e]=$(t))})),b={rootRef:E,encryptRef:B.trailer.getRaw("Encrypt")||null,newRef:B.getNewTemporaryRef(),infoRef:B.trailer.getRaw("Info")||null,info:A,fileIds:B.trailer.get("ID")||null,startXRef:h?c:B.lastXRefStreamPos??c,filename:a}}return to({originalData:r.bytes,xrefInfo:b,newRefs:f,xref:B,hasXfa:!!y,xfaDatasetsRef:w,hasXfaDatasetsEntry:D,needAppearances:m,acroFormRef:I,acroForm:o,xfaData:p,useXrefStream:fA(B.topDict,"XRef")}).finally((()=>{B.resetNewTemporaryRef()}))})),C.on("GetOperatorList",(function(A,e){const i=A.pageIndex;t.getPage(i).then((function(t){const a=new Sd(`GetOperatorList: page ${i}`);h(a);const s=n>=l.INFOS?Date.now():0;t.getOperatorList({handler:C,sink:e,task:a,intent:A.intent,cacheKey:A.cacheKey,annotationStorage:A.annotationStorage,modifiedIds:A.modifiedIds}).then((function(A){Q(a),s&&G(`page=${i+1} - getOperatorList: time=${Date.now()-s}ms, len=${A.length}`),e.close()}),(function(A){Q(a),a.terminated||e.error(A)}))}))})),C.on("GetTextContent",(function(A,e){const{pageIndex:i,includeMarkedContent:a,disableNormalization:s}=A;t.getPage(i).then((function(A){const t=new Sd("GetTextContent: page "+i);h(t);const g=n>=l.INFOS?Date.now():0;A.extractTextContent({handler:C,task:t,sink:e,includeMarkedContent:a,disableNormalization:s}).then((function(){Q(t),g&&G(`page=${i+1} - getTextContent: time=`+(Date.now()-g)+"ms"),e.close()}),(function(A){Q(t),t.terminated||e.error(A)}))}))})),C.on("GetStructTree",(function(A){return t.getPage(A.pageIndex).then((function(A){return t.ensure(A,"getStructTree")}))})),C.on("FontFallback",(function(A){return t.fontFallback(A.id,C)})),C.on("Cleanup",(function(A){return t.cleanup(!0)})),C.on("Terminate",(function(A){i=!0;const e=[];if(t){t.terminate(new P("Worker was terminated."));const A=t.cleanup();e.push(A),t=null}else Dr();a&&a(new P("Worker was terminated."));for(const A of s)e.push(A.finished),A.terminate();return Promise.all(e).then((function(){C.destroy(),C=null}))})),C.on("Ready",(function(e){!function(A){function e(A){B(),C.send("GetDoc",{pdfInfo:A})}function s(A){if(B(),A instanceof H){const e=new Sd(`PasswordException: response ${A.code}`);h(e),C.sendWithPromise("PasswordRequest",A).then((function({password:A}){Q(e),t.updatePassword(A),n()})).catch((function(){Q(e),C.send("DocException",A)}))}else A instanceof v||A instanceof K||A instanceof q||A instanceof Y?C.send("DocException",A):C.send("DocException",new Y(A.message,A.toString()))}function n(){B(),E(!1).then(e,(function(A){B(),A instanceof FA?t.requestLoadedStream().then((function(){B(),E(!0).then(e,s)})):s(A)}))}B(),function({data:A,password:e,disableAutoFetch:t,rangeChunkSize:i,length:s,docBaseUrl:n,enableXfa:r,evaluatorOptions:o}){const I={source:null,disableAutoFetch:t,docBaseUrl:n,docId:g,enableXfa:r,evaluatorOptions:o,handler:C,length:s,password:e,rangeChunkSize:i},c=Promise.withResolvers();let h;if(A){try{I.source=A,h=new md(I),c.resolve(h)}catch(A){c.reject(A)}return c.promise}let Q,l=[];try{Q=new bd(C)}catch(A){return c.reject(A),c.promise}const E=Q.getFullReader();E.headersReady.then((function(){if(E.isRangeSupported){I.source=Q,I.length=E.contentLength,I.disableAutoFetch||=E.isStreamingSupported,h=new yd(I);for(const A of l)h.sendProgressiveData(A);l=[],c.resolve(h),a=null}})).catch((function(A){c.reject(A),a=null}));let u=0;return new Promise((function(A,e){const t=function({value:A,done:i}){try{if(B(),i)return h||function(){const A=SA(l);s&&A.length!==s&&N("reported HTTP length is different from actual");try{I.source=A,h=new md(I),c.resolve(h)}catch(A){c.reject(A)}l=[]}(),void(a=null);u+=A.byteLength,E.isStreamingSupported||C.send("DocProgress",{loaded:u,total:Math.max(u,E.contentLength||0)}),h?h.sendProgressiveData(A):l.push(A),E.read().then(t,e)}catch(A){e(A)}};E.read().then(t,e)})).catch((function(A){c.reject(A),a=null})),a=function(A){Q.cancelAllRequests(A)},c.promise}(A).then((function(A){if(i)throw A.terminate(new P("Worker was terminated.")),new Error("Worker was terminated");t=A,t.requestLoadedStream(!0).then((A=>{C.send("DataLoaded",{length:A.bytes.byteLength})}))})).then(n,s)}(A),A=null})),c}static initializeFromPort(A){const e=new Dd("worker","main",A);Rd.setup(e,A),e.send("ready",null)}}var Gd;return"undefined"==typeof window&&!t&&"undefined"!=typeof self&&"function"==typeof(Gd=self).postMessage&&"onmessage"in Gd&&Rd.initializeFromPort(self),{}})())); \ No newline at end of file diff --git a/dist/352.index.js b/dist/352.index.js deleted file mode 100644 index df036d5..0000000 --- a/dist/352.index.js +++ /dev/null @@ -1,2 +0,0 @@ -/*! For license information please see 352.index.js.LICENSE.txt */ -"use strict";(self.webpackChunkFileViewer=self.webpackChunkFileViewer||[]).push([[352],{352:(t,e,i)=>{i.r(e),i.d(e,{AbortException:()=>ps,AnnotationEditorLayer:()=>gs,AnnotationEditorParamsType:()=>ms,AnnotationEditorType:()=>fs,AnnotationEditorUIManager:()=>bs,AnnotationLayer:()=>vs,AnnotationMode:()=>As,CMapCompressionType:()=>ys,ColorPicker:()=>ws,DOMSVGFactory:()=>_s,DrawLayer:()=>xs,FeatureTest:()=>Cs,GlobalWorkerOptions:()=>Es,ImageKind:()=>Ss,InvalidPDFException:()=>Ts,MissingPDFException:()=>Ms,OPS:()=>ks,OutputScale:()=>Is,PDFDataRangeTransport:()=>Ps,PDFDateString:()=>Rs,PDFWorker:()=>Ds,PasswordResponses:()=>Ls,PermissionFlag:()=>Fs,PixelsPerInch:()=>Ns,RenderingCancelledException:()=>Os,TextLayer:()=>Bs,UnexpectedResponseException:()=>zs,Util:()=>Hs,VerbosityLevel:()=>js,XfaLayer:()=>Us,build:()=>$s,createValidAbsoluteUrl:()=>Ws,fetchData:()=>Gs,getDocument:()=>Vs,getFilenameFromUrl:()=>qs,getPdfFilenameFromUrl:()=>Xs,getXfaPageViewport:()=>Ks,isDataScheme:()=>Ys,isPdfFile:()=>Qs,noContextMenu:()=>Js,normalizeUnicode:()=>Zs,setLayerDimensions:()=>tn,shadow:()=>en,version:()=>sn});var s={d:(t,e)=>{for(var i in e)s.o(e,i)&&!s.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e)},n=globalThis.pdfjsLib={};s.d(n,{AbortException:()=>L,AnnotationEditorLayer:()=>cs,AnnotationEditorParamsType:()=>c,AnnotationEditorType:()=>d,AnnotationEditorUIManager:()=>Mt,AnnotationLayer:()=>Zi,AnnotationMode:()=>h,CMapCompressionType:()=>m,ColorPicker:()=>os,DOMSVGFactory:()=>et,DrawLayer:()=>us,FeatureTest:()=>B,GlobalWorkerOptions:()=>be,ImageKind:()=>p,InvalidPDFException:()=>I,MissingPDFException:()=>P,OPS:()=>f,OutputScale:()=>At,PDFDataRangeTransport:()=>oi,PDFDateString:()=>pt,PDFWorker:()=>ci,PasswordResponses:()=>b,PermissionFlag:()=>u,PixelsPerInch:()=>Q,RenderingCancelledException:()=>st,TextLayer:()=>Qe,UnexpectedResponseException:()=>R,Util:()=>H,VerbosityLevel:()=>g,XfaLayer:()=>_i,build:()=>vi,createValidAbsoluteUrl:()=>E,fetchData:()=>J,getDocument:()=>ni,getFilenameFromUrl:()=>rt,getPdfFilenameFromUrl:()=>ot,getXfaPageViewport:()=>gt,isDataScheme:()=>nt,isPdfFile:()=>at,noContextMenu:()=>dt,normalizeUnicode:()=>$,setLayerDimensions:()=>vt,shadow:()=>S,version:()=>bi});const a=!("object"!=typeof process||process+""!="[object process]"||process.versions.nw||process.versions.electron&&process.type&&"browser"!==process.type),r=[1,0,0,1,0,0],o=[.001,0,0,.001,0,0],l=1.35,h={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},d={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15},c={RESIZE:1,CREATE:2,FREETEXT_SIZE:11,FREETEXT_COLOR:12,FREETEXT_OPACITY:13,INK_COLOR:21,INK_THICKNESS:22,INK_OPACITY:23,HIGHLIGHT_COLOR:31,HIGHLIGHT_DEFAULT_COLOR:32,HIGHLIGHT_THICKNESS:33,HIGHLIGHT_FREE:34,HIGHLIGHT_SHOW_ALL:35},u={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},p={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},g={ERRORS:0,WARNINGS:1,INFOS:5},m={NONE:0,BINARY:1},f={dependency:1,setLineWidth:2,setLineCap:3,setLineJoin:4,setMiterLimit:5,setDash:6,setRenderingIntent:7,setFlatness:8,setGState:9,save:10,restore:11,transform:12,moveTo:13,lineTo:14,curveTo:15,curveTo2:16,curveTo3:17,closePath:18,rectangle:19,stroke:20,closeStroke:21,fill:22,eoFill:23,fillStroke:24,eoFillStroke:25,closeFillStroke:26,closeEOFillStroke:27,endPath:28,clip:29,eoClip:30,beginText:31,endText:32,setCharSpacing:33,setWordSpacing:34,setHScale:35,setLeading:36,setFont:37,setTextRenderingMode:38,setTextRise:39,moveText:40,setLeadingMoveText:41,setTextMatrix:42,nextLine:43,showText:44,showSpacedText:45,nextLineShowText:46,nextLineSetSpacingShowText:47,setCharWidth:48,setCharWidthAndBounds:49,setStrokeColorSpace:50,setFillColorSpace:51,setStrokeColor:52,setStrokeColorN:53,setFillColor:54,setFillColorN:55,setStrokeGray:56,setFillGray:57,setStrokeRGBColor:58,setFillRGBColor:59,setStrokeCMYKColor:60,setFillCMYKColor:61,shadingFill:62,beginInlineImage:63,beginImageData:64,endInlineImage:65,paintXObject:66,markPoint:67,markPointProps:68,beginMarkedContent:69,beginMarkedContentProps:70,endMarkedContent:71,beginCompat:72,endCompat:73,paintFormXObjectBegin:74,paintFormXObjectEnd:75,beginGroup:76,endGroup:77,beginAnnotation:80,endAnnotation:81,paintImageMaskXObject:83,paintImageMaskXObjectGroup:84,paintImageXObject:85,paintInlineImageXObject:86,paintInlineImageXObjectGroup:87,paintImageXObjectRepeat:88,paintImageMaskXObjectRepeat:89,paintSolidColorImageMask:90,constructPath:91,setStrokeTransparent:92,setFillTransparent:93},b={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let v=g.WARNINGS;function A(t){Number.isInteger(t)&&(v=t)}function y(){return v}function w(t){v>=g.INFOS&&console.log(`Info: ${t}`)}function _(t){v>=g.WARNINGS&&console.log(`Warning: ${t}`)}function x(t){throw new Error(t)}function C(t,e){t||x(e)}function E(t,e=null,i=null){if(!t)return null;try{if(i&&"string"==typeof t){if(i.addDefaultProtocol&&t.startsWith("www.")){const e=t.match(/\./g);e?.length>=2&&(t=`http://${t}`)}if(i.tryConvertEncoding)try{t=decodeURIComponent(escape(t))}catch{}}const s=e?new URL(t,e):new URL(t);if(function(t){switch(t?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}(s))return s}catch{}return null}function S(t,e,i,s=!1){return Object.defineProperty(t,e,{value:i,enumerable:!s,configurable:!0,writable:!1}),i}const T=function(){function t(t,e){this.message=t,this.name=e}return t.prototype=new Error,t.constructor=t,t}();class M extends T{constructor(t,e){super(t,"PasswordException"),this.code=e}}class k extends T{constructor(t,e){super(t,"UnknownErrorException"),this.details=e}}class I extends T{constructor(t){super(t,"InvalidPDFException")}}class P extends T{constructor(t){super(t,"MissingPDFException")}}class R extends T{constructor(t,e){super(t,"UnexpectedResponseException"),this.status=e}}class D extends T{constructor(t){super(t,"FormatError")}}class L extends T{constructor(t){super(t,"AbortException")}}function F(t){"object"==typeof t&&void 0!==t?.length||x("Invalid argument for bytesToString");const e=t.length,i=8192;if(et.toString(16).padStart(2,"0")));class H{static makeHexColor(t,e,i){return`#${z[t]}${z[e]}${z[i]}`}static scaleMinMax(t,e){let i;t[0]?(t[0]<0&&(i=e[0],e[0]=e[2],e[2]=i),e[0]*=t[0],e[2]*=t[0],t[3]<0&&(i=e[1],e[1]=e[3],e[3]=i),e[1]*=t[3],e[3]*=t[3]):(i=e[0],e[0]=e[1],e[1]=i,i=e[2],e[2]=e[3],e[3]=i,t[1]<0&&(i=e[1],e[1]=e[3],e[3]=i),e[1]*=t[1],e[3]*=t[1],t[2]<0&&(i=e[0],e[0]=e[2],e[2]=i),e[0]*=t[2],e[2]*=t[2]),e[0]+=t[4],e[1]+=t[5],e[2]+=t[4],e[3]+=t[5]}static transform(t,e){return[t[0]*e[0]+t[2]*e[1],t[1]*e[0]+t[3]*e[1],t[0]*e[2]+t[2]*e[3],t[1]*e[2]+t[3]*e[3],t[0]*e[4]+t[2]*e[5]+t[4],t[1]*e[4]+t[3]*e[5]+t[5]]}static applyTransform(t,e){return[t[0]*e[0]+t[1]*e[2]+e[4],t[0]*e[1]+t[1]*e[3]+e[5]]}static applyInverseTransform(t,e){const i=e[0]*e[3]-e[1]*e[2];return[(t[0]*e[3]-t[1]*e[2]+e[2]*e[5]-e[4]*e[3])/i,(-t[0]*e[1]+t[1]*e[0]+e[4]*e[1]-e[5]*e[0])/i]}static getAxialAlignedBoundingBox(t,e){const i=this.applyTransform(t,e),s=this.applyTransform(t.slice(2,4),e),n=this.applyTransform([t[0],t[3]],e),a=this.applyTransform([t[2],t[1]],e);return[Math.min(i[0],s[0],n[0],a[0]),Math.min(i[1],s[1],n[1],a[1]),Math.max(i[0],s[0],n[0],a[0]),Math.max(i[1],s[1],n[1],a[1])]}static inverseTransform(t){const e=t[0]*t[3]-t[1]*t[2];return[t[3]/e,-t[1]/e,-t[2]/e,t[0]/e,(t[2]*t[5]-t[4]*t[3])/e,(t[4]*t[1]-t[5]*t[0])/e]}static singularValueDecompose2dScale(t){const e=[t[0],t[2],t[1],t[3]],i=t[0]*e[0]+t[1]*e[2],s=t[0]*e[1]+t[1]*e[3],n=t[2]*e[0]+t[3]*e[2],a=t[2]*e[1]+t[3]*e[3],r=(i+a)/2,o=Math.sqrt((i+a)**2-4*(i*a-n*s))/2,l=r+o||1,h=r-o||1;return[Math.sqrt(l),Math.sqrt(h)]}static normalizeRect(t){const e=t.slice(0);return t[0]>t[2]&&(e[0]=t[2],e[2]=t[0]),t[1]>t[3]&&(e[1]=t[3],e[3]=t[1]),e}static intersect(t,e){const i=Math.max(Math.min(t[0],t[2]),Math.min(e[0],e[2])),s=Math.min(Math.max(t[0],t[2]),Math.max(e[0],e[2]));if(i>s)return null;const n=Math.max(Math.min(t[1],t[3]),Math.min(e[1],e[3])),a=Math.min(Math.max(t[1],t[3]),Math.max(e[1],e[3]));return n>a?null:[i,n,s,a]}static#t(t,e,i,s,n,a,r,o,l,h){if(l<=0||l>=1)return;const d=1-l,c=l*l,u=c*l,p=d*(d*(d*t+3*l*e)+3*c*i)+u*s,g=d*(d*(d*n+3*l*a)+3*c*r)+u*o;h[0]=Math.min(h[0],p),h[1]=Math.min(h[1],g),h[2]=Math.max(h[2],p),h[3]=Math.max(h[3],g)}static#e(t,e,i,s,n,a,r,o,l,h,d,c){if(Math.abs(l)<1e-12)return void(Math.abs(h)>=1e-12&&this.#t(t,e,i,s,n,a,r,o,-d/h,c));const u=h**2-4*d*l;if(u<0)return;const p=Math.sqrt(u),g=2*l;this.#t(t,e,i,s,n,a,r,o,(-h+p)/g,c),this.#t(t,e,i,s,n,a,r,o,(-h-p)/g,c)}static bezierBoundingBox(t,e,i,s,n,a,r,o,l){return l?(l[0]=Math.min(l[0],t,r),l[1]=Math.min(l[1],e,o),l[2]=Math.max(l[2],t,r),l[3]=Math.max(l[3],e,o)):l=[Math.min(t,r),Math.min(e,o),Math.max(t,r),Math.max(e,o)],this.#e(t,i,n,r,e,s,a,o,3*(3*(i-n)-t+r),6*(t-2*i+n),3*(i-t),l),this.#e(t,i,n,r,e,s,a,o,3*(3*(s-a)-e+o),6*(e-2*s+a),3*(s-e),l),l}}let j=null,U=null;function $(t){return j||(j=/([\u00a0\u00b5\u037e\u0eb3\u2000-\u200a\u202f\u2126\ufb00-\ufb04\ufb06\ufb20-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufba1\ufba4-\ufba9\ufbae-\ufbb1\ufbd3-\ufbdc\ufbde-\ufbe7\ufbea-\ufbf8\ufbfc-\ufbfd\ufc00-\ufc5d\ufc64-\ufcf1\ufcf5-\ufd3d\ufd88\ufdf4\ufdfa-\ufdfb\ufe71\ufe77\ufe79\ufe7b\ufe7d]+)|(\ufb05+)/gu,U=new Map([["ſt","ſt"]])),t.replaceAll(j,((t,e,i)=>e?e.normalize("NFKC"):U.get(i)))}const W="pdfjs_internal_id_";class G{addFilter(t){return"none"}addHCMFilter(t,e){return"none"}addAlphaFilter(t){return"none"}addLuminosityFilter(t){return"none"}addHighlightHCMFilter(t,e,i,s,n){return"none"}destroy(t=!1){}}class V{#i=!1;constructor({enableHWA:t=!1}){this.#i=t}create(t,e){if(t<=0||e<=0)throw new Error("Invalid canvas size");const i=this._createCanvas(t,e);return{canvas:i,context:i.getContext("2d",{willReadFrequently:!this.#i})}}reset(t,e,i){if(!t.canvas)throw new Error("Canvas is not specified");if(e<=0||i<=0)throw new Error("Invalid canvas size");t.canvas.width=e,t.canvas.height=i}destroy(t){if(!t.canvas)throw new Error("Canvas is not specified");t.canvas.width=0,t.canvas.height=0,t.canvas=null,t.context=null}_createCanvas(t,e){x("Abstract method `_createCanvas` called.")}}class q{constructor({baseUrl:t=null,isCompressed:e=!0}){this.baseUrl=t,this.isCompressed=e}async fetch({name:t}){if(!this.baseUrl)throw new Error("Ensure that the `cMapUrl` and `cMapPacked` API parameters are provided.");if(!t)throw new Error("CMap name must be specified.");const e=this.baseUrl+t+(this.isCompressed?".bcmap":""),i=this.isCompressed?m.BINARY:m.NONE;return this._fetchData(e,i).catch((t=>{throw new Error(`Unable to load ${this.isCompressed?"binary ":""}CMap at: ${e}`)}))}_fetchData(t,e){x("Abstract method `_fetchData` called.")}}class X{constructor({baseUrl:t=null}){this.baseUrl=t}async fetch({filename:t}){if(!this.baseUrl)throw new Error("Ensure that the `standardFontDataUrl` API parameter is provided.");if(!t)throw new Error("Font filename must be specified.");const e=`${this.baseUrl}${t}`;return this._fetchData(e).catch((t=>{throw new Error(`Unable to load font data at: ${e}`)}))}_fetchData(t){x("Abstract method `_fetchData` called.")}}class K{create(t,e,i=!1){if(t<=0||e<=0)throw new Error("Invalid SVG dimensions");const s=this._createSVG("svg:svg");return s.setAttribute("version","1.1"),i||(s.setAttribute("width",`${t}px`),s.setAttribute("height",`${e}px`)),s.setAttribute("preserveAspectRatio","none"),s.setAttribute("viewBox",`0 0 ${t} ${e}`),s}createElement(t){if("string"!=typeof t)throw new Error("Invalid SVG element type");return this._createSVG(t)}_createSVG(t){x("Abstract method `_createSVG` called.")}}const Y="http://www.w3.org/2000/svg";class Q{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF}async function J(t,e="text"){if(ht(t,document.baseURI)){const i=await fetch(t);if(!i.ok)throw new Error(i.statusText);switch(e){case"arraybuffer":return i.arrayBuffer();case"blob":return i.blob();case"json":return i.json()}return i.text()}return new Promise(((i,s)=>{const n=new XMLHttpRequest;n.open("GET",t,!0),n.responseType=e,n.onreadystatechange=()=>{if(n.readyState===XMLHttpRequest.DONE)if(200!==n.status&&0!==n.status)s(new Error(n.statusText));else{switch(e){case"arraybuffer":case"blob":case"json":return void i(n.response)}i(n.responseText)}},n.send(null)}))}class Z extends q{_fetchData(t,e){return J(t,this.isCompressed?"arraybuffer":"text").then((t=>({cMapData:t instanceof ArrayBuffer?new Uint8Array(t):N(t),compressionType:e})))}}class tt extends X{_fetchData(t){return J(t,"arraybuffer").then((t=>new Uint8Array(t)))}}class et extends K{_createSVG(t){return document.createElementNS(Y,t)}}class it{constructor({viewBox:t,scale:e,rotation:i,offsetX:s=0,offsetY:n=0,dontFlip:a=!1}){this.viewBox=t,this.scale=e,this.rotation=i,this.offsetX=s,this.offsetY=n;const r=(t[2]+t[0])/2,o=(t[3]+t[1])/2;let l,h,d,c,u,p,g,m;switch((i%=360)<0&&(i+=360),i){case 180:l=-1,h=0,d=0,c=1;break;case 90:l=0,h=1,d=1,c=0;break;case 270:l=0,h=-1,d=-1,c=0;break;case 0:l=1,h=0,d=0,c=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}a&&(d=-d,c=-c),0===l?(u=Math.abs(o-t[1])*e+s,p=Math.abs(r-t[0])*e+n,g=(t[3]-t[1])*e,m=(t[2]-t[0])*e):(u=Math.abs(r-t[0])*e+s,p=Math.abs(o-t[1])*e+n,g=(t[2]-t[0])*e,m=(t[3]-t[1])*e),this.transform=[l*e,h*e,d*e,c*e,u-l*e*r-d*e*o,p-h*e*r-c*e*o],this.width=g,this.height=m}get rawDims(){const{viewBox:t}=this;return S(this,"rawDims",{pageWidth:t[2]-t[0],pageHeight:t[3]-t[1],pageX:t[0],pageY:t[1]})}clone({scale:t=this.scale,rotation:e=this.rotation,offsetX:i=this.offsetX,offsetY:s=this.offsetY,dontFlip:n=!1}={}){return new it({viewBox:this.viewBox.slice(),scale:t,rotation:e,offsetX:i,offsetY:s,dontFlip:n})}convertToViewportPoint(t,e){return H.applyTransform([t,e],this.transform)}convertToViewportRectangle(t){const e=H.applyTransform([t[0],t[1]],this.transform),i=H.applyTransform([t[2],t[3]],this.transform);return[e[0],e[1],i[0],i[1]]}convertToPdfPoint(t,e){return H.applyInverseTransform([t,e],this.transform)}}class st extends T{constructor(t,e=0){super(t,"RenderingCancelledException"),this.extraDelay=e}}function nt(t){const e=t.length;let i=0;for(;i=1&&s<=12?s-1:0;let n=parseInt(e[3],10);n=n>=1&&n<=31?n:1;let a=parseInt(e[4],10);a=a>=0&&a<=23?a:0;let r=parseInt(e[5],10);r=r>=0&&r<=59?r:0;let o=parseInt(e[6],10);o=o>=0&&o<=59?o:0;const l=e[7]||"Z";let h=parseInt(e[8],10);h=h>=0&&h<=23?h:0;let d=parseInt(e[9],10)||0;return d=d>=0&&d<=59?d:0,"-"===l?(a+=h,r+=d):"+"===l&&(a-=h,r-=d),new Date(Date.UTC(i,s,n,a,r,o))}}function gt(t,{scale:e=1,rotation:i=0}){const{width:s,height:n}=t.attributes.style,a=[0,0,parseInt(s),parseInt(n)];return new it({viewBox:a,scale:e,rotation:i})}function mt(t){if(t.startsWith("#")){const e=parseInt(t.slice(1),16);return[(16711680&e)>>16,(65280&e)>>8,255&e]}return t.startsWith("rgb(")?t.slice(4,-1).split(",").map((t=>parseInt(t))):t.startsWith("rgba(")?t.slice(5,-1).split(",").map((t=>parseInt(t))).slice(0,3):(_(`Not a valid color format: "${t}"`),[0,0,0])}function ft(t){const{a:e,b:i,c:s,d:n,e:a,f:r}=t.getTransform();return[e,i,s,n,a,r]}function bt(t){const{a:e,b:i,c:s,d:n,e:a,f:r}=t.getTransform().invertSelf();return[e,i,s,n,a,r]}function vt(t,e,i=!1,s=!0){if(e instanceof it){const{pageWidth:s,pageHeight:n}=e.rawDims,{style:a}=t,r=B.isCSSRoundSupported,o=`var(--scale-factor) * ${s}px`,l=`var(--scale-factor) * ${n}px`,h=r?`round(down, ${o}, var(--scale-round-x, 1px))`:`calc(${o})`,d=r?`round(down, ${l}, var(--scale-round-y, 1px))`:`calc(${l})`;i&&e.rotation%180!=0?(a.width=d,a.height=h):(a.width=h,a.height=d)}s&&t.setAttribute("data-main-rotation",e.rotation)}class At{constructor(){const t=window.devicePixelRatio||1;this.sx=t,this.sy=t}get scaled(){return 1!==this.sx||1!==this.sy}get symmetric(){return this.sx===this.sy}}class yt{#s=null;#n=null;#a;#r=null;#o=null;static#l=null;constructor(t){this.#a=t,yt.#l||=Object.freeze({freetext:"pdfjs-editor-remove-freetext-button",highlight:"pdfjs-editor-remove-highlight-button",ink:"pdfjs-editor-remove-ink-button",stamp:"pdfjs-editor-remove-stamp-button"})}render(){const t=this.#s=document.createElement("div");t.classList.add("editToolbar","hidden"),t.setAttribute("role","toolbar");const e=this.#a._uiManager._signal;t.addEventListener("contextmenu",dt,{signal:e}),t.addEventListener("pointerdown",yt.#h,{signal:e});const i=this.#r=document.createElement("div");i.className="buttons",t.append(i);const s=this.#a.toolbarPosition;if(s){const{style:e}=t,i="ltr"===this.#a._uiManager.direction?1-s[0]:s[0];e.insetInlineEnd=100*i+"%",e.top=`calc(${100*s[1]}% + var(--editor-toolbar-vert-offset))`}return this.#d(),t}get div(){return this.#s}static#h(t){t.stopPropagation()}#c(t){this.#a._focusEventsAllowed=!1,t.preventDefault(),t.stopPropagation()}#u(t){this.#a._focusEventsAllowed=!0,t.preventDefault(),t.stopPropagation()}#p(t){const e=this.#a._uiManager._signal;t.addEventListener("focusin",this.#c.bind(this),{capture:!0,signal:e}),t.addEventListener("focusout",this.#u.bind(this),{capture:!0,signal:e}),t.addEventListener("contextmenu",dt,{signal:e})}hide(){this.#s.classList.add("hidden"),this.#n?.hideDropdown()}show(){this.#s.classList.remove("hidden"),this.#o?.shown()}#d(){const{editorType:t,_uiManager:e}=this.#a,i=document.createElement("button");i.className="delete",i.tabIndex=0,i.setAttribute("data-l10n-id",yt.#l[t]),this.#p(i),i.addEventListener("click",(t=>{e.delete()}),{signal:e._signal}),this.#r.append(i)}get#g(){const t=document.createElement("div");return t.className="divider",t}async addAltText(t){const e=await t.render();this.#p(e),this.#r.prepend(e,this.#g),this.#o=t}addColorPicker(t){this.#n=t;const e=t.renderButton();this.#p(e),this.#r.prepend(e,this.#g)}remove(){this.#s.remove(),this.#n?.destroy(),this.#n=null}}class wt{#r=null;#s=null;#m;constructor(t){this.#m=t}#f(){const t=this.#s=document.createElement("div");t.className="editToolbar",t.setAttribute("role","toolbar"),t.addEventListener("contextmenu",dt,{signal:this.#m._signal});const e=this.#r=document.createElement("div");return e.className="buttons",t.append(e),this.#b(),t}#v(t,e){let i=0,s=0;for(const n of t){const t=n.y+n.height;if(ti?(s=a,i=t):e?a>s&&(s=a):a{this.#m.highlightSelection("floating_button")}),{signal:i}),this.#r.append(t)}}function _t(t,e,i){for(const s of i)e.addEventListener(s,t[s].bind(t))}class xt{#A=0;get id(){return"pdfjs_internal_editor_"+this.#A++}}class Ct{#y=function(){if("undefined"!=typeof crypto&&"function"==typeof crypto?.randomUUID)return crypto.randomUUID();const t=new Uint8Array(32);if("undefined"!=typeof crypto&&"function"==typeof crypto?.getRandomValues)crypto.getRandomValues(t);else for(let e=0;e<32;e++)t[e]=Math.floor(255*Math.random());return F(t)}();#A=0;#w=null;static get _isSVGFittingCanvas(){const t=new OffscreenCanvas(1,3).getContext("2d",{willReadFrequently:!0}),e=new Image;return e.src='data:image/svg+xml;charset=UTF-8,',S(this,"_isSVGFittingCanvas",e.decode().then((()=>(t.drawImage(e,0,0,1,1,0,0,1,3),0===new Uint32Array(t.getImageData(0,0,1,1).data.buffer)[0]))))}async#_(t,e){this.#w||=new Map;let i=this.#w.get(t);if(null===i)return null;if(i?.bitmap)return i.refCounter+=1,i;try{let t;if(i||={bitmap:null,id:`image_${this.#y}_${this.#A++}`,refCounter:0,isSvg:!1},"string"==typeof e?(i.url=e,t=await J(e,"blob")):e instanceof File?t=i.file=e:e instanceof Blob&&(t=e),"image/svg+xml"===t.type){const e=Ct._isSVGFittingCanvas,s=new FileReader,n=new Image,a=new Promise(((t,a)=>{n.onload=()=>{i.bitmap=n,i.isSvg=!0,t()},s.onload=async()=>{const t=i.svgUrl=s.result;n.src=await e?`${t}#svgView(preserveAspectRatio(none))`:t},n.onerror=s.onerror=a}));s.readAsDataURL(t),await a}else i.bitmap=await createImageBitmap(t);i.refCounter=1}catch(t){console.error(t),i=null}return this.#w.set(t,i),i&&this.#w.set(i.id,i),i}async getFromFile(t){const{lastModified:e,name:i,size:s,type:n}=t;return this.#_(`${e}_${i}_${s}_${n}`,t)}async getFromUrl(t){return this.#_(t,t)}async getFromBlob(t,e){const i=await e;return this.#_(t,i)}async getFromId(t){this.#w||=new Map;const e=this.#w.get(t);if(!e)return null;if(e.bitmap)return e.refCounter+=1,e;if(e.file)return this.getFromFile(e.file);if(e.blobPromise){const{blobPromise:t}=e;return delete e.blobPromise,this.getFromBlob(e.id,t)}return this.getFromUrl(e.url)}getFromCanvas(t,e){this.#w||=new Map;let i=this.#w.get(t);if(i?.bitmap)return i.refCounter+=1,i;const s=new OffscreenCanvas(e.width,e.height);return s.getContext("2d").drawImage(e,0,0),i={bitmap:s.transferToImageBitmap(),id:`image_${this.#y}_${this.#A++}`,refCounter:1,isSvg:!1},this.#w.set(t,i),this.#w.set(i.id,i),i}getSvgUrl(t){const e=this.#w.get(t);return e?.isSvg?e.svgUrl:null}deleteId(t){this.#w||=new Map;const e=this.#w.get(t);if(!e)return;if(e.refCounter-=1,0!==e.refCounter)return;const{bitmap:i}=e;if(!e.url&&!e.file){const t=new OffscreenCanvas(i.width,i.height);t.getContext("bitmaprenderer").transferFromImageBitmap(i),e.blobPromise=t.convertToBlob()}i.close?.(),e.bitmap=null}isValidId(t){return t.startsWith(`image_${this.#y}_`)}}class Et{#x=[];#C=!1;#E;#S=-1;constructor(t=128){this.#E=t}add({cmd:t,undo:e,post:i,mustExec:s,type:n=NaN,overwriteIfSameType:a=!1,keepUndo:r=!1}){if(s&&t(),this.#C)return;const o={cmd:t,undo:e,post:i,type:n};if(-1===this.#S)return this.#x.length>0&&(this.#x.length=0),this.#S=0,void this.#x.push(o);if(a&&this.#x[this.#S].type===n)return r&&(o.undo=this.#x[this.#S].undo),void(this.#x[this.#S]=o);const l=this.#S+1;l===this.#E?this.#x.splice(0,1):(this.#S=l,lt===e[i])))return Tt._colorsMapping.get(t);return e}getHexCode(t){const e=this._colors.get(t);return e?H.makeHexColor(...e):t}}class Mt{#M=new AbortController;#k=null;#I=new Map;#P=new Map;#R=null;#D=null;#L=null;#F=new Et;#N=null;#O=0;#B=new Set;#z=null;#H=null;#j=new Set;#U=!1;#$=!1;#W=!1;#G=null;#V=null;#q=null;#X=null;#K=!1;#Y=null;#Q=new xt;#J=!1;#Z=!1;#tt=null;#et=null;#it=null;#st=null;#nt=d.NONE;#at=new Set;#rt=null;#ot=null;#lt=null;#ht={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1};#dt=[0,0];#ct=null;#ut=null;#pt=null;#gt=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){const t=Mt.prototype,e=t=>t.#ut.contains(document.activeElement)&&"BUTTON"!==document.activeElement.tagName&&t.hasSomethingToControl(),i=(t,{target:e})=>{if(e instanceof HTMLInputElement){const{type:t}=e;return"text"!==t&&"number"!==t}return!0},s=this.TRANSLATE_SMALL,n=this.TRANSLATE_BIG;return S(this,"_keyboardManager",new St([[["ctrl+a","mac+meta+a"],t.selectAll,{checker:i}],[["ctrl+z","mac+meta+z"],t.undo,{checker:i}],[["ctrl+y","ctrl+shift+z","mac+meta+shift+z","ctrl+shift+Z","mac+meta+shift+Z"],t.redo,{checker:i}],[["Backspace","alt+Backspace","ctrl+Backspace","shift+Backspace","mac+Backspace","mac+alt+Backspace","mac+ctrl+Backspace","Delete","ctrl+Delete","shift+Delete","mac+Delete"],t.delete,{checker:i}],[["Enter","mac+Enter"],t.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#ut.contains(e)&&!t.isEnterHandled}],[[" ","mac+ "],t.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#ut.contains(document.activeElement)}],[["Escape","mac+Escape"],t.unselectAll],[["ArrowLeft","mac+ArrowLeft"],t.translateSelectedEditors,{args:[-s,0],checker:e}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t.translateSelectedEditors,{args:[-n,0],checker:e}],[["ArrowRight","mac+ArrowRight"],t.translateSelectedEditors,{args:[s,0],checker:e}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t.translateSelectedEditors,{args:[n,0],checker:e}],[["ArrowUp","mac+ArrowUp"],t.translateSelectedEditors,{args:[0,-s],checker:e}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t.translateSelectedEditors,{args:[0,-n],checker:e}],[["ArrowDown","mac+ArrowDown"],t.translateSelectedEditors,{args:[0,s],checker:e}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t.translateSelectedEditors,{args:[0,n],checker:e}]]))}constructor(t,e,i,s,n,a,r,o,l,h,d){const c=this._signal=this.#M.signal;this.#ut=t,this.#pt=e,this.#R=i,this._eventBus=s,s._on("editingaction",this.onEditingAction.bind(this),{signal:c}),s._on("pagechanging",this.onPageChanging.bind(this),{signal:c}),s._on("scalechanging",this.onScaleChanging.bind(this),{signal:c}),s._on("rotationchanging",this.onRotationChanging.bind(this),{signal:c}),s._on("setpreference",this.onSetPreference.bind(this),{signal:c}),s._on("switchannotationeditorparams",(t=>this.updateParams(t.type,t.value)),{signal:c}),this.#mt(),this.#ft(),this.#bt(),this.#D=n.annotationStorage,this.#G=n.filterFactory,this.#ot=a,this.#X=r||null,this.#U=o,this.#$=l,this.#W=h,this.#st=d||null,this.viewParameters={realScale:Q.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1}destroy(){this.#gt?.resolve(),this.#gt=null,this.#M?.abort(),this.#M=null,this._signal=null;for(const t of this.#P.values())t.destroy();this.#P.clear(),this.#I.clear(),this.#j.clear(),this.#k=null,this.#at.clear(),this.#F.destroy(),this.#R?.destroy(),this.#Y?.hide(),this.#Y=null,this.#V&&(clearTimeout(this.#V),this.#V=null),this.#ct&&(clearTimeout(this.#ct),this.#ct=null)}combinedSignal(t){return AbortSignal.any([this._signal,t.signal])}get mlManager(){return this.#st}get useNewAltTextFlow(){return this.#$}get useNewAltTextWhenAddingImage(){return this.#W}get hcmFilter(){return S(this,"hcmFilter",this.#ot?this.#G.addHCMFilter(this.#ot.foreground,this.#ot.background):"none")}get direction(){return S(this,"direction",getComputedStyle(this.#ut).direction)}get highlightColors(){return S(this,"highlightColors",this.#X?new Map(this.#X.split(",").map((t=>t.split("=").map((t=>t.trim()))))):null)}get highlightColorNames(){return S(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,(t=>t.reverse()))):null)}setMainHighlightColorPicker(t){this.#it=t}editAltText(t,e=!1){this.#R?.editAltText(this,t,e)}switchToMode(t,e){this._eventBus.on("annotationeditormodechanged",e,{once:!0,signal:this._signal}),this._eventBus.dispatch("showannotationeditorui",{source:this,mode:t})}setPreference(t,e){this._eventBus.dispatch("setpreference",{source:this,name:t,value:e})}onSetPreference({name:t,value:e}){"enableNewAltTextWhenAddingImage"===t&&(this.#W=e)}onPageChanging({pageNumber:t}){this.#O=t-1}focusMainContainer(){this.#ut.focus()}findParent(t,e){for(const i of this.#P.values()){const{x:s,y:n,width:a,height:r}=i.div.getBoundingClientRect();if(t>=s&&t<=s+a&&e>=n&&e<=n+r)return i}return null}disableUserSelect(t=!1){this.#pt.classList.toggle("noUserSelect",t)}addShouldRescale(t){this.#j.add(t)}removeShouldRescale(t){this.#j.delete(t)}onScaleChanging({scale:t}){this.commitOrRemove(),this.viewParameters.realScale=t*Q.PDF_TO_CSS_UNITS;for(const t of this.#j)t.onScaleChanging()}onRotationChanging({pagesRotation:t}){this.commitOrRemove(),this.viewParameters.rotation=t}#vt({anchorNode:t}){return t.nodeType===Node.TEXT_NODE?t.parentElement:t}#At(t){const{currentLayer:e}=this;if(e.hasTextLayer(t))return e;for(const e of this.#P.values())if(e.hasTextLayer(t))return e;return null}highlightSelection(t=""){const e=document.getSelection();if(!e||e.isCollapsed)return;const{anchorNode:i,anchorOffset:s,focusNode:n,focusOffset:a}=e,r=e.toString(),o=this.#vt(e).closest(".textLayer"),l=this.getSelectionBoxes(o);if(!l)return;e.empty();const h=this.#At(o),c=this.#nt===d.NONE,u=()=>{h?.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:t,boxes:l,anchorNode:i,anchorOffset:s,focusNode:n,focusOffset:a,text:r}),c&&this.showAllEditors("highlight",!0,!0)};c?this.switchToMode(d.HIGHLIGHT,u):u()}#yt(){const t=document.getSelection();if(!t||t.isCollapsed)return;const e=this.#vt(t).closest(".textLayer"),i=this.getSelectionBoxes(e);i&&(this.#Y||=new wt(this),this.#Y.show(e,i,"ltr"===this.direction))}addToAnnotationStorage(t){t.isEmpty()||!this.#D||this.#D.has(t.id)||this.#D.setValue(t.id,t)}#wt(){const t=document.getSelection();if(!t||t.isCollapsed)return void(this.#rt&&(this.#Y?.hide(),this.#rt=null,this.#_t({hasSelectedText:!1})));const{anchorNode:e}=t;if(e===this.#rt)return;const i=this.#vt(t).closest(".textLayer");if(i){if(this.#Y?.hide(),this.#rt=e,this.#_t({hasSelectedText:!0}),(this.#nt===d.HIGHLIGHT||this.#nt===d.NONE)&&(this.#nt===d.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0),this.#K=this.isShiftKeyDown,!this.isShiftKeyDown)){const t=this.#nt===d.HIGHLIGHT?this.#At(i):null;t?.toggleDrawing();const e=new AbortController,s=this.combinedSignal(e),n=i=>{"pointerup"===i.type&&0!==i.button||(e.abort(),t?.toggleDrawing(!0),"pointerup"===i.type&&this.#xt("main_toolbar"))};window.addEventListener("pointerup",n,{signal:s}),window.addEventListener("blur",n,{signal:s})}}else this.#rt&&(this.#Y?.hide(),this.#rt=null,this.#_t({hasSelectedText:!1}))}#xt(t=""){this.#nt===d.HIGHLIGHT?this.highlightSelection(t):this.#U&&this.#yt()}#mt(){document.addEventListener("selectionchange",this.#wt.bind(this),{signal:this._signal})}#Ct(){if(this.#q)return;this.#q=new AbortController;const t=this.combinedSignal(this.#q);window.addEventListener("focus",this.focus.bind(this),{signal:t}),window.addEventListener("blur",this.blur.bind(this),{signal:t})}#Et(){this.#q?.abort(),this.#q=null}blur(){if(this.isShiftKeyDown=!1,this.#K&&(this.#K=!1,this.#xt("main_toolbar")),!this.hasSelection)return;const{activeElement:t}=document;for(const e of this.#at)if(e.div.contains(t)){this.#et=[e,t],e._focusEventsAllowed=!1;break}}focus(){if(!this.#et)return;const[t,e]=this.#et;this.#et=null,e.addEventListener("focusin",(()=>{t._focusEventsAllowed=!0}),{once:!0,signal:this._signal}),e.focus()}#bt(){if(this.#tt)return;this.#tt=new AbortController;const t=this.combinedSignal(this.#tt);window.addEventListener("keydown",this.keydown.bind(this),{signal:t}),window.addEventListener("keyup",this.keyup.bind(this),{signal:t})}#St(){this.#tt?.abort(),this.#tt=null}#Tt(){if(this.#N)return;this.#N=new AbortController;const t=this.combinedSignal(this.#N);document.addEventListener("copy",this.copy.bind(this),{signal:t}),document.addEventListener("cut",this.cut.bind(this),{signal:t}),document.addEventListener("paste",this.paste.bind(this),{signal:t})}#Mt(){this.#N?.abort(),this.#N=null}#ft(){const t=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:t}),document.addEventListener("drop",this.drop.bind(this),{signal:t})}addEditListeners(){this.#bt(),this.#Tt()}removeEditListeners(){this.#St(),this.#Mt()}dragOver(t){for(const{type:e}of t.dataTransfer.items)for(const i of this.#H)if(i.isHandlingMimeForPasting(e))return t.dataTransfer.dropEffect="copy",void t.preventDefault()}drop(t){for(const e of t.dataTransfer.items)for(const i of this.#H)if(i.isHandlingMimeForPasting(e.type))return i.paste(e,this.currentLayer),void t.preventDefault()}copy(t){if(t.preventDefault(),this.#k?.commitOrRemove(),!this.hasSelection)return;const e=[];for(const t of this.#at){const i=t.serialize(!0);i&&e.push(i)}0!==e.length&&t.clipboardData.setData("application/pdfjs",JSON.stringify(e))}cut(t){this.copy(t),this.delete()}async paste(t){t.preventDefault();const{clipboardData:e}=t;for(const t of e.items)for(const e of this.#H)if(e.isHandlingMimeForPasting(t.type))return void e.paste(t,this.currentLayer);let i=e.getData("application/pdfjs");if(!i)return;try{i=JSON.parse(i)}catch(t){return void _(`paste: "${t.message}".`)}if(!Array.isArray(i))return;this.unselectAll();const s=this.currentLayer;try{const t=[];for(const e of i){const i=await s.deserialize(e);if(!i)return;t.push(i)}const e=()=>{for(const e of t)this.#kt(e);this.#It(t)},n=()=>{for(const e of t)e.remove()};this.addCommands({cmd:e,undo:n,mustExec:!0})}catch(t){_(`paste: "${t.message}".`)}}keydown(t){this.isShiftKeyDown||"Shift"!==t.key||(this.isShiftKeyDown=!0),this.#nt===d.NONE||this.isEditorHandlingKeyboard||Mt._keyboardManager.exec(this,t)}keyup(t){this.isShiftKeyDown&&"Shift"===t.key&&(this.isShiftKeyDown=!1,this.#K&&(this.#K=!1,this.#xt("main_toolbar")))}onEditingAction({name:t}){switch(t){case"undo":case"redo":case"delete":case"selectAll":this[t]();break;case"highlightSelection":this.highlightSelection("context_menu")}}#_t(t){Object.entries(t).some((([t,e])=>this.#ht[t]!==e))&&(this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(this.#ht,t)}),this.#nt===d.HIGHLIGHT&&!1===t.hasSelectedEditor&&this.#Pt([[c.HIGHLIGHT_FREE,!0]]))}#Pt(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})}setEditingState(t){t?(this.#Ct(),this.#Tt(),this.#_t({isEditing:this.#nt!==d.NONE,isEmpty:this.#Rt(),hasSomethingToUndo:this.#F.hasSomethingToUndo(),hasSomethingToRedo:this.#F.hasSomethingToRedo(),hasSelectedEditor:!1})):(this.#Et(),this.#Mt(),this.#_t({isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(t){if(!this.#H){this.#H=t;for(const t of this.#H)this.#Pt(t.defaultPropertiesToUpdate)}}getId(){return this.#Q.id}get currentLayer(){return this.#P.get(this.#O)}getLayer(t){return this.#P.get(t)}get currentPageIndex(){return this.#O}addLayer(t){this.#P.set(t.pageIndex,t),this.#J?t.enable():t.disable()}removeLayer(t){this.#P.delete(t.pageIndex)}async updateMode(t,e=null,i=!1){if(this.#nt!==t&&(!this.#gt||(await this.#gt.promise,this.#gt))){if(this.#gt=Promise.withResolvers(),this.#nt=t,t===d.NONE)return this.setEditingState(!1),this.#Dt(),void this.#gt.resolve();this.setEditingState(!0),await this.#Lt(),this.unselectAll();for(const e of this.#P.values())e.updateMode(t);if(!e)return i&&this.addNewEditorFromKeyboard(),void this.#gt.resolve();for(const t of this.#I.values())t.annotationElementId===e?(this.setSelected(t),t.enterInEditMode()):t.unselect();this.#gt.resolve()}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t!==this.#nt&&this._eventBus.dispatch("switchannotationeditormode",{source:this,mode:t})}updateParams(t,e){if(this.#H){switch(t){case c.CREATE:return void this.currentLayer.addNewEditor();case c.HIGHLIGHT_DEFAULT_COLOR:this.#it?.updateColor(e);break;case c.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}}),(this.#lt||=new Map).set(t,e),this.showAllEditors("highlight",e)}for(const i of this.#at)i.updateParams(t,e);for(const i of this.#H)i.updateDefaultParams(t,e)}}showAllEditors(t,e,i=!1){for(const i of this.#I.values())i.editorType===t&&i.show(e);(this.#lt?.get(c.HIGHLIGHT_SHOW_ALL)??!0)!==e&&this.#Pt([[c.HIGHLIGHT_SHOW_ALL,e]])}enableWaiting(t=!1){if(this.#Z!==t){this.#Z=t;for(const e of this.#P.values())t?e.disableClick():e.enableClick(),e.div.classList.toggle("waiting",t)}}async#Lt(){if(!this.#J){this.#J=!0;const t=[];for(const e of this.#P.values())t.push(e.enable());await Promise.all(t);for(const t of this.#I.values())t.enable()}}#Dt(){if(this.unselectAll(),this.#J){this.#J=!1;for(const t of this.#P.values())t.disable();for(const t of this.#I.values())t.disable()}}getEditors(t){const e=[];for(const i of this.#I.values())i.pageIndex===t&&e.push(i);return e}getEditor(t){return this.#I.get(t)}addEditor(t){this.#I.set(t.id,t)}removeEditor(t){t.div.contains(document.activeElement)&&(this.#V&&clearTimeout(this.#V),this.#V=setTimeout((()=>{this.focusMainContainer(),this.#V=null}),0)),this.#I.delete(t.id),this.unselect(t),t.annotationElementId&&this.#B.has(t.annotationElementId)||this.#D?.remove(t.id)}addDeletedAnnotationElement(t){this.#B.add(t.annotationElementId),this.addChangedExistingAnnotation(t),t.deleted=!0}isDeletedAnnotationElement(t){return this.#B.has(t)}removeDeletedAnnotationElement(t){this.#B.delete(t.annotationElementId),this.removeChangedExistingAnnotation(t),t.deleted=!1}#kt(t){const e=this.#P.get(t.pageIndex);e?e.addOrRebuild(t):(this.addEditor(t),this.addToAnnotationStorage(t))}setActiveEditor(t){this.#k!==t&&(this.#k=t,t&&this.#Pt(t.propertiesToUpdate))}get#Ft(){let t=null;for(t of this.#at);return t}updateUI(t){this.#Ft===t&&this.#Pt(t.propertiesToUpdate)}toggleSelected(t){if(this.#at.has(t))return this.#at.delete(t),t.unselect(),void this.#_t({hasSelectedEditor:this.hasSelection});this.#at.add(t),t.select(),this.#Pt(t.propertiesToUpdate),this.#_t({hasSelectedEditor:!0})}setSelected(t){for(const e of this.#at)e!==t&&e.unselect();this.#at.clear(),this.#at.add(t),t.select(),this.#Pt(t.propertiesToUpdate),this.#_t({hasSelectedEditor:!0})}isSelected(t){return this.#at.has(t)}get firstSelectedEditor(){return this.#at.values().next().value}unselect(t){t.unselect(),this.#at.delete(t),this.#_t({hasSelectedEditor:this.hasSelection})}get hasSelection(){return 0!==this.#at.size}get isEnterHandled(){return 1===this.#at.size&&this.firstSelectedEditor.isEnterHandled}undo(){this.#F.undo(),this.#_t({hasSomethingToUndo:this.#F.hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:this.#Rt()})}redo(){this.#F.redo(),this.#_t({hasSomethingToUndo:!0,hasSomethingToRedo:this.#F.hasSomethingToRedo(),isEmpty:this.#Rt()})}addCommands(t){this.#F.add(t),this.#_t({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#Rt()})}#Rt(){if(0===this.#I.size)return!0;if(1===this.#I.size)for(const t of this.#I.values())return t.isEmpty();return!1}delete(){if(this.commitOrRemove(),!this.hasSelection)return;const t=[...this.#at];this.addCommands({cmd:()=>{for(const e of t)e.remove()},undo:()=>{for(const e of t)this.#kt(e)},mustExec:!0})}commitOrRemove(){this.#k?.commitOrRemove()}hasSomethingToControl(){return this.#k||this.hasSelection}#It(t){for(const t of this.#at)t.unselect();this.#at.clear();for(const e of t)e.isEmpty()||(this.#at.add(e),e.select());this.#_t({hasSelectedEditor:this.hasSelection})}selectAll(){for(const t of this.#at)t.commit();this.#It(this.#I.values())}unselectAll(){if((!this.#k||(this.#k.commitOrRemove(),this.#nt===d.NONE))&&this.hasSelection){for(const t of this.#at)t.unselect();this.#at.clear(),this.#_t({hasSelectedEditor:!1})}}translateSelectedEditors(t,e,i=!1){if(i||this.commitOrRemove(),!this.hasSelection)return;this.#dt[0]+=t,this.#dt[1]+=e;const[s,n]=this.#dt,a=[...this.#at];this.#ct&&clearTimeout(this.#ct),this.#ct=setTimeout((()=>{this.#ct=null,this.#dt[0]=this.#dt[1]=0,this.addCommands({cmd:()=>{for(const t of a)this.#I.has(t.id)&&t.translateInPage(s,n)},undo:()=>{for(const t of a)this.#I.has(t.id)&&t.translateInPage(-s,-n)},mustExec:!1})}),1e3);for(const i of a)i.translateInPage(t,e)}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0),this.#z=new Map;for(const t of this.#at)this.#z.set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!this.#z)return!1;this.disableUserSelect(!1);const t=this.#z;this.#z=null;let e=!1;for(const[{x:i,y:s,pageIndex:n},a]of t)a.newX=i,a.newY=s,a.newPageIndex=n,e||=i!==a.savedX||s!==a.savedY||n!==a.savedPageIndex;if(!e)return!1;const i=(t,e,i,s)=>{if(this.#I.has(t.id)){const n=this.#P.get(s);n?t._setParentAndPosition(n,e,i):(t.pageIndex=s,t.x=e,t.y=i)}};return this.addCommands({cmd:()=>{for(const[e,{newX:s,newY:n,newPageIndex:a}]of t)i(e,s,n,a)},undo:()=>{for(const[e,{savedX:s,savedY:n,savedPageIndex:a}]of t)i(e,s,n,a)},mustExec:!0}),!0}dragSelectedEditors(t,e){if(this.#z)for(const i of this.#z.keys())i.drag(t,e)}rebuild(t){if(null===t.parent){const e=this.getLayer(t.pageIndex);e?(e.changeParent(t),e.addOrRebuild(t)):(this.addEditor(t),this.addToAnnotationStorage(t),t.rebuild())}else t.parent.addOrRebuild(t)}get isEditorHandlingKeyboard(){return this.getActive()?.shouldGetKeyboardEvents()||1===this.#at.size&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(t){return this.#k===t}getActive(){return this.#k}getMode(){return this.#nt}get imageManager(){return S(this,"imageManager",new Ct)}getSelectionBoxes(t){if(!t)return null;const e=document.getSelection();for(let i=0,s=e.rangeCount;i({x:(e-s)/a,y:1-(t+r-i)/n,width:o/a,height:r/n});break;case"180":r=(t,e,r,o)=>({x:1-(t+r-i)/n,y:1-(e+o-s)/a,width:r/n,height:o/a});break;case"270":r=(t,e,r,o)=>({x:1-(e+o-s)/a,y:(t-i)/n,width:o/a,height:r/n});break;default:r=(t,e,r,o)=>({x:(t-i)/n,y:(e-s)/a,width:r/n,height:o/a})}const o=[];for(let t=0,i=e.rangeCount;tt.stopPropagation()),{signal:i});const s=t=>{t.preventDefault(),this.#a._uiManager.editAltText(this.#a),this.#Wt&&this.#a._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:this.#Vt}})};return t.addEventListener("click",s,{capture:!0,signal:i}),t.addEventListener("keydown",(e=>{e.target===t&&"Enter"===e.key&&(this.#Ht=!0,s(e))}),{signal:i}),await this.#qt(),t}get#Vt(){return(this.#o?"added":null===this.#o&&this.guessedText&&"review")||"missing"}finish(){this.#Ot&&(this.#Ot.focus({focusVisible:this.#Ht}),this.#Ht=!1)}isEmpty(){return this.#Wt?null===this.#o:!this.#o&&!this.#Nt}hasData(){return this.#Wt?null!==this.#o||!!this.#Ut:this.isEmpty()}get guessedText(){return this.#Ut}async setGuessedText(t){null===this.#o&&(this.#Ut=t,this.#$t=await kt._l10nPromise.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer")({generatedAltText:t}),this.#qt())}toggleAltTextBadge(t=!1){if(!this.#Wt||this.#o)return this.#jt?.remove(),void(this.#jt=null);if(!this.#jt){const t=this.#jt=document.createElement("div");t.className="noAltTextBadge",this.#a.div.append(t)}this.#jt.classList.toggle("hidden",!t)}serialize(t){let e=this.#o;return t||this.#Ut!==e||(e=this.#$t),{altText:e,decorative:this.#Nt,guessedText:this.#Ut,textWithDisclaimer:this.#$t}}get data(){return{altText:this.#o,decorative:this.#Nt}}set data({altText:t,decorative:e,guessedText:i,textWithDisclaimer:s,cancel:n=!1}){i&&(this.#Ut=i,this.#$t=s),this.#o===t&&this.#Nt===e||(n||(this.#o=t,this.#Nt=e),this.#qt())}toggle(t=!1){this.#Ot&&(!t&&this.#zt&&(clearTimeout(this.#zt),this.#zt=null),this.#Ot.disabled=!t)}shown(){this.#a._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:this.#Vt}})}destroy(){this.#Ot?.remove(),this.#Ot=null,this.#Bt=null,this.#jt?.remove(),this.#jt=null}async#qt(){const t=this.#Ot;if(!t)return;if(this.#Wt){if(t.classList.toggle("done",!!this.#o),kt._l10nPromise.get(kt.#Gt[this.#Vt]).then((e=>{t.setAttribute("aria-label",e);for(const i of t.childNodes)if(i.nodeType===Node.TEXT_NODE){i.textContent=e;break}})),!this.#o)return void this.#Bt?.remove()}else{if(!this.#o&&!this.#Nt)return t.classList.remove("done"),void this.#Bt?.remove();t.classList.add("done"),kt._l10nPromise.get("pdfjs-editor-alt-text-edit-button-label").then((e=>{t.setAttribute("aria-label",e)}))}let e=this.#Bt;if(!e){this.#Bt=e=document.createElement("span"),e.className="tooltip",e.setAttribute("role","tooltip"),e.id=`alt-text-tooltip-${this.#a.id}`;const i=100,s=this.#a._uiManager._signal;s.addEventListener("abort",(()=>{clearTimeout(this.#zt),this.#zt=null}),{once:!0}),t.addEventListener("mouseenter",(()=>{this.#zt=setTimeout((()=>{this.#zt=null,this.#Bt.classList.add("show"),this.#a._reportTelemetry({action:"alt_text_tooltip"})}),i)}),{signal:s}),t.addEventListener("mouseleave",(()=>{this.#zt&&(clearTimeout(this.#zt),this.#zt=null),this.#Bt?.classList.remove("show")}),{signal:s})}e.innerText=this.#Nt?await kt._l10nPromise.get("pdfjs-editor-alt-text-decorative-tooltip"):this.#o,e.parentNode||t.append(e);const i=this.#a.getImageForAltText();i?.setAttribute("aria-describedby",e.id)}}class It{#Xt=null;#Kt=null;#o=null;#Yt=!1;#Qt=!1;#Jt=null;#Zt=null;#te=null;#ee="";#ie=!1;#se=null;#ne=!1;#ae=!1;#re=!1;#oe=null;#le=0;#he=0;#de=null;_editToolbar=null;_initialOptions=Object.create(null);_initialData=null;_isVisible=!0;_uiManager=null;_focusEventsAllowed=!0;static _l10nPromise=null;static _l10nResizer=null;#ce=!1;#ue=It._zIndex++;static _borderLineWidth=-1;static _colorManager=new Tt;static _zIndex=1;static _telemetryTimeout=1e3;static get _resizerKeyboardManager(){const t=It.prototype._resizeWithKeyboard,e=Mt.TRANSLATE_SMALL,i=Mt.TRANSLATE_BIG;return S(this,"_resizerKeyboardManager",new St([[["ArrowLeft","mac+ArrowLeft"],t,{args:[-e,0]}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t,{args:[-i,0]}],[["ArrowRight","mac+ArrowRight"],t,{args:[e,0]}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t,{args:[i,0]}],[["ArrowUp","mac+ArrowUp"],t,{args:[0,-e]}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t,{args:[0,-i]}],[["ArrowDown","mac+ArrowDown"],t,{args:[0,e]}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t,{args:[0,i]}],[["Escape","mac+Escape"],It.prototype._stopResizingWithKeyboard]]))}constructor(t){this.parent=t.parent,this.id=t.id,this.width=this.height=null,this.pageIndex=t.parent.pageIndex,this.name=t.name,this.div=null,this._uiManager=t.uiManager,this.annotationElementId=null,this._willKeepAspectRatio=!1,this._initialOptions.isCentered=t.isCentered,this._structTreeParentId=null;const{rotation:e,rawDims:{pageWidth:i,pageHeight:s,pageX:n,pageY:a}}=this.parent.viewport;this.rotation=e,this.pageRotation=(360+e-this._uiManager.viewParameters.rotation)%360,this.pageDimensions=[i,s],this.pageTranslation=[n,a];const[r,o]=this.parentDimensions;this.x=t.x/r,this.y=t.y/o,this.isAttachedToDOM=!1,this.deleted=!1}get editorType(){return Object.getPrototypeOf(this).constructor._type}static get _defaultLineColor(){return S(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){const e=new Pt({id:t.parent.getNextId(),parent:t.parent,uiManager:t._uiManager});e.annotationElementId=t.annotationElementId,e.deleted=!0,e._uiManager.addToAnnotationStorage(e)}static initialize(t,e,i){if(It._l10nResizer||=Object.freeze({topLeft:"pdfjs-editor-resizer-top-left",topMiddle:"pdfjs-editor-resizer-top-middle",topRight:"pdfjs-editor-resizer-top-right",middleRight:"pdfjs-editor-resizer-middle-right",bottomRight:"pdfjs-editor-resizer-bottom-right",bottomMiddle:"pdfjs-editor-resizer-bottom-middle",bottomLeft:"pdfjs-editor-resizer-bottom-left",middleLeft:"pdfjs-editor-resizer-middle-left"}),It._l10nPromise||=new Map([...["pdfjs-editor-alt-text-button-label","pdfjs-editor-alt-text-edit-button-label","pdfjs-editor-alt-text-decorative-tooltip","pdfjs-editor-new-alt-text-added-button-label","pdfjs-editor-new-alt-text-missing-button-label","pdfjs-editor-new-alt-text-to-review-button-label"].map((e=>[e,t.get(e)])),...["pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer"].map((e=>[e,t.get.bind(t,e)]))]),i?.strings)for(const e of i.strings)It._l10nPromise.set(e,t.get(e));if(-1!==It._borderLineWidth)return;const s=getComputedStyle(document.documentElement);It._borderLineWidth=parseFloat(s.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,e){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return!1}static paste(t,e){x("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return this.#ce}set _isDraggable(t){this.#ce=t,this.div?.classList.toggle("draggable",t)}get isEnterHandled(){return!0}center(){const[t,e]=this.pageDimensions;switch(this.parentRotation){case 90:this.x-=this.height*e/(2*t),this.y+=this.width*t/(2*e);break;case 180:this.x+=this.width/2,this.y+=this.height/2;break;case 270:this.x+=this.height*e/(2*t),this.y-=this.width*t/(2*e);break;default:this.x-=this.width/2,this.y-=this.height/2}this.fixAndSetPosition()}addCommands(t){this._uiManager.addCommands(t)}get currentLayer(){return this._uiManager.currentLayer}setInBackground(){this.div.style.zIndex=0}setInForeground(){this.div.style.zIndex=this.#ue}setParent(t){null!==t?(this.pageIndex=t.pageIndex,this.pageDimensions=t.pageDimensions):this.#pe(),this.parent=t}focusin(t){this._focusEventsAllowed&&(this.#ie?this.#ie=!1:this.parent.setSelected(this))}focusout(t){if(!this._focusEventsAllowed)return;if(!this.isAttachedToDOM)return;const e=t.relatedTarget;e?.closest(`#${this.id}`)||(t.preventDefault(),this.parent?.isMultipleSelection||this.commitOrRemove())}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.addToAnnotationStorage()}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(t,e,i,s){const[n,a]=this.parentDimensions;[i,s]=this.screenToPageTranslation(i,s),this.x=(t+i)/n,this.y=(e+s)/a,this.fixAndSetPosition()}#ge([t,e],i,s){[i,s]=this.screenToPageTranslation(i,s),this.x+=i/t,this.y+=s/e,this.fixAndSetPosition()}translate(t,e){this.#ge(this.parentDimensions,t,e)}translateInPage(t,e){this.#se||=[this.x,this.y],this.#ge(this.pageDimensions,t,e),this.div.scrollIntoView({block:"nearest"})}drag(t,e){this.#se||=[this.x,this.y];const[i,s]=this.parentDimensions;if(this.x+=t/i,this.y+=e/s,this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){const{x:t,y:e}=this.div.getBoundingClientRect();this.parent.findNewParent(this,t,e)&&(this.x-=Math.floor(this.x),this.y-=Math.floor(this.y))}let{x:n,y:a}=this;const[r,o]=this.getBaseTranslation();n+=r,a+=o,this.div.style.left=`${(100*n).toFixed(2)}%`,this.div.style.top=`${(100*a).toFixed(2)}%`,this.div.scrollIntoView({block:"nearest"})}get _hasBeenMoved(){return!!this.#se&&(this.#se[0]!==this.x||this.#se[1]!==this.y)}getBaseTranslation(){const[t,e]=this.parentDimensions,{_borderLineWidth:i}=It,s=i/t,n=i/e;switch(this.rotation){case 90:return[-s,n];case 180:return[s,n];case 270:return[s,-n];default:return[-s,-n]}}get _mustFixPosition(){return!0}fixAndSetPosition(t=this.rotation){const[e,i]=this.pageDimensions;let{x:s,y:n,width:a,height:r}=this;if(a*=e,r*=i,s*=e,n*=i,this._mustFixPosition)switch(t){case 0:s=Math.max(0,Math.min(e-a,s)),n=Math.max(0,Math.min(i-r,n));break;case 90:s=Math.max(0,Math.min(e-r,s)),n=Math.min(i,Math.max(a,n));break;case 180:s=Math.min(e,Math.max(a,s)),n=Math.min(i,Math.max(r,n));break;case 270:s=Math.min(e,Math.max(r,s)),n=Math.max(0,Math.min(i-a,n))}this.x=s/=e,this.y=n/=i;const[o,l]=this.getBaseTranslation();s+=o,n+=l;const{style:h}=this.div;h.left=`${(100*s).toFixed(2)}%`,h.top=`${(100*n).toFixed(2)}%`,this.moveInDOM()}static#me(t,e,i){switch(i){case 90:return[e,-t];case 180:return[-t,-e];case 270:return[-e,t];default:return[t,e]}}screenToPageTranslation(t,e){return It.#me(t,e,this.parentRotation)}pageTranslationToScreen(t,e){return It.#me(t,e,360-this.parentRotation)}#fe(t){switch(t){case 90:{const[t,e]=this.pageDimensions;return[0,-t/e,e/t,0]}case 180:return[-1,0,0,-1];case 270:{const[t,e]=this.pageDimensions;return[0,t/e,-e/t,0]}default:return[1,0,0,1]}}get parentScale(){return this._uiManager.viewParameters.realScale}get parentRotation(){return(this._uiManager.viewParameters.rotation+this.pageRotation)%360}get parentDimensions(){const{parentScale:t,pageDimensions:[e,i]}=this;return[e*t,i*t]}setDims(t,e){const[i,s]=this.parentDimensions;this.div.style.width=`${(100*t/i).toFixed(2)}%`,this.#Qt||(this.div.style.height=`${(100*e/s).toFixed(2)}%`)}fixDims(){const{style:t}=this.div,{height:e,width:i}=t,s=i.endsWith("%"),n=!this.#Qt&&e.endsWith("%");if(s&&n)return;const[a,r]=this.parentDimensions;s||(t.width=`${(100*parseFloat(i)/a).toFixed(2)}%`),this.#Qt||n||(t.height=`${(100*parseFloat(e)/r).toFixed(2)}%`)}getInitialTranslation(){return[0,0]}#be(){if(this.#Jt)return;this.#Jt=document.createElement("div"),this.#Jt.classList.add("resizers");const t=this._willKeepAspectRatio?["topLeft","topRight","bottomRight","bottomLeft"]:["topLeft","topMiddle","topRight","middleRight","bottomRight","bottomMiddle","bottomLeft","middleLeft"],e=this._uiManager._signal;for(const i of t){const t=document.createElement("div");this.#Jt.append(t),t.classList.add("resizer",i),t.setAttribute("data-resizer-name",i),t.addEventListener("pointerdown",this.#ve.bind(this,i),{signal:e}),t.addEventListener("contextmenu",dt,{signal:e}),t.tabIndex=-1}this.div.prepend(this.#Jt)}#ve(t,e){e.preventDefault();const{isMac:i}=B.platform;if(0!==e.button||e.ctrlKey&&i)return;this.#o?.toggle(!1);const s=this._isDraggable;this._isDraggable=!1;const n=new AbortController,a=this._uiManager.combinedSignal(n);this.parent.togglePointerEvents(!1),window.addEventListener("pointermove",this.#Ae.bind(this,t),{passive:!0,capture:!0,signal:a}),window.addEventListener("contextmenu",dt,{signal:a});const r=this.x,o=this.y,l=this.width,h=this.height,d=this.parent.div.style.cursor,c=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(e.target).cursor;const u=()=>{n.abort(),this.parent.togglePointerEvents(!0),this.#o?.toggle(!0),this._isDraggable=s,this.parent.div.style.cursor=d,this.div.style.cursor=c,this.#ye(r,o,l,h)};window.addEventListener("pointerup",u,{signal:a}),window.addEventListener("blur",u,{signal:a})}#ye(t,e,i,s){const n=this.x,a=this.y,r=this.width,o=this.height;n===t&&a===e&&r===i&&o===s||this.addCommands({cmd:()=>{this.width=r,this.height=o,this.x=n,this.y=a;const[t,e]=this.parentDimensions;this.setDims(t*r,e*o),this.fixAndSetPosition()},undo:()=>{this.width=i,this.height=s,this.x=t,this.y=e;const[n,a]=this.parentDimensions;this.setDims(n*i,a*s),this.fixAndSetPosition()},mustExec:!0})}#Ae(t,e){const[i,s]=this.parentDimensions,n=this.x,a=this.y,r=this.width,o=this.height,l=It.MIN_SIZE/i,h=It.MIN_SIZE/s,d=t=>Math.round(1e4*t)/1e4,c=this.#fe(this.rotation),u=(t,e)=>[c[0]*t+c[2]*e,c[1]*t+c[3]*e],p=this.#fe(360-this.rotation);let g,m,f=!1,b=!1;switch(t){case"topLeft":f=!0,g=(t,e)=>[0,0],m=(t,e)=>[t,e];break;case"topMiddle":g=(t,e)=>[t/2,0],m=(t,e)=>[t/2,e];break;case"topRight":f=!0,g=(t,e)=>[t,0],m=(t,e)=>[0,e];break;case"middleRight":b=!0,g=(t,e)=>[t,e/2],m=(t,e)=>[0,e/2];break;case"bottomRight":f=!0,g=(t,e)=>[t,e],m=(t,e)=>[0,0];break;case"bottomMiddle":g=(t,e)=>[t/2,e],m=(t,e)=>[t/2,0];break;case"bottomLeft":f=!0,g=(t,e)=>[0,e],m=(t,e)=>[t,0];break;case"middleLeft":b=!0,g=(t,e)=>[0,e/2],m=(t,e)=>[t,e/2]}const v=g(r,o),A=m(r,o);let y=u(...A);const w=d(n+y[0]),_=d(a+y[1]);let x=1,C=1,[E,S]=this.screenToPageTranslation(e.movementX,e.movementY);var T,M;if([E,S]=(T=E/i,M=S/s,[p[0]*T+p[2]*M,p[1]*T+p[3]*M]),f){const t=Math.hypot(r,o);x=C=Math.max(Math.min(Math.hypot(A[0]-v[0]-E,A[1]-v[1]-S)/t,1/r,1/o),l/r,h/o)}else b?x=Math.max(l,Math.min(1,Math.abs(A[0]-v[0]-E)))/r:C=Math.max(h,Math.min(1,Math.abs(A[1]-v[1]-S)))/o;const k=d(r*x),I=d(o*C);y=u(...m(k,I));const P=w-y[0],R=_-y[1];this.width=k,this.height=I,this.x=P,this.y=R,this.setDims(i*k,s*I),this.fixAndSetPosition()}altTextFinish(){this.#o?.finish()}async addEditToolbar(){return this._editToolbar||this.#ae||(this._editToolbar=new yt(this),this.div.append(this._editToolbar.render()),this.#o&&await this._editToolbar.addAltText(this.#o)),this._editToolbar}removeEditToolbar(){this._editToolbar&&(this._editToolbar.remove(),this._editToolbar=null,this.#o?.destroy())}addContainer(t){const e=this._editToolbar?.div;e?e.before(t):this.div.append(t)}getClientDimensions(){return this.div.getBoundingClientRect()}async addAltTextButton(){this.#o||(kt.initialize(It._l10nPromise),this.#o=new kt(this),this.#Xt&&(this.#o.data=this.#Xt,this.#Xt=null),await this.addEditToolbar())}get altTextData(){return this.#o?.data}set altTextData(t){this.#o&&(this.#o.data=t)}get guessedAltText(){return this.#o?.guessedText}async setGuessedAltText(t){await(this.#o?.setGuessedText(t))}serializeAltText(t){return this.#o?.serialize(t)}hasAltText(){return!!this.#o&&!this.#o.isEmpty()}hasAltTextData(){return this.#o?.hasData()??!1}render(){this.div=document.createElement("div"),this.div.setAttribute("data-editor-rotation",(360-this.rotation)%360),this.div.className=this.name,this.div.setAttribute("id",this.id),this.div.tabIndex=this.#Yt?-1:0,this._isVisible||this.div.classList.add("hidden"),this.setInForeground(),this.#we();const[t,e]=this.parentDimensions;this.parentRotation%180!=0&&(this.div.style.maxWidth=`${(100*e/t).toFixed(2)}%`,this.div.style.maxHeight=`${(100*t/e).toFixed(2)}%`);const[i,s]=this.getInitialTranslation();return this.translate(i,s),_t(this,this.div,["pointerdown"]),this.div}pointerdown(t){const{isMac:e}=B.platform;0!==t.button||t.ctrlKey&&e?t.preventDefault():(this.#ie=!0,this._isDraggable?this.#_e(t):this.#xe(t))}#xe(t){const{isMac:e}=B.platform;t.ctrlKey&&!e||t.shiftKey||t.metaKey&&e?this.parent.toggleSelected(this):this.parent.setSelected(this)}#_e(t){const e=this._uiManager.isSelected(this);this._uiManager.setUpDragSession();const i=new AbortController,s=this._uiManager.combinedSignal(i);if(e){this.div.classList.add("moving"),this.#le=t.clientX,this.#he=t.clientY;const e=t=>{const{clientX:e,clientY:i}=t,[s,n]=this.screenToPageTranslation(e-this.#le,i-this.#he);this.#le=e,this.#he=i,this._uiManager.dragSelectedEditors(s,n)};window.addEventListener("pointermove",e,{passive:!0,capture:!0,signal:s})}const n=()=>{i.abort(),e&&this.div.classList.remove("moving"),this.#ie=!1,this._uiManager.endDragSession()||this.#xe(t)};window.addEventListener("pointerup",n,{signal:s}),window.addEventListener("blur",n,{signal:s})}moveInDOM(){this.#oe&&clearTimeout(this.#oe),this.#oe=setTimeout((()=>{this.#oe=null,this.parent?.moveEditorInDOM(this)}),0)}_setParentAndPosition(t,e,i){t.changeParent(this),this.x=e,this.y=i,this.fixAndSetPosition()}getRect(t,e,i=this.rotation){const s=this.parentScale,[n,a]=this.pageDimensions,[r,o]=this.pageTranslation,l=t/s,h=e/s,d=this.x*n,c=this.y*a,u=this.width*n,p=this.height*a;switch(i){case 0:return[d+l+r,a-c-h-p+o,d+l+u+r,a-c-h+o];case 90:return[d+h+r,a-c+l+o,d+h+p+r,a-c+l+u+o];case 180:return[d-l-u+r,a-c+h+o,d-l+r,a-c+h+p+o];case 270:return[d-h-p+r,a-c-l-u+o,d-h+r,a-c-l+o];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(t,e){const[i,s,n,a]=t,r=n-i,o=a-s;switch(this.rotation){case 0:return[i,e-a,r,o];case 90:return[i,e-s,o,r];case 180:return[n,e-s,r,o];case 270:return[n,e-a,o,r];default:throw new Error("Invalid rotation")}}onceAdded(){}isEmpty(){return!1}enableEditMode(){this.#ae=!0}disableEditMode(){this.#ae=!1}isInEditMode(){return this.#ae}shouldGetKeyboardEvents(){return this.#re}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}#we(){if(this.#te||!this.div)return;this.#te=new AbortController;const t=this._uiManager.combinedSignal(this.#te);this.div.addEventListener("focusin",this.focusin.bind(this),{signal:t}),this.div.addEventListener("focusout",this.focusout.bind(this),{signal:t})}rebuild(){this.#we()}rotate(t){}serializeDeleted(){return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex,popupRef:this._initialData?.popupRef||""}}serialize(t=!1,e=null){x("An editor must be serializable")}static async deserialize(t,e,i){const s=new this.prototype.constructor({parent:e,id:e.getNextId(),uiManager:i});s.rotation=t.rotation,s.#Xt=t.accessibilityData;const[n,a]=s.pageDimensions,[r,o,l,h]=s.getRectInCurrentCoords(t.rect,a);return s.x=r/n,s.y=o/a,s.width=l/n,s.height=h/a,s}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||null!==this.serialize())}remove(){if(this.#te?.abort(),this.#te=null,this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),this.#oe&&(clearTimeout(this.#oe),this.#oe=null),this.#pe(),this.removeEditToolbar(),this.#de){for(const t of this.#de.values())clearTimeout(t);this.#de=null}this.parent=null}get isResizable(){return!1}makeResizable(){this.isResizable&&(this.#be(),this.#Jt.classList.remove("hidden"),_t(this,this.div,["keydown"]))}get toolbarPosition(){return null}keydown(t){if(!this.isResizable||t.target!==this.div||"Enter"!==t.key)return;this._uiManager.setSelected(this),this.#Zt={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const e=this.#Jt.children;if(!this.#Kt){this.#Kt=Array.from(e);const t=this.#Ce.bind(this),i=this.#Ee.bind(this),s=this._uiManager._signal;for(const e of this.#Kt){const n=e.getAttribute("data-resizer-name");e.setAttribute("role","spinbutton"),e.addEventListener("keydown",t,{signal:s}),e.addEventListener("blur",i,{signal:s}),e.addEventListener("focus",this.#Se.bind(this,n),{signal:s}),e.setAttribute("data-l10n-id",It._l10nResizer[n])}}const i=this.#Kt[0];let s=0;for(const t of e){if(t===i)break;s++}const n=(360-this.rotation+this.parentRotation)%360/90*(this.#Kt.length/4);if(n!==s){if(ns)for(let t=0;t{this.div?.classList.contains("selectedEditor")&&this._editToolbar?.show()}))}unselect(){this.#Jt?.classList.add("hidden"),this.div?.classList.remove("selectedEditor"),this.div?.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0}),this._editToolbar?.hide(),this.#o?.toggleAltTextBadge(!0)}updateParams(t,e){}disableEditing(){}enableEditing(){}enterInEditMode(){}getImageForAltText(){return null}get contentDiv(){return this.div}get isEditing(){return this.#ne}set isEditing(t){this.#ne=t,this.parent&&(t?(this.parent.setSelected(this),this.parent.setActiveEditor(this)):this.parent.setActiveEditor(null))}setAspectRatio(t,e){this.#Qt=!0;const i=t/e,{style:s}=this.div;s.aspectRatio=i,s.height="auto"}static get MIN_SIZE(){return 16}static canCreateNewEmptyEditor(){return!0}get telemetryInitialData(){return{action:"added"}}get telemetryFinalData(){return null}_reportTelemetry(t,e=!1){if(e){this.#de||=new Map;const{action:e}=t;let i=this.#de.get(e);return i&&clearTimeout(i),i=setTimeout((()=>{this._reportTelemetry(t),this.#de.delete(e),0===this.#de.size&&(this.#de=null)}),It._telemetryTimeout),void this.#de.set(e,i)}t.type||=this.editorType,this._uiManager._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:t}})}show(t=this._isVisible){this.div.classList.toggle("hidden",!t),this._isVisible=t}enable(){this.div&&(this.div.tabIndex=0),this.#Yt=!1}disable(){this.div&&(this.div.tabIndex=-1),this.#Yt=!0}renderAnnotationElement(t){let e=t.container.querySelector(".annotationContent");if(e){if("CANVAS"===e.nodeName){const t=e;e=document.createElement("div"),e.classList.add("annotationContent",this.editorType),t.before(e)}}else e=document.createElement("div"),e.classList.add("annotationContent",this.editorType),t.container.prepend(e);return e}resetAnnotationElement(t){const{firstChild:e}=t.container;"DIV"===e?.nodeName&&e.classList.contains("annotationContent")&&e.remove()}}class Pt extends It{constructor(t){super(t),this.annotationElementId=t.annotationElementId,this.deleted=!0}serialize(){return this.serializeDeleted()}}const Rt=3285377520,Dt=4294901760,Lt=65535;class Ft{constructor(t){this.h1=t?4294967295&t:Rt,this.h2=t?4294967295&t:Rt}update(t){let e,i;if("string"==typeof t){e=new Uint8Array(2*t.length),i=0;for(let s=0,n=t.length;s>>8,e[i++]=255&n)}}else{if(!ArrayBuffer.isView(t))throw new Error("Invalid data format, must be a string or TypedArray.");e=t.slice(),i=e.byteLength}const s=i>>2,n=i-4*s,a=new Uint32Array(e.buffer,0,s);let r=0,o=0,l=this.h1,h=this.h2;const d=3432918353,c=461845907,u=11601,p=13715;for(let t=0;t>>17,r=r*c&Dt|r*p&Lt,l^=r,l=l<<13|l>>>19,l=5*l+3864292196):(o=a[t],o=o*d&Dt|o*u&Lt,o=o<<15|o>>>17,o=o*c&Dt|o*p&Lt,h^=o,h=h<<13|h>>>19,h=5*h+3864292196);switch(r=0,n){case 3:r^=e[4*s+2]<<16;case 2:r^=e[4*s+1]<<8;case 1:r^=e[4*s],r=r*d&Dt|r*u&Lt,r=r<<15|r>>>17,r=r*c&Dt|r*p&Lt,1&s?l^=r:h^=r}this.h1=l,this.h2=h}hexdigest(){let t=this.h1,e=this.h2;return t^=e>>>1,t=3981806797*t&Dt|36045*t&Lt,e=4283543511*e&Dt|(2950163797*(e<<16|t>>>16)&Dt)>>>16,t^=e>>>1,t=444984403*t&Dt|60499*t&Lt,e=3301882366*e&Dt|(3120437893*(e<<16|t>>>16)&Dt)>>>16,t^=e>>>1,(t>>>0).toString(16).padStart(8,"0")+(e>>>0).toString(16).padStart(8,"0")}}const Nt=Object.freeze({map:null,hash:"",transfer:void 0});class Ot{#Me=!1;#ke=null;#Ie=new Map;constructor(){this.onSetModified=null,this.onResetModified=null,this.onAnnotationEditor=null}getValue(t,e){const i=this.#Ie.get(t);return void 0===i?e:Object.assign(e,i)}getRawValue(t){return this.#Ie.get(t)}remove(t){if(this.#Ie.delete(t),0===this.#Ie.size&&this.resetModified(),"function"==typeof this.onAnnotationEditor){for(const t of this.#Ie.values())if(t instanceof It)return;this.onAnnotationEditor(null)}}setValue(t,e){const i=this.#Ie.get(t);let s=!1;if(void 0!==i)for(const[t,n]of Object.entries(e))i[t]!==n&&(s=!0,i[t]=n);else s=!0,this.#Ie.set(t,e);s&&this.#Pe(),e instanceof It&&"function"==typeof this.onAnnotationEditor&&this.onAnnotationEditor(e.constructor._type)}has(t){return this.#Ie.has(t)}getAll(){return this.#Ie.size>0?O(this.#Ie):null}setAll(t){for(const[e,i]of Object.entries(t))this.setValue(e,i)}get size(){return this.#Ie.size}#Pe(){this.#Me||(this.#Me=!0,"function"==typeof this.onSetModified&&this.onSetModified())}resetModified(){this.#Me&&(this.#Me=!1,"function"==typeof this.onResetModified&&this.onResetModified())}get print(){return new Bt(this)}get serializable(){if(0===this.#Ie.size)return Nt;const t=new Map,e=new Ft,i=[],s=Object.create(null);let n=!1;for(const[i,a]of this.#Ie){const r=a instanceof It?a.serialize(!1,s):a;r&&(t.set(i,r),e.update(`${i}:${JSON.stringify(r)}`),n||=!!r.bitmap)}if(n)for(const e of t.values())e.bitmap&&i.push(e.bitmap);return t.size>0?{map:t,hash:e.hexdigest(),transfer:i}:Nt}get editorStats(){let t=null;const e=new Map;for(const i of this.#Ie.values()){if(!(i instanceof It))continue;const s=i.telemetryFinalData;if(!s)continue;const{type:n}=s;e.has(n)||e.set(n,Object.getPrototypeOf(i).constructor),t||=Object.create(null);const a=t[n]||=new Map;for(const[t,e]of Object.entries(s)){if("type"===t)continue;let i=a.get(t);i||(i=new Map,a.set(t,i));const s=i.get(e)??0;i.set(e,s+1)}}for(const[i,s]of e)t[i]=s.computeTelemetryFinalData(t[i]);return t}resetModifiedIds(){this.#ke=null}get modifiedIds(){if(this.#ke)return this.#ke;const t=[];for(const e of this.#Ie.values())e instanceof It&&e.annotationElementId&&e.serialize()&&t.push(e.annotationElementId);return this.#ke={ids:new Set(t),hash:t.join(",")}}}class Bt extends Ot{#Re;constructor(t){super();const{map:e,hash:i,transfer:s}=t.serializable,n=structuredClone(e,s?{transfer:s}:null);this.#Re={map:n,hash:i,transfer:s}}get print(){x("Should not call PrintAnnotationStorage.print")}get serializable(){return this.#Re}get modifiedIds(){return S(this,"modifiedIds",{ids:new Set,hash:""})}}class zt{#De=new Set;constructor({ownerDocument:t=globalThis.document,styleElement:e=null}){this._document=t,this.nativeFontFaces=new Set,this.styleElement=null,this.loadingRequests=[],this.loadTestFontId=0}addNativeFontFace(t){this.nativeFontFaces.add(t),this._document.fonts.add(t)}removeNativeFontFace(t){this.nativeFontFaces.delete(t),this._document.fonts.delete(t)}insertRule(t){this.styleElement||(this.styleElement=this._document.createElement("style"),this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement));const e=this.styleElement.sheet;e.insertRule(t,e.cssRules.length)}clear(){for(const t of this.nativeFontFaces)this._document.fonts.delete(t);this.nativeFontFaces.clear(),this.#De.clear(),this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}async loadSystemFont({systemFontInfo:t,_inspectFont:e}){if(t&&!this.#De.has(t.loadedName))if(C(!this.disableFontFace,"loadSystemFont shouldn't be called when `disableFontFace` is set."),this.isFontLoadingAPISupported){const{loadedName:i,src:s,style:n}=t,a=new FontFace(i,s,n);this.addNativeFontFace(a);try{await a.load(),this.#De.add(i),e?.(t)}catch{_(`Cannot load system font: ${t.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(a)}}else x("Not implemented: loadSystemFont without the Font Loading API.")}async bind(t){if(t.attached||t.missingFile&&!t.systemFontInfo)return;if(t.attached=!0,t.systemFontInfo)return void await this.loadSystemFont(t);if(this.isFontLoadingAPISupported){const e=t.createNativeFontFace();if(e){this.addNativeFontFace(e);try{await e.loaded}catch(i){throw _(`Failed to load font '${e.family}': '${i}'.`),t.disableFontFace=!0,i}}return}const e=t.createFontFaceRule();if(e){if(this.insertRule(e),this.isSyncFontLoadingSupported)return;await new Promise((e=>{const i=this._queueLoadingCallback(e);this._prepareFontLoadEvent(t,i)}))}}get isFontLoadingAPISupported(){return S(this,"isFontLoadingAPISupported",!!this._document?.fonts)}get isSyncFontLoadingSupported(){let t=!1;return(a||"undefined"!=typeof navigator&&"string"==typeof navigator?.userAgent&&/Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent))&&(t=!0),S(this,"isSyncFontLoadingSupported",t)}_queueLoadingCallback(t){const{loadingRequests:e}=this,i={done:!1,complete:function(){for(C(!i.done,"completeRequest() cannot be called twice."),i.done=!0;e.length>0&&e[0].done;){const t=e.shift();setTimeout(t.callback,0)}},callback:t};return e.push(i),i}get _loadTestFont(){return S(this,"_loadTestFont",atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA=="))}_prepareFontLoadEvent(t,e){function i(t,e){return t.charCodeAt(e)<<24|t.charCodeAt(e+1)<<16|t.charCodeAt(e+2)<<8|255&t.charCodeAt(e+3)}function s(t,e,i,s){return t.substring(0,e)+s+t.substring(e+i)}let n,a;const r=this._document.createElement("canvas");r.width=1,r.height=1;const o=r.getContext("2d");let l=0;const h=`lt${Date.now()}${this.loadTestFontId++}`;let d=this._loadTestFont;d=s(d,976,h.length,h);const c=1482184792;let u=i(d,16);for(n=0,a=h.length-3;n>24&255,p>>16&255,p>>8&255,255&p)));const g=`@font-face {font-family:"${h}";src:url(data:font/opentype;base64,${btoa(d)});}`;this.insertRule(g);const m=this._document.createElement("div");m.style.visibility="hidden",m.style.width=m.style.height="10px",m.style.position="absolute",m.style.top=m.style.left="0px";for(const e of[t.loadedName,h]){const t=this._document.createElement("span");t.textContent="Hi",t.style.fontFamily=e,m.append(t)}this._document.body.append(m),function t(e,i){if(++l>30)return _("Load test font never loaded."),void i();o.font="30px "+e,o.fillText(".",0,20),o.getImageData(0,0,1,1).data[3]>0?i():setTimeout(t.bind(null,e,i))}(h,(()=>{m.remove(),e.complete()}))}}class Ht{constructor(t,{disableFontFace:e=!1,inspectFont:i=null}){this.compiledGlyphs=Object.create(null);for(const e in t)this[e]=t[e];this.disableFontFace=!0===e,this._inspectFont=i}createNativeFontFace(){if(!this.data||this.disableFontFace)return null;let t;if(this.cssFontInfo){const e={weight:this.cssFontInfo.fontWeight};this.cssFontInfo.italicAngle&&(e.style=`oblique ${this.cssFontInfo.italicAngle}deg`),t=new FontFace(this.cssFontInfo.fontFamily,this.data,e)}else t=new FontFace(this.loadedName,this.data,{});return this._inspectFont?.(this),t}createFontFaceRule(){if(!this.data||this.disableFontFace)return null;const t=F(this.data),e=`url(data:${this.mimetype};base64,${btoa(t)});`;let i;if(this.cssFontInfo){let t=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(t+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`),i=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${t}src:${e}}`}else i=`@font-face {font-family:"${this.loadedName}";src:${e}}`;return this._inspectFont?.(this,e),i}getPathGenerator(t,e){if(void 0!==this.compiledGlyphs[e])return this.compiledGlyphs[e];let i;try{i=t.get(this.loadedName+"_path_"+e)}catch(t){_(`getPathGenerator - ignoring character: "${t}".`)}if(!Array.isArray(i)||0===i.length)return this.compiledGlyphs[e]=function(t,e){};const s=[];for(let t=0,e=i.length;tt.bezierCurveTo(e,n,a,r,o,l))),t+=6}break;case 1:{const[e,n]=i.slice(t,t+2);s.push((t=>t.moveTo(e,n))),t+=2}break;case 2:{const[e,n]=i.slice(t,t+2);s.push((t=>t.lineTo(e,n))),t+=2}break;case 3:{const[e,n,a,r]=i.slice(t,t+4);s.push((t=>t.quadraticCurveTo(e,n,a,r))),t+=4}break;case 4:s.push((t=>t.restore()));break;case 5:s.push((t=>t.save()));break;case 6:C(2===s.length,"Scale command is only valid at the third position.");break;case 7:{const[e,n,a,r,o,l]=i.slice(t,t+6);s.push((t=>t.transform(e,n,a,r,o,l))),t+=6}break;case 8:{const[e,n]=i.slice(t,t+2);s.push((t=>t.translate(e,n))),t+=2}}return this.compiledGlyphs[e]=function(t,e){s[0](t),s[1](t),t.scale(e,-e);for(let e=2,i=s.length;e{const t=await import("fs"),e=await import("http"),i=await import("https"),s=await import("url");return new Map(Object.entries({fs:t,http:e,https:i,url:s,canvas:void 0,path2d:void 0}))})().then((t=>{Ut=t,jt.resolve()}),(t=>{_(`loadPackages: ${t}`),Ut=new Map,jt.resolve()}))}class $t{static get promise(){return jt.promise}static get(t){return Ut?.get(t)}}const Wt=function(t){return $t.get("fs").promises.readFile(t).then((t=>new Uint8Array(t)))},Gt="Fill",Vt="Stroke",qt="Shading";function Xt(t,e){if(!e)return;const i=e[2]-e[0],s=e[3]-e[1],n=new Path2D;n.rect(e[0],e[1],i,s),t.clip(n)}class Kt{getPattern(){x("Abstract method `getPattern` called.")}}class Yt extends Kt{constructor(t){super(),this._type=t[1],this._bbox=t[2],this._colorStops=t[3],this._p0=t[4],this._p1=t[5],this._r0=t[6],this._r1=t[7],this.matrix=null}_createGradient(t){let e;"axial"===this._type?e=t.createLinearGradient(this._p0[0],this._p0[1],this._p1[0],this._p1[1]):"radial"===this._type&&(e=t.createRadialGradient(this._p0[0],this._p0[1],this._r0,this._p1[0],this._p1[1],this._r1));for(const t of this._colorStops)e.addColorStop(t[0],t[1]);return e}getPattern(t,e,i,s){let n;if(s===Vt||s===Gt){const a=e.current.getClippedPathBoundingBox(s,ft(t))||[0,0,0,0],r=Math.ceil(a[2]-a[0])||1,o=Math.ceil(a[3]-a[1])||1,l=e.cachedCanvases.getCanvas("pattern",r,o),h=l.context;h.clearRect(0,0,h.canvas.width,h.canvas.height),h.beginPath(),h.rect(0,0,h.canvas.width,h.canvas.height),h.translate(-a[0],-a[1]),i=H.transform(i,[1,0,0,1,a[0],a[1]]),h.transform(...e.baseTransform),this.matrix&&h.transform(...this.matrix),Xt(h,this._bbox),h.fillStyle=this._createGradient(h),h.fill(),n=t.createPattern(l.canvas,"no-repeat");const d=new DOMMatrix(i);n.setTransform(d)}else Xt(t,this._bbox),n=this._createGradient(t);return n}}function Qt(t,e,i,s,n,a,r,o){const l=e.coords,h=e.colors,d=t.data,c=4*t.width;let u;l[i+1]>l[s+1]&&(u=i,i=s,s=u,u=a,a=r,r=u),l[s+1]>l[n+1]&&(u=s,s=n,n=u,u=r,r=o,o=u),l[i+1]>l[s+1]&&(u=i,i=s,s=u,u=a,a=r,r=u);const p=(l[i]+e.offsetX)*e.scaleX,g=(l[i+1]+e.offsetY)*e.scaleY,m=(l[s]+e.offsetX)*e.scaleX,f=(l[s+1]+e.offsetY)*e.scaleY,b=(l[n]+e.offsetX)*e.scaleX,v=(l[n+1]+e.offsetY)*e.scaleY;if(g>=v)return;const A=h[a],y=h[a+1],w=h[a+2],_=h[r],x=h[r+1],C=h[r+2],E=h[o],S=h[o+1],T=h[o+2],M=Math.round(g),k=Math.round(v);let I,P,R,D,L,F,N,O;for(let t=M;t<=k;t++){if(tv?1:f===v?0:(f-t)/(f-v),I=m-(m-b)*e,P=_-(_-E)*e,R=x-(x-S)*e,D=C-(C-T)*e}let e;e=tv?1:(g-t)/(g-v),L=p-(p-b)*e,F=A-(A-E)*e,N=y-(y-S)*e,O=w-(w-T)*e;const i=Math.round(Math.min(I,L)),s=Math.round(Math.max(I,L));let n=c*t+4*i;for(let t=i;t<=s;t++)e=(I-t)/(I-L),e<0?e=0:e>1&&(e=1),d[n++]=P-(P-F)*e|0,d[n++]=R-(R-N)*e|0,d[n++]=D-(D-O)*e|0,d[n++]=255}}function Jt(t,e,i){const s=e.coords,n=e.colors;let a,r;switch(e.type){case"lattice":const o=e.verticesPerRow,l=Math.floor(s.length/o)-1,h=o-1;for(a=0;a=Math.ceil(p*b)?A=o:_=!0,E>=Math.ceil(g*v)?y=l:x=!0;const S=this.getSizeAndScale(A,this.ctx.canvas.width,b),T=this.getSizeAndScale(y,this.ctx.canvas.height,v),M=t.cachedCanvases.getCanvas("pattern",S.size,T.size),k=M.context,I=r.createCanvasGraphics(k);if(I.groupLevel=t.groupLevel,this.setFillAndStrokeStyleToContext(I,s,a),k.translate(-S.scale*h,-T.scale*d),I.transform(S.scale,0,0,T.scale,0,0),k.save(),this.clipBbox(I,h,d,c,u),I.baseTransform=ft(I.ctx),I.executeOperatorList(i),I.endDrawing(),k.restore(),_||x){const e=M.canvas;_&&(A=o),x&&(y=l);const i=this.getSizeAndScale(A,this.ctx.canvas.width,b),s=this.getSizeAndScale(y,this.ctx.canvas.height,v),n=i.size,a=s.size,r=t.cachedCanvases.getCanvas("pattern-workaround",n,a),c=r.context,u=_?Math.floor(p/o):0,m=x?Math.floor(g/l):0;for(let t=0;t<=u;t++)for(let i=0;i<=m;i++)c.drawImage(e,n*t,a*i,n,a,0,0,n,a);return{canvas:r.canvas,scaleX:i.scale,scaleY:s.scale,offsetX:h,offsetY:d}}return{canvas:M.canvas,scaleX:S.scale,scaleY:T.scale,offsetX:h,offsetY:d}}getSizeAndScale(t,e,i){const s=Math.max(ee.MAX_PATTERN_SIZE,e);let n=Math.ceil(t*i);return n>=s?n=s:i=n/t,{scale:i,size:n}}clipBbox(t,e,i,s,n){const a=s-e,r=n-i;t.ctx.rect(e,i,a,r),t.current.updateRectMinMax(ft(t.ctx),[e,i,s,n]),t.clip(),t.endPath()}setFillAndStrokeStyleToContext(t,e,i){const s=t.ctx,n=t.current;switch(e){case 1:const t=this.ctx;s.fillStyle=t.fillStyle,s.strokeStyle=t.strokeStyle,n.fillColor=t.fillStyle,n.strokeColor=t.strokeStyle;break;case 2:const a=H.makeHexColor(i[0],i[1],i[2]);s.fillStyle=a,s.strokeStyle=a,n.fillColor=a,n.strokeColor=a;break;default:throw new D(`Unsupported paint type: ${e}`)}}getPattern(t,e,i,s){let n=i;s!==qt&&(n=H.transform(n,e.baseTransform),this.matrix&&(n=H.transform(n,this.matrix)));const a=this.createPatternCanvas(e);let r=new DOMMatrix(n);r=r.translate(a.offsetX,a.offsetY),r=r.scale(1/a.scaleX,1/a.scaleY);const o=t.createPattern(a.canvas,"repeat");return o.setTransform(r),o}}function ie({src:t,srcPos:e=0,dest:i,width:s,height:n,nonBlackColor:a=4294967295,inverseDecode:r=!1}){const o=B.isLittleEndian?4278190080:255,[l,h]=r?[a,o]:[o,a],d=s>>3,c=7&s,u=t.length;i=new Uint32Array(i.buffer);let p=0;for(let s=0;s>2),p=i.length,f=s+7>>3,b=4294967295,v=B.isLittleEndian?4278190080:255;for(u=0;uf?s:8*t-7,r=-8&a;let o=0,c=0;for(;n>=1}for(;l=a&&(m=n,f=s*m),l=0,g=f;g--;)c[l++]=d[h++],c[l++]=d[h++],c[l++]=d[h++],c[l++]=255;t.putImageData(o,0,u*se)}}}function le(t,e){if(e.bitmap)return void t.drawImage(e.bitmap,0,0);const i=e.height,s=e.width,n=i%se,a=(i-n)/se,r=0===n?a:a+1,o=t.createImageData(s,se);let l=0;const h=e.data,d=o.data;for(let e=0;e10&&"function"==typeof i,h=l?Date.now()+15:0;let d=0;const c=this.commonObjs,u=this.objs;let p;for(;;){if(void 0!==s&&r===s.nextBreakPoint)return s.breakIt(r,i),r;if(p=a[r],p!==f.dependency)this[p].apply(this,n[r]);else for(const t of n[r]){const e=t.startsWith("g_")?c:u;if(!e.has(t))return e.get(t,i),r}if(r++,r===o)return r;if(l&&++d>10){if(Date.now()>h)return i(),r;d=0}}}#Le(){for(;this.stateStack.length||this.inSMaskMode;)this.restore();this.current.activeSMask=null,this.ctx.restore(),this.transparentCanvas&&(this.ctx=this.compositeCtx,this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.drawImage(this.transparentCanvas,0,0),this.ctx.restore(),this.transparentCanvas=null)}endDrawing(){this.#Le(),this.cachedCanvases.clear(),this.cachedPatterns.clear();for(const t of this._cachedBitmapsMap.values()){for(const e of t.values())"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement&&(e.width=e.height=0);t.clear()}this._cachedBitmapsMap.clear(),this.#Fe()}#Fe(){if(this.pageColors){const t=this.filterFactory.addHCMFilter(this.pageColors.foreground,this.pageColors.background);if("none"!==t){const e=this.ctx.filter;this.ctx.filter=t,this.ctx.drawImage(this.ctx.canvas,0,0),this.ctx.filter=e}}}_scaleImage(t,e){const i=t.width,s=t.height;let n,a,r=Math.max(Math.hypot(e[0],e[1]),1),o=Math.max(Math.hypot(e[2],e[3]),1),l=i,h=s,d="prescale1";for(;r>2&&l>1||o>2&&h>1;){let e=l,i=h;r>2&&l>1&&(e=l>=16384?Math.floor(l/2)-1||1:Math.ceil(l/2),r/=l/e),o>2&&h>1&&(i=h>=16384?Math.floor(h/2)-1||1:Math.ceil(h)/2,o/=h/i),n=this.cachedCanvases.getCanvas(d,e,i),a=n.context,a.clearRect(0,0,e,i),a.drawImage(t,0,0,l,h,0,0,e,i),t=n.canvas,l=e,h=i,d="prescale1"===d?"prescale2":"prescale1"}return{img:t,paintWidth:l,paintHeight:h}}_createMaskCanvas(t){const e=this.ctx,{width:i,height:s}=t,n=this.current.fillColor,a=this.current.patternFill,r=ft(e);let o,l,h,d;if((t.bitmap||t.data)&&t.count>1){const e=t.bitmap||t.data.buffer;l=JSON.stringify(a?r:[r.slice(0,4),n]),o=this._cachedBitmapsMap.get(e),o||(o=new Map,this._cachedBitmapsMap.set(e,o));const i=o.get(l);if(i&&!a)return{canvas:i,offsetX:Math.round(Math.min(r[0],r[2])+r[4]),offsetY:Math.round(Math.min(r[1],r[3])+r[5])};h=i}h||(d=this.cachedCanvases.getCanvas("maskCanvas",i,s),le(d.context,t));let c=H.transform(r,[1/i,0,0,-1/s,0,0]);c=H.transform(c,[1,0,0,1,0,-s]);const[u,p,g,m]=H.getAxialAlignedBoundingBox([0,0,i,s],c),f=Math.round(g-u)||1,b=Math.round(m-p)||1,v=this.cachedCanvases.getCanvas("fillCanvas",f,b),A=v.context,y=u,w=p;A.translate(-y,-w),A.transform(...c),h||(h=this._scaleImage(d.canvas,bt(A)),h=h.img,o&&a&&o.set(l,h)),A.imageSmoothingEnabled=ce(ft(A),t.interpolate),ae(A,h,0,0,h.width,h.height,0,0,i,s),A.globalCompositeOperation="source-in";const _=H.transform(bt(A),[1,0,0,1,-y,-w]);return A.fillStyle=a?n.getPattern(e,this,_,Gt):n,A.fillRect(0,0,i,s),o&&!a&&(this.cachedCanvases.delete("fillCanvas"),o.set(l,v.canvas)),{canvas:v.canvas,offsetX:Math.round(y),offsetY:Math.round(w)}}setLineWidth(t){t!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=t,this.ctx.lineWidth=t}setLineCap(t){this.ctx.lineCap=ue[t]}setLineJoin(t){this.ctx.lineJoin=pe[t]}setMiterLimit(t){this.ctx.miterLimit=t}setDash(t,e){const i=this.ctx;void 0!==i.setLineDash&&(i.setLineDash(t),i.lineDashOffset=e)}setRenderingIntent(t){}setFlatness(t){}setGState(t){for(const[e,i]of t)switch(e){case"LW":this.setLineWidth(i);break;case"LC":this.setLineCap(i);break;case"LJ":this.setLineJoin(i);break;case"ML":this.setMiterLimit(i);break;case"D":this.setDash(i[0],i[1]);break;case"RI":this.setRenderingIntent(i);break;case"FL":this.setFlatness(i);break;case"Font":this.setFont(i[0],i[1]);break;case"CA":this.current.strokeAlpha=i;break;case"ca":this.current.fillAlpha=i,this.ctx.globalAlpha=i;break;case"BM":this.ctx.globalCompositeOperation=i;break;case"SMask":this.current.activeSMask=i?this.tempSMask:null,this.tempSMask=null,this.checkSMaskState();break;case"TR":this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(i)}}get inSMaskMode(){return!!this.suspendedCtx}checkSMaskState(){const t=this.inSMaskMode;this.current.activeSMask&&!t?this.beginSMaskMode():!this.current.activeSMask&&t&&this.endSMaskMode()}beginSMaskMode(){if(this.inSMaskMode)throw new Error("beginSMaskMode called while already in smask mode");const t=this.ctx.canvas.width,e=this.ctx.canvas.height,i="smaskGroupAt"+this.groupLevel,s=this.cachedCanvases.getCanvas(i,t,e);this.suspendedCtx=this.ctx,this.ctx=s.context;const n=this.ctx;n.setTransform(...ft(this.suspendedCtx)),he(this.suspendedCtx,n),function(t,e){if(t._removeMirroring)throw new Error("Context is already forwarding operations.");t.__originalSave=t.save,t.__originalRestore=t.restore,t.__originalRotate=t.rotate,t.__originalScale=t.scale,t.__originalTranslate=t.translate,t.__originalTransform=t.transform,t.__originalSetTransform=t.setTransform,t.__originalResetTransform=t.resetTransform,t.__originalClip=t.clip,t.__originalMoveTo=t.moveTo,t.__originalLineTo=t.lineTo,t.__originalBezierCurveTo=t.bezierCurveTo,t.__originalRect=t.rect,t.__originalClosePath=t.closePath,t.__originalBeginPath=t.beginPath,t._removeMirroring=()=>{t.save=t.__originalSave,t.restore=t.__originalRestore,t.rotate=t.__originalRotate,t.scale=t.__originalScale,t.translate=t.__originalTranslate,t.transform=t.__originalTransform,t.setTransform=t.__originalSetTransform,t.resetTransform=t.__originalResetTransform,t.clip=t.__originalClip,t.moveTo=t.__originalMoveTo,t.lineTo=t.__originalLineTo,t.bezierCurveTo=t.__originalBezierCurveTo,t.rect=t.__originalRect,t.closePath=t.__originalClosePath,t.beginPath=t.__originalBeginPath,delete t._removeMirroring},t.save=function(){e.save(),this.__originalSave()},t.restore=function(){e.restore(),this.__originalRestore()},t.translate=function(t,i){e.translate(t,i),this.__originalTranslate(t,i)},t.scale=function(t,i){e.scale(t,i),this.__originalScale(t,i)},t.transform=function(t,i,s,n,a,r){e.transform(t,i,s,n,a,r),this.__originalTransform(t,i,s,n,a,r)},t.setTransform=function(t,i,s,n,a,r){e.setTransform(t,i,s,n,a,r),this.__originalSetTransform(t,i,s,n,a,r)},t.resetTransform=function(){e.resetTransform(),this.__originalResetTransform()},t.rotate=function(t){e.rotate(t),this.__originalRotate(t)},t.clip=function(t){e.clip(t),this.__originalClip(t)},t.moveTo=function(t,i){e.moveTo(t,i),this.__originalMoveTo(t,i)},t.lineTo=function(t,i){e.lineTo(t,i),this.__originalLineTo(t,i)},t.bezierCurveTo=function(t,i,s,n,a,r){e.bezierCurveTo(t,i,s,n,a,r),this.__originalBezierCurveTo(t,i,s,n,a,r)},t.rect=function(t,i,s,n){e.rect(t,i,s,n),this.__originalRect(t,i,s,n)},t.closePath=function(){e.closePath(),this.__originalClosePath()},t.beginPath=function(){e.beginPath(),this.__originalBeginPath()}}(n,this.suspendedCtx),this.setGState([["BM","source-over"],["ca",1],["CA",1]])}endSMaskMode(){if(!this.inSMaskMode)throw new Error("endSMaskMode called while not in smask mode");this.ctx._removeMirroring(),he(this.ctx,this.suspendedCtx),this.ctx=this.suspendedCtx,this.suspendedCtx=null}compose(t){if(!this.current.activeSMask)return;t?(t[0]=Math.floor(t[0]),t[1]=Math.floor(t[1]),t[2]=Math.ceil(t[2]),t[3]=Math.ceil(t[3])):t=[0,0,this.ctx.canvas.width,this.ctx.canvas.height];const e=this.current.activeSMask,i=this.suspendedCtx;this.composeSMask(i,e,this.ctx,t),this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height),this.ctx.restore()}composeSMask(t,e,i,s){const n=s[0],a=s[1],r=s[2]-n,o=s[3]-a;0!==r&&0!==o&&(this.genericComposeSMask(e.context,i,r,o,e.subtype,e.backdrop,e.transferMap,n,a,e.offsetX,e.offsetY),t.save(),t.globalAlpha=1,t.globalCompositeOperation="source-over",t.setTransform(1,0,0,1,0,0),t.drawImage(i.canvas,0,0),t.restore())}genericComposeSMask(t,e,i,s,n,a,r,o,l,h,d){let c=t.canvas,u=o-h,p=l-d;if(a)if(u<0||p<0||u+i>c.width||p+s>c.height){const t=this.cachedCanvases.getCanvas("maskExtension",i,s),e=t.context;e.drawImage(c,-u,-p),a.some((t=>0!==t))&&(e.globalCompositeOperation="destination-atop",e.fillStyle=H.makeHexColor(...a),e.fillRect(0,0,i,s),e.globalCompositeOperation="source-over"),c=t.canvas,u=p=0}else if(a.some((t=>0!==t))){t.save(),t.globalAlpha=1,t.setTransform(1,0,0,1,0,0);const e=new Path2D;e.rect(u,p,i,s),t.clip(e),t.globalCompositeOperation="destination-atop",t.fillStyle=H.makeHexColor(...a),t.fillRect(u,p,i,s),t.restore()}e.save(),e.globalAlpha=1,e.setTransform(1,0,0,1,0,0),"Alpha"===n&&r?e.filter=this.filterFactory.addAlphaFilter(r):"Luminosity"===n&&(e.filter=this.filterFactory.addLuminosityFilter(r));const g=new Path2D;g.rect(o,l,i,s),e.clip(g),e.globalCompositeOperation="destination-in",e.drawImage(c,u,p,i,s,o,l,i,s),e.restore()}save(){this.inSMaskMode?(he(this.ctx,this.suspendedCtx),this.suspendedCtx.save()):this.ctx.save();const t=this.current;this.stateStack.push(t),this.current=t.clone()}restore(){0===this.stateStack.length&&this.inSMaskMode&&this.endSMaskMode(),0!==this.stateStack.length&&(this.current=this.stateStack.pop(),this.inSMaskMode?(this.suspendedCtx.restore(),he(this.suspendedCtx,this.ctx)):this.ctx.restore(),this.checkSMaskState(),this.pendingClip=null,this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null)}transform(t,e,i,s,n,a){this.ctx.transform(t,e,i,s,n,a),this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null}constructPath(t,e,i){const s=this.ctx,n=this.current;let a,r,o=n.x,l=n.y;const h=ft(s),d=0===h[0]&&0===h[3]||0===h[1]&&0===h[2],c=d?i.slice(0):null;for(let i=0,u=0,p=t.length;i100&&(h=100),this.current.fontSizeScale=e/h,this.ctx.font=`${l} ${r} ${h}px ${a}`}setTextRenderingMode(t){this.current.textRenderingMode=t}setTextRise(t){this.current.textRise=t}moveText(t,e){this.current.x=this.current.lineX+=t,this.current.y=this.current.lineY+=e}setLeadingMoveText(t,e){this.setLeading(-e),this.moveText(t,e)}setTextMatrix(t,e,i,s,n,a){this.current.textMatrix=[t,e,i,s,n,a],this.current.textMatrixScale=Math.hypot(t,e),this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0}nextLine(){this.moveText(0,this.current.leading)}paintChar(t,e,i,s){const n=this.ctx,a=this.current,r=a.font,o=a.textRenderingMode,l=a.fontSize/a.fontSizeScale,h=3&o,d=!!(4&o),c=a.patternFill&&!r.missingFile;let u;(r.disableFontFace||d||c)&&(u=r.getPathGenerator(this.commonObjs,t)),r.disableFontFace||c?(n.save(),n.translate(e,i),n.beginPath(),u(n,l),s&&n.setTransform(...s),0!==h&&2!==h||n.fill(),1!==h&&2!==h||n.stroke(),n.restore()):(0!==h&&2!==h||n.fillText(t,e,i),1!==h&&2!==h||n.strokeText(t,e,i)),d&&(this.pendingTextPaths||=[]).push({transform:ft(n),x:e,y:i,fontSize:l,addToPath:u})}get isFontSubpixelAAEnabled(){const{context:t}=this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled",10,10);t.scale(1.5,1),t.fillText("I",0,10);const e=t.getImageData(0,0,10,10).data;let i=!1;for(let t=3;t0&&e[t]<255){i=!0;break}return S(this,"isFontSubpixelAAEnabled",i)}showText(t){const e=this.current,i=e.font;if(i.isType3Font)return this.showType3Text(t);const s=e.fontSize;if(0===s)return;const n=this.ctx,a=e.fontSizeScale,r=e.charSpacing,o=e.wordSpacing,l=e.fontDirection,h=e.textHScale*l,d=t.length,c=i.vertical,u=c?1:-1,p=i.defaultVMetrics,g=s*e.fontMatrix[0],m=0===e.textRenderingMode&&!i.disableFontFace&&!e.patternFill;let f;if(n.save(),n.transform(...e.textMatrix),n.translate(e.x,e.y+e.textRise),l>0?n.scale(h,-1):n.scale(h,1),e.patternFill){n.save();const t=e.fillColor.getPattern(n,this,bt(n),Gt);f=ft(n),n.restore(),n.fillStyle=t}let b=e.lineWidth;const v=e.textMatrixScale;if(0===v||0===b){const t=3&e.textRenderingMode;1!==t&&2!==t||(b=this.getSinglePixelWidth())}else b/=v;if(1!==a&&(n.scale(a,a),b/=a),n.lineWidth=b,i.isInvalidPDFjsFont){const i=[];let s=0;for(const e of t)i.push(e.unicode),s+=e.width;return n.fillText(i.join(""),0,0),e.x+=s*g*h,n.restore(),void this.compose()}let A,y=0;for(A=0;A0){const t=1e3*n.measureText(b).width/s*a;if(xnew fe(t,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack})};e=new ee(t,i,this.ctx,n,s)}else e=this._getPattern(t[1],t[2]);return e}setStrokeColorN(){this.current.strokeColor=this.getColorN_Pattern(arguments)}setFillColorN(){this.current.fillColor=this.getColorN_Pattern(arguments),this.current.patternFill=!0}setStrokeRGBColor(t,e,i){this.ctx.strokeStyle=this.current.strokeColor=H.makeHexColor(t,e,i)}setStrokeTransparent(){this.ctx.strokeStyle=this.current.strokeColor="transparent"}setFillRGBColor(t,e,i){this.ctx.fillStyle=this.current.fillColor=H.makeHexColor(t,e,i),this.current.patternFill=!1}setFillTransparent(){this.ctx.fillStyle=this.current.fillColor="transparent",this.current.patternFill=!1}_getPattern(t,e=null){let i;return this.cachedPatterns.has(t)?i=this.cachedPatterns.get(t):(i=function(t){switch(t[0]){case"RadialAxial":return new Yt(t);case"Mesh":return new Zt(t);case"Dummy":return new te}throw new Error(`Unknown IR type: ${t[0]}`)}(this.getObject(t)),this.cachedPatterns.set(t,i)),e&&(i.matrix=e),i}shadingFill(t){if(!this.contentVisible)return;const e=this.ctx;this.save();const i=this._getPattern(t);e.fillStyle=i.getPattern(e,this,bt(e),qt);const s=bt(e);if(s){const{width:t,height:i}=e.canvas,[n,a,r,o]=H.getAxialAlignedBoundingBox([0,0,t,i],s);this.ctx.fillRect(n,a,r-n,o-a)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.compose(this.current.getClippedPathBoundingBox()),this.restore()}beginInlineImage(){x("Should not call beginInlineImage")}beginImageData(){x("Should not call beginImageData")}paintFormXObjectBegin(t,e){if(this.contentVisible&&(this.save(),this.baseTransformStack.push(this.baseTransform),t&&this.transform(...t),this.baseTransform=ft(this.ctx),e)){const t=e[2]-e[0],i=e[3]-e[1];this.ctx.rect(e[0],e[1],t,i),this.current.updateRectMinMax(ft(this.ctx),e),this.clip(),this.endPath()}}paintFormXObjectEnd(){this.contentVisible&&(this.restore(),this.baseTransform=this.baseTransformStack.pop())}beginGroup(t){if(!this.contentVisible)return;this.save(),this.inSMaskMode&&(this.endSMaskMode(),this.current.activeSMask=null);const e=this.ctx;t.isolated||w("TODO: Support non-isolated groups."),t.knockout&&_("Knockout groups not supported.");const i=ft(e);if(t.matrix&&e.transform(...t.matrix),!t.bbox)throw new Error("Bounding box is required.");let s=H.getAxialAlignedBoundingBox(t.bbox,ft(e));const n=[0,0,e.canvas.width,e.canvas.height];s=H.intersect(s,n)||[0,0,0,0];const a=Math.floor(s[0]),r=Math.floor(s[1]),o=Math.max(Math.ceil(s[2])-a,1),l=Math.max(Math.ceil(s[3])-r,1);this.current.startNewPathAndClipBox([0,0,o,l]);let h="groupAt"+this.groupLevel;t.smask&&(h+="_smask_"+this.smaskCounter++%2);const d=this.cachedCanvases.getCanvas(h,o,l),c=d.context;c.translate(-a,-r),c.transform(...i),t.smask?this.smaskStack.push({canvas:d.canvas,context:c,offsetX:a,offsetY:r,subtype:t.smask.subtype,backdrop:t.smask.backdrop,transferMap:t.smask.transferMap||null,startTransformInverse:null}):(e.setTransform(1,0,0,1,0,0),e.translate(a,r),e.save()),he(e,c),this.ctx=c,this.setGState([["BM","source-over"],["ca",1],["CA",1]]),this.groupStack.push(e),this.groupLevel++}endGroup(t){if(!this.contentVisible)return;this.groupLevel--;const e=this.ctx,i=this.groupStack.pop();if(this.ctx=i,this.ctx.imageSmoothingEnabled=!1,t.smask)this.tempSMask=this.smaskStack.pop(),this.restore();else{this.ctx.restore();const t=ft(this.ctx);this.restore(),this.ctx.save(),this.ctx.setTransform(...t);const i=H.getAxialAlignedBoundingBox([0,0,e.canvas.width,e.canvas.height],t);this.ctx.drawImage(e.canvas,0,0),this.ctx.restore(),this.compose(i)}}beginAnnotation(t,e,i,s,n){if(this.#Le(),de(this.ctx),this.ctx.save(),this.save(),this.baseTransform&&this.ctx.setTransform(...this.baseTransform),e){const s=e[2]-e[0],a=e[3]-e[1];if(n&&this.annotationCanvasMap){(i=i.slice())[4]-=e[0],i[5]-=e[1],(e=e.slice())[0]=e[1]=0,e[2]=s,e[3]=a;const[n,r]=H.singularValueDecompose2dScale(ft(this.ctx)),{viewportScale:o}=this,l=Math.ceil(s*this.outputScaleX*o),h=Math.ceil(a*this.outputScaleY*o);this.annotationCanvas=this.canvasFactory.create(l,h);const{canvas:d,context:c}=this.annotationCanvas;this.annotationCanvasMap.set(t,d),this.annotationCanvas.savedCtx=this.ctx,this.ctx=c,this.ctx.save(),this.ctx.setTransform(n,0,0,-r,0,a*r),de(this.ctx)}else de(this.ctx),this.endPath(),this.ctx.rect(e[0],e[1],s,a),this.ctx.clip(),this.ctx.beginPath()}this.current=new re(this.ctx.canvas.width,this.ctx.canvas.height),this.transform(...i),this.transform(...s)}endAnnotation(){this.annotationCanvas&&(this.ctx.restore(),this.#Fe(),this.ctx=this.annotationCanvas.savedCtx,delete this.annotationCanvas.savedCtx,delete this.annotationCanvas)}paintImageMaskXObject(t){if(!this.contentVisible)return;const e=t.count;(t=this.getObject(t.data,t)).count=e;const i=this.ctx,s=this.processingType3;if(s&&(void 0===s.compiled&&(s.compiled=function(t){const{width:e,height:i}=t;if(e>1e3||i>1e3)return null;const s=new Uint8Array([0,2,4,0,1,0,5,4,8,10,0,8,0,2,1,0]),n=e+1;let a,r,o,l=new Uint8Array(n*(i+1));const h=e+7&-8;let d=new Uint8Array(h*i),c=0;for(const e of t.data){let t=128;for(;t>0;)d[c++]=e&t?0:255,t>>=1}let u=0;for(c=0,0!==d[c]&&(l[0]=1,++u),r=1;r>2)+(d[c+1]?4:0)+(d[c-h+1]?8:0),s[t]&&(l[o+r]=s[t],++u),c++;if(d[c-h]!==d[c]&&(l[o+r]=d[c]?2:4,++u),u>1e3)return null}for(c=h*(i-1),o=a*n,0!==d[c]&&(l[o]=8,++u),r=1;r1e3)return null;const p=new Int32Array([0,n,-1,0,-n,0,0,0,1]),g=new Path2D;for(a=0;u&&a<=i;a++){let t=a*n;const i=t+e;for(;t>4,l[t]&=r>>2|r<<2),g.lineTo(t%n,t/n|0),l[t]||--u}while(s!==t);--a}return d=null,l=null,function(t){t.save(),t.scale(1/e,-1/i),t.translate(0,-i),t.fill(g),t.beginPath(),t.restore()}}(t)),s.compiled))return void s.compiled(i);const n=this._createMaskCanvas(t),a=n.canvas;i.save(),i.setTransform(1,0,0,1,0,0),i.drawImage(a,n.offsetX,n.offsetY),i.restore(),this.compose()}paintImageMaskXObjectRepeat(t,e,i=0,s=0,n,a){if(!this.contentVisible)return;t=this.getObject(t.data,t);const r=this.ctx;r.save();const o=ft(r);r.transform(e,i,s,n,0,0);const l=this._createMaskCanvas(t);r.setTransform(1,0,0,1,l.offsetX-o[4],l.offsetY-o[5]);for(let t=0,h=a.length;te?h/e:1,r=l>e?l/e:1}}this._cachedScaleForStroking[0]=a,this._cachedScaleForStroking[1]=r}return this._cachedScaleForStroking}rescaleAndStroke(t){const{ctx:e}=this,{lineWidth:i}=this.current,[s,n]=this.getScaleForStroking();if(e.lineWidth=i||1,1===s&&1===n)return void e.stroke();const a=e.getLineDash();if(t&&e.save(),e.scale(s,n),a.length>0){const t=Math.max(s,n);e.setLineDash(a.map((e=>e/t))),e.lineDashOffset/=t}e.stroke(),t&&e.restore()}isContentVisible(){for(let t=this.markedContentStack.length-1;t>=0;t--)if(!this.markedContentStack[t].visible)return!1;return!0}}for(const t in f)void 0!==fe.prototype[t]&&(fe.prototype[f[t]]=fe.prototype[t]);class be{static#Ne=null;static#Oe="";static get workerPort(){return this.#Ne}static set workerPort(t){if(!("undefined"!=typeof Worker&&t instanceof Worker)&&null!==t)throw new Error("Invalid `workerPort` type.");this.#Ne=t}static get workerSrc(){return this.#Oe}static set workerSrc(t){if("string"!=typeof t)throw new Error("Invalid `workerSrc` type.");this.#Oe=t}}function ve(t){switch(t instanceof Error||"object"==typeof t&&null!==t||x('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),t.name){case"AbortException":return new L(t.message);case"MissingPDFException":return new P(t.message);case"PasswordException":return new M(t.message,t.code);case"UnexpectedResponseException":return new R(t.message,t.status);case"UnknownErrorException":return new k(t.message,t.details);default:return new k(t.message,t.toString())}}class Ae{constructor(t,e,i){this.sourceName=t,this.targetName=e,this.comObj=i,this.callbackId=1,this.streamId=1,this.streamSinks=Object.create(null),this.streamControllers=Object.create(null),this.callbackCapabilities=Object.create(null),this.actionHandler=Object.create(null),this._onComObjOnMessage=t=>{const e=t.data;if(e.targetName!==this.sourceName)return;if(e.stream)return void this.#Be(e);if(e.callback){const t=e.callbackId,i=this.callbackCapabilities[t];if(!i)throw new Error(`Cannot resolve callback ${t}`);if(delete this.callbackCapabilities[t],1===e.callback)i.resolve(e.data);else{if(2!==e.callback)throw new Error("Unexpected callback case");i.reject(ve(e.reason))}return}const s=this.actionHandler[e.action];if(!s)throw new Error(`Unknown action from worker: ${e.action}`);if(e.callbackId){const t=this.sourceName,n=e.sourceName;new Promise((function(t){t(s(e.data))})).then((function(s){i.postMessage({sourceName:t,targetName:n,callback:1,callbackId:e.callbackId,data:s})}),(function(s){i.postMessage({sourceName:t,targetName:n,callback:2,callbackId:e.callbackId,reason:ve(s)})}))}else e.streamId?this.#ze(e):s(e.data)},i.addEventListener("message",this._onComObjOnMessage)}on(t,e){const i=this.actionHandler;if(i[t])throw new Error(`There is already an actionName called "${t}"`);i[t]=e}send(t,e,i){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,data:e},i)}sendWithPromise(t,e,i){const s=this.callbackId++,n=Promise.withResolvers();this.callbackCapabilities[s]=n;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,callbackId:s,data:e},i)}catch(t){n.reject(t)}return n.promise}sendWithStream(t,e,i,s){const n=this.streamId++,a=this.sourceName,r=this.targetName,o=this.comObj;return new ReadableStream({start:i=>{const l=Promise.withResolvers();return this.streamControllers[n]={controller:i,startCall:l,pullCall:null,cancelCall:null,isClosed:!1},o.postMessage({sourceName:a,targetName:r,action:t,streamId:n,data:e,desiredSize:i.desiredSize},s),l.promise},pull:t=>{const e=Promise.withResolvers();return this.streamControllers[n].pullCall=e,o.postMessage({sourceName:a,targetName:r,stream:6,streamId:n,desiredSize:t.desiredSize}),e.promise},cancel:t=>{C(t instanceof Error,"cancel must have a valid reason");const e=Promise.withResolvers();return this.streamControllers[n].cancelCall=e,this.streamControllers[n].isClosed=!0,o.postMessage({sourceName:a,targetName:r,stream:1,streamId:n,reason:ve(t)}),e.promise}},i)}#ze(t){const e=t.streamId,i=this.sourceName,s=t.sourceName,n=this.comObj,a=this,r=this.actionHandler[t.action],o={enqueue(t,a=1,r){if(this.isCancelled)return;const o=this.desiredSize;this.desiredSize-=a,o>0&&this.desiredSize<=0&&(this.sinkCapability=Promise.withResolvers(),this.ready=this.sinkCapability.promise),n.postMessage({sourceName:i,targetName:s,stream:4,streamId:e,chunk:t},r)},close(){this.isCancelled||(this.isCancelled=!0,n.postMessage({sourceName:i,targetName:s,stream:3,streamId:e}),delete a.streamSinks[e])},error(t){C(t instanceof Error,"error must have a valid reason"),this.isCancelled||(this.isCancelled=!0,n.postMessage({sourceName:i,targetName:s,stream:5,streamId:e,reason:ve(t)}))},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:t.desiredSize,ready:null};o.sinkCapability.resolve(),o.ready=o.sinkCapability.promise,this.streamSinks[e]=o,new Promise((function(e){e(r(t.data,o))})).then((function(){n.postMessage({sourceName:i,targetName:s,stream:8,streamId:e,success:!0})}),(function(t){n.postMessage({sourceName:i,targetName:s,stream:8,streamId:e,reason:ve(t)})}))}#Be(t){const e=t.streamId,i=this.sourceName,s=t.sourceName,n=this.comObj,a=this.streamControllers[e],r=this.streamSinks[e];switch(t.stream){case 8:t.success?a.startCall.resolve():a.startCall.reject(ve(t.reason));break;case 7:t.success?a.pullCall.resolve():a.pullCall.reject(ve(t.reason));break;case 6:if(!r){n.postMessage({sourceName:i,targetName:s,stream:7,streamId:e,success:!0});break}r.desiredSize<=0&&t.desiredSize>0&&r.sinkCapability.resolve(),r.desiredSize=t.desiredSize,new Promise((function(t){t(r.onPull?.())})).then((function(){n.postMessage({sourceName:i,targetName:s,stream:7,streamId:e,success:!0})}),(function(t){n.postMessage({sourceName:i,targetName:s,stream:7,streamId:e,reason:ve(t)})}));break;case 4:if(C(a,"enqueue should have stream controller"),a.isClosed)break;a.controller.enqueue(t.chunk);break;case 3:if(C(a,"close should have stream controller"),a.isClosed)break;a.isClosed=!0,a.controller.close(),this.#He(a,e);break;case 5:C(a,"error should have stream controller"),a.controller.error(ve(t.reason)),this.#He(a,e);break;case 2:t.success?a.cancelCall.resolve():a.cancelCall.reject(ve(t.reason)),this.#He(a,e);break;case 1:if(!r)break;new Promise((function(e){e(r.onCancel?.(ve(t.reason)))})).then((function(){n.postMessage({sourceName:i,targetName:s,stream:2,streamId:e,success:!0})}),(function(t){n.postMessage({sourceName:i,targetName:s,stream:2,streamId:e,reason:ve(t)})})),r.sinkCapability.reject(ve(t.reason)),r.isCancelled=!0,delete this.streamSinks[e];break;default:throw new Error("Unexpected stream case")}}async#He(t,e){await Promise.allSettled([t.startCall?.promise,t.pullCall?.promise,t.cancelCall?.promise]),delete this.streamControllers[e]}destroy(){this.comObj.removeEventListener("message",this._onComObjOnMessage)}}class ye{#je;#Ue;constructor({parsedData:t,rawData:e}){this.#je=t,this.#Ue=e}getRaw(){return this.#Ue}get(t){return this.#je.get(t)??null}getAll(){return O(this.#je)}has(t){return this.#je.has(t)}}const we=Symbol("INTERNAL");class _e{#$e=!1;#We=!1;#Ge=!1;#Ve=!0;constructor(t,{name:e,intent:i,usage:s}){this.#$e=!!(2&t),this.#We=!!(4&t),this.name=e,this.intent=i,this.usage=s}get visible(){if(this.#Ge)return this.#Ve;if(!this.#Ve)return!1;const{print:t,view:e}=this.usage;return this.#$e?"OFF"!==e?.viewState:!this.#We||"OFF"!==t?.printState}_setVisible(t,e,i=!1){t!==we&&x("Internal method `_setVisible` called."),this.#Ge=i,this.#Ve=e}}class xe{#qe=null;#Xe=new Map;#Ke=null;#Ye=null;constructor(t,e=2){if(this.renderingIntent=e,this.name=null,this.creator=null,null!==t){this.name=t.name,this.creator=t.creator,this.#Ye=t.order;for(const i of t.groups)this.#Xe.set(i.id,new _e(e,i));if("OFF"===t.baseState)for(const t of this.#Xe.values())t._setVisible(we,!1);for(const e of t.on)this.#Xe.get(e)._setVisible(we,!0);for(const e of t.off)this.#Xe.get(e)._setVisible(we,!1);this.#Ke=this.getHash()}}#Qe(t){const e=t.length;if(e<2)return!0;const i=t[0];for(let s=1;s0?O(this.#Xe):null}getGroup(t){return this.#Xe.get(t)||null}getHash(){if(null!==this.#qe)return this.#qe;const t=new Ft;for(const[e,i]of this.#Xe)t.update(`${e}:${i.visible}`);return this.#qe=t.hexdigest()}}class Ce{constructor(t,{disableRange:e=!1,disableStream:i=!1}){C(t,'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');const{length:s,initialData:n,progressiveDone:a,contentDispositionFilename:r}=t;if(this._queuedChunks=[],this._progressiveDone=a,this._contentDispositionFilename=r,n?.length>0){const t=n instanceof Uint8Array&&n.byteLength===n.buffer.byteLength?n.buffer:new Uint8Array(n).buffer;this._queuedChunks.push(t)}this._pdfDataRangeTransport=t,this._isStreamingSupported=!i,this._isRangeSupported=!e,this._contentLength=s,this._fullRequestReader=null,this._rangeReaders=[],t.addRangeListener(((t,e)=>{this._onReceiveData({begin:t,chunk:e})})),t.addProgressListener(((t,e)=>{this._onProgress({loaded:t,total:e})})),t.addProgressiveReadListener((t=>{this._onReceiveData({chunk:t})})),t.addProgressiveDoneListener((()=>{this._onProgressiveDone()})),t.transportReady()}_onReceiveData({begin:t,chunk:e}){const i=e instanceof Uint8Array&&e.byteLength===e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer;void 0===t?this._fullRequestReader?this._fullRequestReader._enqueue(i):this._queuedChunks.push(i):C(this._rangeReaders.some((function(e){return e._begin===t&&(e._enqueue(i),!0)})),"_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.")}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}_onProgress(t){void 0===t.total?this._rangeReaders[0]?.onProgress?.({loaded:t.loaded}):this._fullRequestReader?.onProgress?.({loaded:t.loaded,total:t.total})}_onProgressiveDone(){this._fullRequestReader?.progressiveDone(),this._progressiveDone=!0}_removeRangeReader(t){const e=this._rangeReaders.indexOf(t);e>=0&&this._rangeReaders.splice(e,1)}getFullReader(){C(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");const t=this._queuedChunks;return this._queuedChunks=null,new Ee(this,t,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const i=new Se(this,t,e);return this._pdfDataRangeTransport.requestDataRange(t,e),this._rangeReaders.push(i),i}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeReaders.slice(0))e.cancel(t);this._pdfDataRangeTransport.abort()}}class Ee{constructor(t,e,i=!1,s=null){this._stream=t,this._done=i||!1,this._filename=at(s)?s:null,this._queuedChunks=e||[],this._loaded=0;for(const t of this._queuedChunks)this._loaded+=t.byteLength;this._requests=[],this._headersReady=Promise.resolve(),t._fullRequestReader=this,this.onProgress=null}_enqueue(t){this._done||(this._requests.length>0?this._requests.shift().resolve({value:t,done:!1}):this._queuedChunks.push(t),this._loaded+=t.byteLength)}get headersReady(){return this._headersReady}get filename(){return this._filename}get isRangeSupported(){return this._stream._isRangeSupported}get isStreamingSupported(){return this._stream._isStreamingSupported}get contentLength(){return this._stream._contentLength}async read(){if(this._queuedChunks.length>0)return{value:this._queuedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}progressiveDone(){this._done||(this._done=!0)}}class Se{constructor(t,e,i){this._stream=t,this._begin=e,this._end=i,this._queuedChunk=null,this._requests=[],this._done=!1,this.onProgress=null}_enqueue(t){if(!this._done){if(0===this._requests.length)this._queuedChunk=t;else{this._requests.shift().resolve({value:t,done:!1});for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}this._done=!0,this._stream._removeRangeReader(this)}}get isStreamingSupported(){return!1}async read(){if(this._queuedChunk){const t=this._queuedChunk;return this._queuedChunk=null,{value:t,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0,this._stream._removeRangeReader(this)}}function Te(t,e){const i=new Headers;if(!t||!e||"object"!=typeof e)return i;for(const t in e){const s=e[t];void 0!==s&&i.append(t,s)}return i}function Me({responseHeaders:t,isHttp:e,rangeChunkSize:i,disableRange:s}){const n={allowRangeRequests:!1,suggestedLength:void 0},a=parseInt(t.get("Content-Length"),10);return Number.isInteger(a)?(n.suggestedLength=a,a<=2*i||s||!e||"bytes"!==t.get("Accept-Ranges")||"identity"!==(t.get("Content-Encoding")||"identity")||(n.allowRangeRequests=!0),n):n}function ke(t){const e=t.get("Content-Disposition");if(e){let t=function(t){let e=!0,i=s("filename\\*","i").exec(t);if(i){i=i[1];let t=r(i);return t=unescape(t),t=o(t),t=l(t),a(t)}if(i=function(t){const e=[];let i;const n=s("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;null!==(i=n.exec(t));){let[,t,s,n]=i;if(t=parseInt(t,10),t in e){if(0===t)break}else e[t]=[s,n]}const a=[];for(let t=0;t{if(!Pe(e.status))throw Ie(e.status,s);this._reader=e.body.getReader(),this._headersCapability.resolve();const i=e.headers,{allowRangeRequests:n,suggestedLength:a}=Me({responseHeaders:i,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=n,this._contentLength=a||this._contentLength,this._filename=ke(i),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new L("Streaming is disabled."))})).catch(this._headersCapability.reject),this.onProgress=null}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._headersCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:(this._loaded+=t.byteLength,this.onProgress?.({loaded:this._loaded,total:this._contentLength}),{value:De(t),done:!1})}cancel(t){this._reader?.cancel(t),this._abortController.abort()}}class Ne{constructor(t,e,i){this._stream=t,this._reader=null,this._loaded=0;const s=t.source;this._withCredentials=s.withCredentials||!1,this._readCapability=Promise.withResolvers(),this._isStreamingSupported=!s.disableStream,this._abortController=new AbortController;const n=new Headers(t.headers);n.append("Range",`bytes=${e}-${i-1}`);const a=s.url;fetch(a,Re(n,this._withCredentials,this._abortController)).then((t=>{if(!Pe(t.status))throw Ie(t.status,a);this._readCapability.resolve(),this._reader=t.body.getReader()})).catch(this._readCapability.reject),this.onProgress=null}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._readCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:(this._loaded+=t.byteLength,this.onProgress?.({loaded:this._loaded}),{value:De(t),done:!1})}cancel(t){this._reader?.cancel(t),this._abortController.abort()}}class Oe{constructor({url:t,httpHeaders:e,withCredentials:i}){this.url=t,this.isHttp=/^https?:/i.test(t),this.headers=Te(this.isHttp,e),this.withCredentials=i||!1,this.currXhrId=0,this.pendingRequests=Object.create(null)}requestRange(t,e,i){const s={begin:t,end:e};for(const t in i)s[t]=i[t];return this.request(s)}requestFull(t){return this.request(t)}request(t){const e=new XMLHttpRequest,i=this.currXhrId++,s=this.pendingRequests[i]={xhr:e};e.open("GET",this.url),e.withCredentials=this.withCredentials;for(const[t,i]of this.headers)e.setRequestHeader(t,i);return this.isHttp&&"begin"in t&&"end"in t?(e.setRequestHeader("Range",`bytes=${t.begin}-${t.end-1}`),s.expectedStatus=206):s.expectedStatus=200,e.responseType="arraybuffer",t.onError&&(e.onerror=function(i){t.onError(e.status)}),e.onreadystatechange=this.onStateChange.bind(this,i),e.onprogress=this.onProgress.bind(this,i),s.onHeadersReceived=t.onHeadersReceived,s.onDone=t.onDone,s.onError=t.onError,s.onProgress=t.onProgress,e.send(null),i}onProgress(t,e){const i=this.pendingRequests[t];i&&i.onProgress?.(e)}onStateChange(t,e){const i=this.pendingRequests[t];if(!i)return;const s=i.xhr;if(s.readyState>=2&&i.onHeadersReceived&&(i.onHeadersReceived(),delete i.onHeadersReceived),4!==s.readyState)return;if(!(t in this.pendingRequests))return;if(delete this.pendingRequests[t],0===s.status&&this.isHttp)return void i.onError?.(s.status);const n=s.status||200;if((200!==n||206!==i.expectedStatus)&&n!==i.expectedStatus)return void i.onError?.(s.status);const a=function(t){const e=t.response;return"string"!=typeof e?e:N(e).buffer}(s);if(206===n){const t=s.getResponseHeader("Content-Range"),e=/bytes (\d+)-(\d+)\/(\d+)/.exec(t);i.onDone({begin:parseInt(e[1],10),chunk:a})}else a?i.onDone({begin:0,chunk:a}):i.onError?.(s.status)}getRequestXhr(t){return this.pendingRequests[t].xhr}isPendingRequest(t){return t in this.pendingRequests}abortRequest(t){const e=this.pendingRequests[t].xhr;delete this.pendingRequests[t],e.abort()}}class Be{constructor(t){this._source=t,this._manager=new Oe(t),this._rangeChunkSize=t.rangeChunkSize,this._fullRequestReader=null,this._rangeRequestReaders=[]}_onRangeRequestReaderClosed(t){const e=this._rangeRequestReaders.indexOf(t);e>=0&&this._rangeRequestReaders.splice(e,1)}getFullReader(){return C(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once."),this._fullRequestReader=new ze(this._manager,this._source),this._fullRequestReader}getRangeReader(t,e){const i=new He(this._manager,t,e);return i.onClosed=this._onRangeRequestReaderClosed.bind(this),this._rangeRequestReaders.push(i),i}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class ze{constructor(t,e){this._manager=t;const i={onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)};this._url=e.url,this._fullRequestId=t.requestFull(i),this._headersCapability=Promise.withResolvers(),this._disableRange=e.disableRange||!1,this._contentLength=e.length,this._rangeChunkSize=e.rangeChunkSize,this._rangeChunkSize||this._disableRange||(this._disableRange=!0),this._isStreamingSupported=!1,this._isRangeSupported=!1,this._cachedChunks=[],this._requests=[],this._done=!1,this._storedError=void 0,this._filename=null,this.onProgress=null}_onHeadersReceived(){const t=this._fullRequestId,e=this._manager.getRequestXhr(t),i=new Headers(e.getAllResponseHeaders().trim().split(/[\r\n]+/).map((t=>{const[e,...i]=t.split(": ");return[e,i.join(": ")]}))),{allowRangeRequests:s,suggestedLength:n}=Me({responseHeaders:i,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});s&&(this._isRangeSupported=!0),this._contentLength=n||this._contentLength,this._filename=ke(i),this._isRangeSupported&&this._manager.abortRequest(t),this._headersCapability.resolve()}_onDone(t){if(t&&(this._requests.length>0?this._requests.shift().resolve({value:t.chunk,done:!1}):this._cachedChunks.push(t.chunk)),this._done=!0,!(this._cachedChunks.length>0)){for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}}_onError(t){this._storedError=Ie(t,this._url),this._headersCapability.reject(this._storedError);for(const t of this._requests)t.reject(this._storedError);this._requests.length=0,this._cachedChunks.length=0}_onProgress(t){this.onProgress?.({loaded:t.loaded,total:t.lengthComputable?t.total:this._contentLength})}get filename(){return this._filename}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}get contentLength(){return this._contentLength}get headersReady(){return this._headersCapability.promise}async read(){if(this._storedError)throw this._storedError;if(this._cachedChunks.length>0)return{value:this._cachedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0,this._headersCapability.reject(t);for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._fullRequestId)&&this._manager.abortRequest(this._fullRequestId),this._fullRequestReader=null}}class He{constructor(t,e,i){this._manager=t;const s={onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)};this._url=t.url,this._requestId=t.requestRange(e,i,s),this._requests=[],this._queuedChunk=null,this._done=!1,this._storedError=void 0,this.onProgress=null,this.onClosed=null}_close(){this.onClosed?.(this)}_onDone(t){const e=t.chunk;this._requests.length>0?this._requests.shift().resolve({value:e,done:!1}):this._queuedChunk=e,this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0,this._close()}_onError(t){this._storedError=Ie(t,this._url);for(const t of this._requests)t.reject(this._storedError);this._requests.length=0,this._queuedChunk=null}_onProgress(t){this.isStreamingSupported||this.onProgress?.({loaded:t.loaded})}get isStreamingSupported(){return!1}async read(){if(this._storedError)throw this._storedError;if(null!==this._queuedChunk){const t=this._queuedChunk;return this._queuedChunk=null,{value:t,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._requestId)&&this._manager.abortRequest(this._requestId),this._close()}}const je=/^[a-z][a-z0-9\-+.]+:/i;function Ue(t,e,i){return"http:"===t.protocol?$t.get("http").request(t,{headers:e},i):$t.get("https").request(t,{headers:e},i)}class $e{constructor(t){this.source=t,this.url=function(t){if(je.test(t))return new URL(t);const e=$t.get("url");return new URL(e.pathToFileURL(t))}(t.url),this.isHttp="http:"===this.url.protocol||"https:"===this.url.protocol,this.isFsUrl="file:"===this.url.protocol,this.headers=Te(this.isHttp,t.httpHeaders),this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return C(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once."),this._fullRequestReader=this.isFsUrl?new Xe(this):new Ve(this),this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const i=this.isFsUrl?new Ke(this,t,e):new qe(this,t,e);return this._rangeRequestReaders.push(i),i}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class We{constructor(t){this._url=t.url,this._done=!1,this._storedError=null,this.onProgress=null;const e=t.source;this._contentLength=e.length,this._loaded=0,this._filename=null,this._disableRange=e.disableRange||!1,this._rangeChunkSize=e.rangeChunkSize,this._rangeChunkSize||this._disableRange||(this._disableRange=!0),this._isStreamingSupported=!e.disableStream,this._isRangeSupported=!e.disableRange,this._readableStream=null,this._readCapability=Promise.withResolvers(),this._headersCapability=Promise.withResolvers()}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const t=this._readableStream.read();return null===t?(this._readCapability=Promise.withResolvers(),this.read()):(this._loaded+=t.length,this.onProgress?.({loaded:this._loaded,total:this._contentLength}),{value:new Uint8Array(t).buffer,done:!1})}cancel(t){this._readableStream?this._readableStream.destroy(t):this._error(t)}_error(t){this._storedError=t,this._readCapability.resolve()}_setReadableStream(t){this._readableStream=t,t.on("readable",(()=>{this._readCapability.resolve()})),t.on("end",(()=>{t.destroy(),this._done=!0,this._readCapability.resolve()})),t.on("error",(t=>{this._error(t)})),!this._isStreamingSupported&&this._isRangeSupported&&this._error(new L("streaming is disabled")),this._storedError&&this._readableStream.destroy(this._storedError)}}class Ge{constructor(t){this._url=t.url,this._done=!1,this._storedError=null,this.onProgress=null,this._loaded=0,this._readableStream=null,this._readCapability=Promise.withResolvers();const e=t.source;this._isStreamingSupported=!e.disableStream}get isStreamingSupported(){return this._isStreamingSupported}async read(){if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const t=this._readableStream.read();return null===t?(this._readCapability=Promise.withResolvers(),this.read()):(this._loaded+=t.length,this.onProgress?.({loaded:this._loaded}),{value:new Uint8Array(t).buffer,done:!1})}cancel(t){this._readableStream?this._readableStream.destroy(t):this._error(t)}_error(t){this._storedError=t,this._readCapability.resolve()}_setReadableStream(t){this._readableStream=t,t.on("readable",(()=>{this._readCapability.resolve()})),t.on("end",(()=>{t.destroy(),this._done=!0,this._readCapability.resolve()})),t.on("error",(t=>{this._error(t)})),this._storedError&&this._readableStream.destroy(this._storedError)}}class Ve extends We{constructor(t){super(t);const e=Object.fromEntries(t.headers);this._request=Ue(this._url,e,(e=>{if(404===e.statusCode){const t=new P(`Missing PDF "${this._url}".`);return this._storedError=t,void this._headersCapability.reject(t)}this._headersCapability.resolve(),this._setReadableStream(e);const i=new Headers(this._readableStream.headers),{allowRangeRequests:s,suggestedLength:n}=Me({responseHeaders:i,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=s,this._contentLength=n||this._contentLength,this._filename=ke(i)})),this._request.on("error",(t=>{this._storedError=t,this._headersCapability.reject(t)})),this._request.end()}}class qe extends Ge{constructor(t,e,i){super(t);const s=Object.fromEntries(t.headers);s.Range=`bytes=${e}-${i-1}`,this._request=Ue(this._url,s,(t=>{if(404!==t.statusCode)this._setReadableStream(t);else{const t=new P(`Missing PDF "${this._url}".`);this._storedError=t}})),this._request.on("error",(t=>{this._storedError=t})),this._request.end()}}class Xe extends We{constructor(t){super(t);const e=$t.get("fs");e.promises.lstat(this._url).then((t=>{this._contentLength=t.size,this._setReadableStream(e.createReadStream(this._url)),this._headersCapability.resolve()}),(t=>{"ENOENT"===t.code&&(t=new P(`Missing PDF "${this._url}".`)),this._storedError=t,this._headersCapability.reject(t)}))}}class Ke extends Ge{constructor(t,e,i){super(t);const s=$t.get("fs");this._setReadableStream(s.createReadStream(this._url,{start:e,end:i-1}))}}const Ye=30;class Qe{#Je=Promise.withResolvers();#ut=null;#Ze=!1;#ti=!!globalThis.FontInspector?.enabled;#ei=null;#ii=null;#si=0;#ni=0;#ai=null;#ri=null;#oi=0;#li=0;#hi=Object.create(null);#di=[];#ci=null;#ui=[];#pi=new WeakMap;#gi=null;static#mi=new Map;static#fi=new Map;static#bi=new WeakMap;static#vi=null;static#Ai=new Set;constructor({textContentSource:t,container:e,viewport:i}){if(t instanceof ReadableStream)this.#ci=t;else{if("object"!=typeof t)throw new Error('No "textContentSource" parameter specified.');this.#ci=new ReadableStream({start(e){e.enqueue(t),e.close()}})}this.#ut=this.#ri=e,this.#li=i.scale*(globalThis.devicePixelRatio||1),this.#oi=i.rotation,this.#ii={div:null,properties:null,ctx:null};const{pageWidth:s,pageHeight:n,pageX:a,pageY:r}=i.rawDims;this.#gi=[1,0,0,-1,-a,r+n],this.#ni=s,this.#si=n,Qe.#yi(),vt(e,i),this.#Je.promise.finally((()=>{Qe.#Ai.delete(this),this.#ii=null,this.#hi=null})).catch((()=>{}))}static get fontFamilyMap(){const{isWindows:t,isFirefox:e}=B.platform;return S(this,"fontFamilyMap",new Map([["sans-serif",(t&&e?"Calibri, ":"")+"sans-serif"],["monospace",(t&&e?"Lucida Console, ":"")+"monospace"]]))}render(){const t=()=>{this.#ai.read().then((({value:e,done:i})=>{i?this.#Je.resolve():(this.#ei??=e.lang,Object.assign(this.#hi,e.styles),this.#wi(e.items),t())}),this.#Je.reject)};return this.#ai=this.#ci.getReader(),Qe.#Ai.add(this),t(),this.#Je.promise}update({viewport:t,onBefore:e=null}){const i=t.scale*(globalThis.devicePixelRatio||1),s=t.rotation;if(s!==this.#oi&&(e?.(),this.#oi=s,vt(this.#ri,{rotation:s})),i!==this.#li){e?.(),this.#li=i;const t={div:null,properties:null,ctx:Qe.#_i(this.#ei)};for(const e of this.#ui)t.properties=this.#pi.get(e),t.div=e,this.#xi(t)}}cancel(){const t=new L("TextLayer task cancelled.");this.#ai?.cancel(t).catch((()=>{})),this.#ai=null,this.#Je.reject(t)}get textDivs(){return this.#ui}get textContentItemsStr(){return this.#di}#wi(t){if(this.#Ze)return;this.#ii.ctx??=Qe.#_i(this.#ei);const e=this.#ui,i=this.#di;for(const s of t){if(e.length>1e5)return _("Ignoring additional textDivs for performance reasons."),void(this.#Ze=!0);if(void 0!==s.str)i.push(s.str),this.#Ci(s);else if("beginMarkedContentProps"===s.type||"beginMarkedContent"===s.type){const t=this.#ut;this.#ut=document.createElement("span"),this.#ut.classList.add("markedContent"),null!==s.id&&this.#ut.setAttribute("id",`${s.id}`),t.append(this.#ut)}else"endMarkedContent"===s.type&&(this.#ut=this.#ut.parentNode)}}#Ci(t){const e=document.createElement("span"),i={angle:0,canvasWidth:0,hasText:""!==t.str,hasEOL:t.hasEOL,fontSize:0};this.#ui.push(e);const s=H.transform(this.#gi,t.transform);let n=Math.atan2(s[1],s[0]);const a=this.#hi[t.fontName];a.vertical&&(n+=Math.PI/2);let r=this.#ti&&a.fontSubstitution||a.fontFamily;r=Qe.fontFamilyMap.get(r)||r;const o=Math.hypot(s[2],s[3]),l=o*Qe.#Ei(r,this.#ei);let h,d;0===n?(h=s[4],d=s[5]-l):(h=s[4]+l*Math.sin(n),d=s[5]-l*Math.cos(n));const c="calc(var(--scale-factor)*",u=e.style;this.#ut===this.#ri?(u.left=`${(100*h/this.#ni).toFixed(2)}%`,u.top=`${(100*d/this.#si).toFixed(2)}%`):(u.left=`${c}${h.toFixed(2)}px)`,u.top=`${c}${d.toFixed(2)}px)`),u.fontSize=`${c}${(Qe.#vi*o).toFixed(2)}px)`,u.fontFamily=r,i.fontSize=o,e.setAttribute("role","presentation"),e.textContent=t.str,e.dir=t.dir,this.#ti&&(e.dataset.fontName=a.fontSubstitutionLoadedName||t.fontName),0!==n&&(i.angle=n*(180/Math.PI));let p=!1;if(t.str.length>1)p=!0;else if(" "!==t.str&&t.transform[0]!==t.transform[3]){const e=Math.abs(t.transform[0]),i=Math.abs(t.transform[3]);e!==i&&Math.max(e,i)/Math.min(e,i)>1.5&&(p=!0)}if(p&&(i.canvasWidth=a.vertical?t.height:t.width),this.#pi.set(e,i),this.#ii.div=e,this.#ii.properties=i,this.#xi(this.#ii),i.hasText&&this.#ut.append(e),i.hasEOL){const t=document.createElement("br");t.setAttribute("role","presentation"),this.#ut.append(t)}}#xi(t){const{div:e,properties:i,ctx:s}=t,{style:n}=e;let a="";if(Qe.#vi>1&&(a=`scale(${1/Qe.#vi})`),0!==i.canvasWidth&&i.hasText){const{fontFamily:t}=n,{canvasWidth:r,fontSize:o}=i;Qe.#Si(s,o*this.#li,t);const{width:l}=s.measureText(e.textContent);l>0&&(a=`scaleX(${r*this.#li/l}) ${a}`)}0!==i.angle&&(a=`rotate(${i.angle}deg) ${a}`),a.length>0&&(n.transform=a)}static cleanup(){if(!(this.#Ai.size>0)){this.#mi.clear();for(const{canvas:t}of this.#fi.values())t.remove();this.#fi.clear()}}static#_i(t=null){let e=this.#fi.get(t||="");if(!e){const i=document.createElement("canvas");i.className="hiddenCanvasElement",i.lang=t,document.body.append(i),e=i.getContext("2d",{alpha:!1,willReadFrequently:!0}),this.#fi.set(t,e),this.#bi.set(e,{size:0,family:""})}return e}static#Si(t,e,i){const s=this.#bi.get(t);e===s.size&&i===s.family||(t.font=`${e}px ${i}`,s.size=e,s.family=i)}static#yi(){if(null!==this.#vi)return;const t=document.createElement("div");t.style.opacity=0,t.style.lineHeight=1,t.style.fontSize="1px",t.style.position="absolute",t.textContent="X",document.body.append(t),this.#vi=t.getBoundingClientRect().height,t.remove()}static#Ei(t,e){const i=this.#mi.get(t);if(i)return i;const s=this.#_i(e);s.canvas.width=s.canvas.height=Ye,this.#Si(s,Ye,t);const n=s.measureText("");let a=n.fontBoundingBoxAscent,r=Math.abs(n.fontBoundingBoxDescent);if(a){const e=a/(a+r);return this.#mi.set(t,e),s.canvas.width=s.canvas.height=0,e}s.strokeStyle="red",s.clearRect(0,0,Ye,Ye),s.strokeText("g",0,0);let o=s.getImageData(0,0,Ye,Ye).data;r=0;for(let t=o.length-1-3;t>=0;t-=4)if(o[t]>0){r=Math.ceil(t/4/Ye);break}s.clearRect(0,0,Ye,Ye),s.strokeText("A",0,Ye),o=s.getImageData(0,0,Ye,Ye).data,a=0;for(let t=0,e=o.length;t0){a=Ye-Math.floor(t/4/Ye);break}s.canvas.width=s.canvas.height=0;const l=a?a/(a+r):.8;return this.#mi.set(t,l),l}}class Je{static textContent(t){const e=[],i={items:e,styles:Object.create(null)};return function t(i){if(!i)return;let s=null;const n=i.name;if("#text"===n)s=i.value;else{if(!Je.shouldBuildText(n))return;i?.attributes?.textContent?s=i.attributes.textContent:i.value&&(s=i.value)}if(null!==s&&e.push({str:s}),i.children)for(const e of i.children)t(e)}(t),i}static shouldBuildText(t){return!("textarea"===t||"input"===t||"option"===t||"select"===t)}}const Ze=65536,ti=a?class extends V{_createCanvas(t,e){return $t.get("canvas").createCanvas(t,e)}}:class extends V{constructor({ownerDocument:t=globalThis.document,enableHWA:e=!1}){super({enableHWA:e}),this._document=t}_createCanvas(t,e){const i=this._document.createElement("canvas");return i.width=t,i.height=e,i}},ei=a?class extends q{_fetchData(t,e){return Wt(t).then((t=>({cMapData:t,compressionType:e})))}}:Z,ii=a?class extends G{}:class extends G{#Ti;#Mi;#ki;#Ii;#Pi;#Ri;#A=0;constructor({docId:t,ownerDocument:e=globalThis.document}){super(),this.#Ii=t,this.#Pi=e}get#w(){return this.#Mi||=new Map}get#Di(){return this.#Ri||=new Map}get#Li(){if(!this.#ki){const t=this.#Pi.createElement("div"),{style:e}=t;e.visibility="hidden",e.contain="strict",e.width=e.height=0,e.position="absolute",e.top=e.left=0,e.zIndex=-1;const i=this.#Pi.createElementNS(Y,"svg");i.setAttribute("width",0),i.setAttribute("height",0),this.#ki=this.#Pi.createElementNS(Y,"defs"),t.append(i),i.append(this.#ki),this.#Pi.body.append(t)}return this.#ki}#Fi(t){if(1===t.length){const e=t[0],i=new Array(256);for(let t=0;t<256;t++)i[t]=e[t]/255;const s=i.join(",");return[s,s,s]}const[e,i,s]=t,n=new Array(256),a=new Array(256),r=new Array(256);for(let t=0;t<256;t++)n[t]=e[t]/255,a[t]=i[t]/255,r[t]=s[t]/255;return[n.join(","),a.join(","),r.join(",")]}#Ni(t){if(void 0===this.#Ti){this.#Ti="";const t=this.#Pi.URL;t!==this.#Pi.baseURI&&(nt(t)?_('#createUrl: ignore "data:"-URL for performance reasons.'):this.#Ti=t.split("#",1)[0])}return`url(${this.#Ti}#${t})`}addFilter(t){if(!t)return"none";let e=this.#w.get(t);if(e)return e;const[i,s,n]=this.#Fi(t),a=1===t.length?i:`${i}${s}${n}`;if(e=this.#w.get(a),e)return this.#w.set(t,e),e;const r=`g_${this.#Ii}_transfer_map_${this.#A++}`,o=this.#Ni(r);this.#w.set(t,o),this.#w.set(a,o);const l=this.#Oi(r);return this.#Bi(i,s,n,l),o}addHCMFilter(t,e){const i=`${t}-${e}`,s="base";let n=this.#Di.get(s);if(n?.key===i)return n.url;if(n?(n.filter?.remove(),n.key=i,n.url="none",n.filter=null):(n={key:i,url:"none",filter:null},this.#Di.set(s,n)),!t||!e)return n.url;const a=this.#zi(t);t=H.makeHexColor(...a);const r=this.#zi(e);if(e=H.makeHexColor(...r),this.#Li.style.color="","#000000"===t&&"#ffffff"===e||t===e)return n.url;const o=new Array(256);for(let t=0;t<=255;t++){const e=t/255;o[t]=e<=.03928?e/12.92:((e+.055)/1.055)**2.4}const l=o.join(","),h=`g_${this.#Ii}_hcm_filter`,d=n.filter=this.#Oi(h);this.#Bi(l,l,l,d),this.#Hi(d);const c=(t,e)=>{const i=a[t]/255,s=r[t]/255,n=new Array(e+1);for(let t=0;t<=e;t++)n[t]=i+t/e*(s-i);return n.join(",")};return this.#Bi(c(0,5),c(1,5),c(2,5),d),n.url=this.#Ni(h),n.url}addAlphaFilter(t){let e=this.#w.get(t);if(e)return e;const[i]=this.#Fi([t]),s=`alpha_${i}`;if(e=this.#w.get(s),e)return this.#w.set(t,e),e;const n=`g_${this.#Ii}_alpha_map_${this.#A++}`,a=this.#Ni(n);this.#w.set(t,a),this.#w.set(s,a);const r=this.#Oi(n);return this.#ji(i,r),a}addLuminosityFilter(t){let e,i,s=this.#w.get(t||"luminosity");if(s)return s;if(t?([e]=this.#Fi([t]),i=`luminosity_${e}`):i="luminosity",s=this.#w.get(i),s)return this.#w.set(t,s),s;const n=`g_${this.#Ii}_luminosity_map_${this.#A++}`,a=this.#Ni(n);this.#w.set(t,a),this.#w.set(i,a);const r=this.#Oi(n);return this.#Ui(r),t&&this.#ji(e,r),a}addHighlightHCMFilter(t,e,i,s,n){const a=`${e}-${i}-${s}-${n}`;let r=this.#Di.get(t);if(r?.key===a)return r.url;if(r?(r.filter?.remove(),r.key=a,r.url="none",r.filter=null):(r={key:a,url:"none",filter:null},this.#Di.set(t,r)),!e||!i)return r.url;const[o,l]=[e,i].map(this.#zi.bind(this));let h=Math.round(.2126*o[0]+.7152*o[1]+.0722*o[2]),d=Math.round(.2126*l[0]+.7152*l[1]+.0722*l[2]),[c,u]=[s,n].map(this.#zi.bind(this));d{const s=new Array(256),n=(d-h)/i,a=t/255,r=(e-t)/(255*i);let o=0;for(let t=0;t<=i;t++){const e=Math.round(h+t*n),i=a+t*r;for(let t=o;t<=e;t++)s[t]=i;o=e+1}for(let t=o;t<256;t++)s[t]=s[o-1];return s.join(",")},g=`g_${this.#Ii}_hcm_${t}_filter`,m=r.filter=this.#Oi(g);return this.#Hi(m),this.#Bi(p(c[0],u[0],5),p(c[1],u[1],5),p(c[2],u[2],5),m),r.url=this.#Ni(g),r.url}destroy(t=!1){t&&0!==this.#Di.size||(this.#ki&&(this.#ki.parentNode.parentNode.remove(),this.#ki=null),this.#Mi&&(this.#Mi.clear(),this.#Mi=null),this.#A=0)}#Ui(t){const e=this.#Pi.createElementNS(Y,"feColorMatrix");e.setAttribute("type","matrix"),e.setAttribute("values","0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0.59 0.11 0 0"),t.append(e)}#Hi(t){const e=this.#Pi.createElementNS(Y,"feColorMatrix");e.setAttribute("type","matrix"),e.setAttribute("values","0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0"),t.append(e)}#Oi(t){const e=this.#Pi.createElementNS(Y,"filter");return e.setAttribute("color-interpolation-filters","sRGB"),e.setAttribute("id",t),this.#Li.append(e),e}#$i(t,e,i){const s=this.#Pi.createElementNS(Y,e);s.setAttribute("type","discrete"),s.setAttribute("tableValues",i),t.append(s)}#Bi(t,e,i,s){const n=this.#Pi.createElementNS(Y,"feComponentTransfer");s.append(n),this.#$i(n,"feFuncR",t),this.#$i(n,"feFuncG",e),this.#$i(n,"feFuncB",i)}#ji(t,e){const i=this.#Pi.createElementNS(Y,"feComponentTransfer");e.append(i),this.#$i(i,"feFuncA",t)}#zi(t){return this.#Li.style.color=t,mt(getComputedStyle(this.#Li).getPropertyValue("color"))}},si=a?class extends X{_fetchData(t){return Wt(t)}}:tt;function ni(t={}){"string"==typeof t||t instanceof URL?t={url:t}:(t instanceof ArrayBuffer||ArrayBuffer.isView(t))&&(t={data:t});const e=new ri,{docId:i}=e,s=t.url?function(t){if(t instanceof URL)return t.href;try{return new URL(t,window.location).href}catch{if(a&&"string"==typeof t)return t}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}(t.url):null,n=t.data?function(t){if(a&&"undefined"!=typeof Buffer&&t instanceof Buffer)throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");if(t instanceof Uint8Array&&t.byteLength===t.buffer.byteLength)return t;if("string"==typeof t)return N(t);if(t instanceof ArrayBuffer||ArrayBuffer.isView(t)||"object"==typeof t&&!isNaN(t?.length))return new Uint8Array(t);throw new Error("Invalid PDF binary data: either TypedArray, string, or array-like object is expected in the data property.")}(t.data):null,r=t.httpHeaders||null,o=!0===t.withCredentials,l=t.password??null,h=t.range instanceof oi?t.range:null,d=Number.isInteger(t.rangeChunkSize)&&t.rangeChunkSize>0?t.rangeChunkSize:Ze;let c=t.worker instanceof ci?t.worker:null;const u=t.verbosity,p="string"!=typeof t.docBaseUrl||nt(t.docBaseUrl)?null:t.docBaseUrl,g="string"==typeof t.cMapUrl?t.cMapUrl:null,m=!1!==t.cMapPacked,f=t.CMapReaderFactory||ei,b="string"==typeof t.standardFontDataUrl?t.standardFontDataUrl:null,v=t.StandardFontDataFactory||si,y=!0!==t.stopAtErrors,w=Number.isInteger(t.maxImageSize)&&t.maxImageSize>-1?t.maxImageSize:-1,_=!1!==t.isEvalSupported,x="boolean"==typeof t.isOffscreenCanvasSupported?t.isOffscreenCanvasSupported:!a,C=Number.isInteger(t.canvasMaxAreaInBytes)?t.canvasMaxAreaInBytes:-1,E="boolean"==typeof t.disableFontFace?t.disableFontFace:a,S=!0===t.fontExtraProperties,T=!0===t.enableXfa,M=t.ownerDocument||globalThis.document,k=!0===t.disableRange,I=!0===t.disableStream,P=!0===t.disableAutoFetch,R=!0===t.pdfBug,D=t.CanvasFactory||ti,L=t.FilterFactory||ii,F=!0===t.enableHWA,O=h?h.length:t.length??NaN,B="boolean"==typeof t.useSystemFonts?t.useSystemFonts:!a&&!E,z="boolean"==typeof t.useWorkerFetch?t.useWorkerFetch:f===Z&&v===tt&&g&&b&&ht(g,document.baseURI)&&ht(b,document.baseURI);t.canvasFactory&&ct("`canvasFactory`-instance option, please use `CanvasFactory` instead."),t.filterFactory&&ct("`filterFactory`-instance option, please use `FilterFactory` instead."),A(u);const H={canvasFactory:new D({ownerDocument:M,enableHWA:F}),filterFactory:new L({docId:i,ownerDocument:M}),cMapReaderFactory:z?null:new f({baseUrl:g,isCompressed:m}),standardFontDataFactory:z?null:new v({baseUrl:b})};if(!c){const t={verbosity:u,port:be.workerPort};c=t.port?ci.fromPort(t):new ci(t),e._worker=c}const j={docId:i,apiVersion:"4.7.76",data:n,password:l,disableAutoFetch:P,rangeChunkSize:d,length:O,docBaseUrl:p,enableXfa:T,evaluatorOptions:{maxImageSize:w,disableFontFace:E,ignoreErrors:y,isEvalSupported:_,isOffscreenCanvasSupported:x,canvasMaxAreaInBytes:C,fontExtraProperties:S,useSystemFonts:B,cMapUrl:z?g:null,standardFontDataUrl:z?b:null}},U={disableFontFace:E,fontExtraProperties:S,ownerDocument:M,pdfBug:R,styleElement:null,loadingParams:{disableAutoFetch:P,enableXfa:T}};return c.promise.then((function(){if(e.destroyed)throw new Error("Loading aborted");if(c.destroyed)throw new Error("Worker was destroyed");const t=c.messageHandler.sendWithPromise("GetDocRequest",j,n?[n.buffer]:null);let l;if(h)l=new Ce(h,{disableRange:k,disableStream:I});else if(!n){if(!s)throw new Error("getDocument - no `url` parameter provided.");let t;t=a?"undefined"!=typeof fetch&&"undefined"!=typeof Response&&"body"in Response.prototype&&ht(s)?Le:$e:ht(s)?Le:Be,l=new t({url:s,length:O,httpHeaders:r,withCredentials:o,rangeChunkSize:d,disableRange:k,disableStream:I})}return t.then((t=>{if(e.destroyed)throw new Error("Loading aborted");if(c.destroyed)throw new Error("Worker was destroyed");const s=new Ae(i,t,c.port),n=new ui(s,e,l,U,H);e._transport=n,s.send("Ready",null)}))})).catch(e._capability.reject),e}function ai(t){return"object"==typeof t&&Number.isInteger(t?.num)&&t.num>=0&&Number.isInteger(t?.gen)&&t.gen>=0}class ri{static#Ii=0;constructor(){this._capability=Promise.withResolvers(),this._transport=null,this._worker=null,this.docId="d"+ri.#Ii++,this.destroyed=!1,this.onPassword=null,this.onProgress=null}get promise(){return this._capability.promise}async destroy(){this.destroyed=!0;try{this._worker?.port&&(this._worker._pendingDestroy=!0),await(this._transport?.destroy())}catch(t){throw this._worker?.port&&delete this._worker._pendingDestroy,t}this._transport=null,this._worker&&(this._worker.destroy(),this._worker=null)}}class oi{constructor(t,e,i=!1,s=null){this.length=t,this.initialData=e,this.progressiveDone=i,this.contentDispositionFilename=s,this._rangeListeners=[],this._progressListeners=[],this._progressiveReadListeners=[],this._progressiveDoneListeners=[],this._readyCapability=Promise.withResolvers()}addRangeListener(t){this._rangeListeners.push(t)}addProgressListener(t){this._progressListeners.push(t)}addProgressiveReadListener(t){this._progressiveReadListeners.push(t)}addProgressiveDoneListener(t){this._progressiveDoneListeners.push(t)}onDataRange(t,e){for(const i of this._rangeListeners)i(t,e)}onDataProgress(t,e){this._readyCapability.promise.then((()=>{for(const i of this._progressListeners)i(t,e)}))}onDataProgressiveRead(t){this._readyCapability.promise.then((()=>{for(const e of this._progressiveReadListeners)e(t)}))}onDataProgressiveDone(){this._readyCapability.promise.then((()=>{for(const t of this._progressiveDoneListeners)t()}))}transportReady(){this._readyCapability.resolve()}requestDataRange(t,e){x("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class li{constructor(t,e){this._pdfInfo=t,this._transport=e}get annotationStorage(){return this._transport.annotationStorage}get canvasFactory(){return this._transport.canvasFactory}get filterFactory(){return this._transport.filterFactory}get numPages(){return this._pdfInfo.numPages}get fingerprints(){return this._pdfInfo.fingerprints}get isPureXfa(){return S(this,"isPureXfa",!!this._transport._htmlForXfa)}get allXfaHtml(){return this._transport._htmlForXfa}getPage(t){return this._transport.getPage(t)}getPageIndex(t){return this._transport.getPageIndex(t)}getDestinations(){return this._transport.getDestinations()}getDestination(t){return this._transport.getDestination(t)}getPageLabels(){return this._transport.getPageLabels()}getPageLayout(){return this._transport.getPageLayout()}getPageMode(){return this._transport.getPageMode()}getViewerPreferences(){return this._transport.getViewerPreferences()}getOpenAction(){return this._transport.getOpenAction()}getAttachments(){return this._transport.getAttachments()}getJSActions(){return this._transport.getDocJSActions()}getOutline(){return this._transport.getOutline()}getOptionalContentConfig({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getOptionalContentConfig(e)}getPermissions(){return this._transport.getPermissions()}getMetadata(){return this._transport.getMetadata()}getMarkInfo(){return this._transport.getMarkInfo()}getData(){return this._transport.getData()}saveDocument(){return this._transport.saveDocument()}getDownloadInfo(){return this._transport.downloadInfoCapability.promise}cleanup(t=!1){return this._transport.startCleanup(t||this.isPureXfa)}destroy(){return this.loadingTask.destroy()}cachedPageNumber(t){return this._transport.cachedPageNumber(t)}get loadingParams(){return this._transport.loadingParams}get loadingTask(){return this._transport.loadingTask}getFieldObjects(){return this._transport.getFieldObjects()}hasJSActions(){return this._transport.hasJSActions()}getCalculationOrderIds(){return this._transport.getCalculationOrderIds()}}class hi{#Wi=null;#Gi=!1;constructor(t,e,i,s=!1){this._pageIndex=t,this._pageInfo=e,this._transport=i,this._stats=s?new lt:null,this._pdfBug=s,this.commonObjs=i.commonObjs,this.objs=new gi,this._maybeCleanupAfterRender=!1,this._intentStates=new Map,this.destroyed=!1}get pageNumber(){return this._pageIndex+1}get rotate(){return this._pageInfo.rotate}get ref(){return this._pageInfo.ref}get userUnit(){return this._pageInfo.userUnit}get view(){return this._pageInfo.view}getViewport({scale:t,rotation:e=this.rotate,offsetX:i=0,offsetY:s=0,dontFlip:n=!1}={}){return new it({viewBox:this.view,scale:t,rotation:e,offsetX:i,offsetY:s,dontFlip:n})}getAnnotations({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getAnnotations(this._pageIndex,e)}getJSActions(){return this._transport.getPageJSActions(this._pageIndex)}get filterFactory(){return this._transport.filterFactory}get isPureXfa(){return S(this,"isPureXfa",!!this._transport._htmlForXfa)}async getXfa(){return this._transport._htmlForXfa?.children[this._pageIndex]||null}render({canvasContext:t,viewport:e,intent:i="display",annotationMode:s=h.ENABLE,transform:n=null,background:a=null,optionalContentConfigPromise:r=null,annotationCanvasMap:o=null,pageColors:l=null,printAnnotationStorage:d=null,isEditing:c=!1}){this._stats?.time("Overall");const u=this._transport.getRenderingIntent(i,s,d,c),{renderingIntent:p,cacheKey:g}=u;this.#Gi=!1,this.#Vi(),r||=this._transport.getOptionalContentConfig(p);let m=this._intentStates.get(g);m||(m=Object.create(null),this._intentStates.set(g,m)),m.streamReaderCancelTimeout&&(clearTimeout(m.streamReaderCancelTimeout),m.streamReaderCancelTimeout=null);const f=!!(4&p);m.displayReadyCapability||(m.displayReadyCapability=Promise.withResolvers(),m.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(u));const b=t=>{m.renderTasks.delete(v),(this._maybeCleanupAfterRender||f)&&(this.#Gi=!0),this.#qi(!f),t?(v.capability.reject(t),this._abortOperatorList({intentState:m,reason:t instanceof Error?t:new Error(t)})):v.capability.resolve(),this._stats&&(this._stats.timeEnd("Rendering"),this._stats.timeEnd("Overall"),globalThis.Stats?.enabled&&globalThis.Stats.add(this.pageNumber,this._stats))},v=new fi({callback:b,params:{canvasContext:t,viewport:e,transform:n,background:a},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:o,operatorList:m.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!f,pdfBug:this._pdfBug,pageColors:l});(m.renderTasks||=new Set).add(v);const A=v.task;return Promise.all([m.displayReadyCapability.promise,r]).then((([t,e])=>{if(this.destroyed)b();else{if(this._stats?.time("Rendering"),!(e.renderingIntent&p))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");v.initializeGraphics({transparency:t,optionalContentConfig:e}),v.operatorListChanged()}})).catch(b),A}getOperatorList({intent:t="display",annotationMode:e=h.ENABLE,printAnnotationStorage:i=null,isEditing:s=!1}={}){const n=this._transport.getRenderingIntent(t,e,i,s,!0);let a,r=this._intentStates.get(n.cacheKey);return r||(r=Object.create(null),this._intentStates.set(n.cacheKey,r)),r.opListReadCapability||(a=Object.create(null),a.operatorListChanged=function(){r.operatorList.lastChunk&&(r.opListReadCapability.resolve(r.operatorList),r.renderTasks.delete(a))},r.opListReadCapability=Promise.withResolvers(),(r.renderTasks||=new Set).add(a),r.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(n)),r.opListReadCapability.promise}streamTextContent({includeMarkedContent:t=!1,disableNormalization:e=!1}={}){return this._transport.messageHandler.sendWithStream("GetTextContent",{pageIndex:this._pageIndex,includeMarkedContent:!0===t,disableNormalization:!0===e},{highWaterMark:100,size:t=>t.items.length})}getTextContent(t={}){if(this._transport._htmlForXfa)return this.getXfa().then((t=>Je.textContent(t)));const e=this.streamTextContent(t);return new Promise((function(t,i){const s=e.getReader(),n={items:[],styles:Object.create(null),lang:null};!function e(){s.read().then((function({value:i,done:s}){s?t(n):(n.lang??=i.lang,Object.assign(n.styles,i.styles),n.items.push(...i.items),e())}),i)}()}))}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;const t=[];for(const e of this._intentStates.values())if(this._abortOperatorList({intentState:e,reason:new Error("Page was destroyed."),force:!0}),!e.opListReadCapability)for(const i of e.renderTasks)t.push(i.completed),i.cancel();return this.objs.clear(),this.#Gi=!1,this.#Vi(),Promise.all(t)}cleanup(t=!1){this.#Gi=!0;const e=this.#qi(!1);return t&&e&&(this._stats&&=new lt),e}#qi(t=!1){if(this.#Vi(),!this.#Gi||this.destroyed)return!1;if(t)return this.#Wi=setTimeout((()=>{this.#Wi=null,this.#qi(!1)}),5e3),!1;for(const{renderTasks:t,operatorList:e}of this._intentStates.values())if(t.size>0||!e.lastChunk)return!1;return this._intentStates.clear(),this.objs.clear(),this.#Gi=!1,!0}#Vi(){this.#Wi&&(clearTimeout(this.#Wi),this.#Wi=null)}_startRenderPage(t,e){const i=this._intentStates.get(e);i&&(this._stats?.timeEnd("Page Request"),i.displayReadyCapability?.resolve(t))}_renderPageChunk(t,e){for(let i=0,s=t.length;i{r.read().then((({value:t,done:e})=>{e?o.streamReader=null:this._transport.destroyed||(this._renderPageChunk(t,o),l())}),(t=>{if(o.streamReader=null,!this._transport.destroyed){if(o.operatorList){o.operatorList.lastChunk=!0;for(const t of o.renderTasks)t.operatorListChanged();this.#qi(!0)}if(o.displayReadyCapability)o.displayReadyCapability.reject(t);else{if(!o.opListReadCapability)throw t;o.opListReadCapability.reject(t)}}}))};l()}_abortOperatorList({intentState:t,reason:e,force:i=!1}){if(t.streamReader){if(t.streamReaderCancelTimeout&&(clearTimeout(t.streamReaderCancelTimeout),t.streamReaderCancelTimeout=null),!i){if(t.renderTasks.size>0)return;if(e instanceof st){let i=100;return e.extraDelay>0&&e.extraDelay<1e3&&(i+=e.extraDelay),void(t.streamReaderCancelTimeout=setTimeout((()=>{t.streamReaderCancelTimeout=null,this._abortOperatorList({intentState:t,reason:e,force:!0})}),i))}}if(t.streamReader.cancel(new L(e.message)).catch((()=>{})),t.streamReader=null,!this._transport.destroyed){for(const[e,i]of this._intentStates)if(i===t){this._intentStates.delete(e);break}this.cleanup()}}}get stats(){return this._stats}}class di{#Xi=new Set;#Ki=Promise.resolve();postMessage(t,e){const i={data:structuredClone(t,e?{transfer:e}:null)};this.#Ki.then((()=>{for(const t of this.#Xi)t.call(this,i)}))}addEventListener(t,e){this.#Xi.add(e)}removeEventListener(t,e){this.#Xi.delete(e)}terminate(){this.#Xi.clear()}}class ci{static#Yi=0;static#Qi=!1;static#Ji;static{a&&(this.#Qi=!0,be.workerSrc||="./pdf.worker.mjs"),this._isSameOrigin=(t,e)=>{let i;try{if(i=new URL(t),!i.origin||"null"===i.origin)return!1}catch{return!1}const s=new URL(e,i);return i.origin===s.origin},this._createCDNWrapper=t=>{const e=`await import("${t}");`;return URL.createObjectURL(new Blob([e],{type:"text/javascript"}))}}constructor({name:t=null,port:e=null,verbosity:i=y()}={}){if(this.name=t,this.destroyed=!1,this.verbosity=i,this._readyCapability=Promise.withResolvers(),this._port=null,this._webWorker=null,this._messageHandler=null,e){if(ci.#Ji?.has(e))throw new Error("Cannot use more than one PDFWorker per port.");return(ci.#Ji||=new WeakMap).set(e,this),void this._initializeFromPort(e)}this._initialize()}get promise(){return a?Promise.all([$t.promise,this._readyCapability.promise]):this._readyCapability.promise}#Zi(){this._readyCapability.resolve(),this._messageHandler.send("configure",{verbosity:this.verbosity})}get port(){return this._port}get messageHandler(){return this._messageHandler}_initializeFromPort(t){this._port=t,this._messageHandler=new Ae("main","worker",t),this._messageHandler.on("ready",(function(){})),this.#Zi()}_initialize(){if(ci.#Qi||ci.#ts)return void this._setupFakeWorker();let{workerSrc:t}=ci;try{ci._isSameOrigin(window.location.href,t)||(t=ci._createCDNWrapper(new URL(t,window.location).href));const e=new Worker(t,{type:"module"}),i=new Ae("main","worker",e),s=()=>{n.abort(),i.destroy(),e.terminate(),this.destroyed?this._readyCapability.reject(new Error("Worker was destroyed")):this._setupFakeWorker()},n=new AbortController;e.addEventListener("error",(()=>{this._webWorker||s()}),{signal:n.signal}),i.on("test",(t=>{n.abort(),!this.destroyed&&t?(this._messageHandler=i,this._port=e,this._webWorker=e,this.#Zi()):s()})),i.on("ready",(t=>{if(n.abort(),this.destroyed)s();else try{a()}catch{this._setupFakeWorker()}}));const a=()=>{const t=new Uint8Array;i.send("test",t,[t.buffer])};return void a()}catch{w("The worker has been disabled.")}this._setupFakeWorker()}_setupFakeWorker(){ci.#Qi||(_("Setting up fake worker."),ci.#Qi=!0),ci._setupFakeWorkerGlobal.then((t=>{if(this.destroyed)return void this._readyCapability.reject(new Error("Worker was destroyed"));const e=new di;this._port=e;const i="fake"+ci.#Yi++,s=new Ae(i+"_worker",i,e);t.setup(s,e),this._messageHandler=new Ae(i,i+"_worker",e),this.#Zi()})).catch((t=>{this._readyCapability.reject(new Error(`Setting up fake worker failed: "${t.message}".`))}))}destroy(){this.destroyed=!0,this._webWorker&&(this._webWorker.terminate(),this._webWorker=null),ci.#Ji?.delete(this._port),this._port=null,this._messageHandler&&(this._messageHandler.destroy(),this._messageHandler=null)}static fromPort(t){if(!t?.port)throw new Error("PDFWorker.fromPort - invalid method signature.");const e=this.#Ji?.get(t.port);if(e){if(e._pendingDestroy)throw new Error("PDFWorker.fromPort - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return e}return new ci(t)}static get workerSrc(){if(be.workerSrc)return be.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get#ts(){try{return globalThis.pdfjsWorker?.WorkerMessageHandler||null}catch{return null}}static get _setupFakeWorkerGlobal(){return S(this,"_setupFakeWorkerGlobal",(async()=>this.#ts?this.#ts:(await import(this.workerSrc)).WorkerMessageHandler)())}}class ui{#es=new Map;#is=new Map;#ss=new Map;#ns=new Map;#as=null;constructor(t,e,i,s,n){this.messageHandler=t,this.loadingTask=e,this.commonObjs=new gi,this.fontLoader=new zt({ownerDocument:s.ownerDocument,styleElement:s.styleElement}),this.loadingParams=s.loadingParams,this._params=s,this.canvasFactory=n.canvasFactory,this.filterFactory=n.filterFactory,this.cMapReaderFactory=n.cMapReaderFactory,this.standardFontDataFactory=n.standardFontDataFactory,this.destroyed=!1,this.destroyCapability=null,this._networkStream=i,this._fullReader=null,this._lastProgress=null,this.downloadInfoCapability=Promise.withResolvers(),this.setupMessageHandler()}#rs(t,e=null){const i=this.#es.get(t);if(i)return i;const s=this.messageHandler.sendWithPromise(t,e);return this.#es.set(t,s),s}get annotationStorage(){return S(this,"annotationStorage",new Ot)}getRenderingIntent(t,e=h.ENABLE,i=null,s=!1,n=!1){let a=2,r=Nt;switch(t){case"any":a=1;break;case"display":break;case"print":a=4;break;default:_(`getRenderingIntent - invalid intent: ${t}`)}const o=4&a&&i instanceof Bt?i:this.annotationStorage;switch(e){case h.DISABLE:a+=64;break;case h.ENABLE:break;case h.ENABLE_FORMS:a+=16;break;case h.ENABLE_STORAGE:a+=32,r=o.serializable;break;default:_(`getRenderingIntent - invalid annotationMode: ${e}`)}s&&(a+=128),n&&(a+=256);const{ids:l,hash:d}=o.modifiedIds;return{renderingIntent:a,cacheKey:[a,r.hash,d].join("_"),annotationStorageSerializable:r,modifiedIds:l}}destroy(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=Promise.withResolvers(),this.#as?.reject(new Error("Worker was destroyed during onPassword callback"));const t=[];for(const e of this.#is.values())t.push(e._destroy());this.#is.clear(),this.#ss.clear(),this.#ns.clear(),this.hasOwnProperty("annotationStorage")&&this.annotationStorage.resetModified();const e=this.messageHandler.sendWithPromise("Terminate",null);return t.push(e),Promise.all(t).then((()=>{this.commonObjs.clear(),this.fontLoader.clear(),this.#es.clear(),this.filterFactory.destroy(),Qe.cleanup(),this._networkStream?.cancelAllRequests(new L("Worker was terminated.")),this.messageHandler&&(this.messageHandler.destroy(),this.messageHandler=null),this.destroyCapability.resolve()}),this.destroyCapability.reject),this.destroyCapability.promise}setupMessageHandler(){const{messageHandler:t,loadingTask:e}=this;t.on("GetReader",((t,e)=>{C(this._networkStream,"GetReader - no `IPDFStream` instance available."),this._fullReader=this._networkStream.getFullReader(),this._fullReader.onProgress=t=>{this._lastProgress={loaded:t.loaded,total:t.total}},e.onPull=()=>{this._fullReader.read().then((function({value:t,done:i}){i?e.close():(C(t instanceof ArrayBuffer,"GetReader - expected an ArrayBuffer."),e.enqueue(new Uint8Array(t),1,[t]))})).catch((t=>{e.error(t)}))},e.onCancel=t=>{this._fullReader.cancel(t),e.ready.catch((t=>{if(!this.destroyed)throw t}))}})),t.on("ReaderHeadersReady",(t=>{const i=Promise.withResolvers(),s=this._fullReader;return s.headersReady.then((()=>{s.isStreamingSupported&&s.isRangeSupported||(this._lastProgress&&e.onProgress?.(this._lastProgress),s.onProgress=t=>{e.onProgress?.({loaded:t.loaded,total:t.total})}),i.resolve({isStreamingSupported:s.isStreamingSupported,isRangeSupported:s.isRangeSupported,contentLength:s.contentLength})}),i.reject),i.promise})),t.on("GetRangeReader",((t,e)=>{C(this._networkStream,"GetRangeReader - no `IPDFStream` instance available.");const i=this._networkStream.getRangeReader(t.begin,t.end);i?(e.onPull=()=>{i.read().then((function({value:t,done:i}){i?e.close():(C(t instanceof ArrayBuffer,"GetRangeReader - expected an ArrayBuffer."),e.enqueue(new Uint8Array(t),1,[t]))})).catch((t=>{e.error(t)}))},e.onCancel=t=>{i.cancel(t),e.ready.catch((t=>{if(!this.destroyed)throw t}))}):e.close()})),t.on("GetDoc",(({pdfInfo:t})=>{this._numPages=t.numPages,this._htmlForXfa=t.htmlForXfa,delete t.htmlForXfa,e._capability.resolve(new li(t,this))})),t.on("DocException",(function(t){let i;switch(t.name){case"PasswordException":i=new M(t.message,t.code);break;case"InvalidPDFException":i=new I(t.message);break;case"MissingPDFException":i=new P(t.message);break;case"UnexpectedResponseException":i=new R(t.message,t.status);break;case"UnknownErrorException":i=new k(t.message,t.details);break;default:x("DocException - expected a valid Error.")}e._capability.reject(i)})),t.on("PasswordRequest",(t=>{if(this.#as=Promise.withResolvers(),e.onPassword){const i=t=>{t instanceof Error?this.#as.reject(t):this.#as.resolve({password:t})};try{e.onPassword(i,t.code)}catch(t){this.#as.reject(t)}}else this.#as.reject(new M(t.message,t.code));return this.#as.promise})),t.on("DataLoaded",(t=>{e.onProgress?.({loaded:t.length,total:t.length}),this.downloadInfoCapability.resolve(t)})),t.on("StartRenderPage",(t=>{this.destroyed||this.#is.get(t.pageIndex)._startRenderPage(t.transparency,t.cacheKey)})),t.on("commonobj",(([e,i,s])=>{if(this.destroyed)return null;if(this.commonObjs.has(e))return null;switch(i){case"Font":const{disableFontFace:n,fontExtraProperties:a,pdfBug:r}=this._params;if("error"in s){const t=s.error;_(`Error during font loading: ${t}`),this.commonObjs.resolve(e,t);break}const o=r&&globalThis.FontInspector?.enabled?(t,e)=>globalThis.FontInspector.fontAdded(t,e):null,l=new Ht(s,{disableFontFace:n,inspectFont:o});this.fontLoader.bind(l).catch((()=>t.sendWithPromise("FontFallback",{id:e}))).finally((()=>{!a&&l.data&&(l.data=null),this.commonObjs.resolve(e,l)}));break;case"CopyLocalImage":const{imageRef:h}=s;C(h,"The imageRef must be defined.");for(const t of this.#is.values())for(const[,i]of t.objs)if(i?.ref===h)return i.dataLen?(this.commonObjs.resolve(e,structuredClone(i)),i.dataLen):null;break;case"FontPath":case"Image":case"Pattern":this.commonObjs.resolve(e,s);break;default:throw new Error(`Got unknown common object type ${i}`)}return null})),t.on("obj",(([t,e,i,s])=>{if(this.destroyed)return;const n=this.#is.get(e);if(!n.objs.has(t))if(0!==n._intentStates.size)switch(i){case"Image":n.objs.resolve(t,s),s?.dataLen>1e7&&(n._maybeCleanupAfterRender=!0);break;case"Pattern":n.objs.resolve(t,s);break;default:throw new Error(`Got unknown object type ${i}`)}else s?.bitmap?.close()})),t.on("DocProgress",(t=>{this.destroyed||e.onProgress?.({loaded:t.loaded,total:t.total})})),t.on("FetchBuiltInCMap",(t=>this.destroyed?Promise.reject(new Error("Worker was destroyed.")):this.cMapReaderFactory?this.cMapReaderFactory.fetch(t):Promise.reject(new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter.")))),t.on("FetchStandardFontData",(t=>this.destroyed?Promise.reject(new Error("Worker was destroyed.")):this.standardFontDataFactory?this.standardFontDataFactory.fetch(t):Promise.reject(new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter."))))}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){this.annotationStorage.size<=0&&_("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");const{map:t,transfer:e}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:t,filename:this._fullReader?.filename??null},e).finally((()=>{this.annotationStorage.resetModified()}))}getPage(t){if(!Number.isInteger(t)||t<=0||t>this._numPages)return Promise.reject(new Error("Invalid page request."));const e=t-1,i=this.#ss.get(e);if(i)return i;const s=this.messageHandler.sendWithPromise("GetPage",{pageIndex:e}).then((i=>{if(this.destroyed)throw new Error("Transport destroyed");i.refStr&&this.#ns.set(i.refStr,t);const s=new hi(e,i,this,this._params.pdfBug);return this.#is.set(e,s),s}));return this.#ss.set(e,s),s}getPageIndex(t){return ai(t)?this.messageHandler.sendWithPromise("GetPageIndex",{num:t.num,gen:t.gen}):Promise.reject(new Error("Invalid pageIndex request."))}getAnnotations(t,e){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:t,intent:e})}getFieldObjects(){return this.#rs("GetFieldObjects")}hasJSActions(){return this.#rs("HasJSActions")}getCalculationOrderIds(){return this.messageHandler.sendWithPromise("GetCalculationOrderIds",null)}getDestinations(){return this.messageHandler.sendWithPromise("GetDestinations",null)}getDestination(t){return"string"!=typeof t?Promise.reject(new Error("Invalid destination request.")):this.messageHandler.sendWithPromise("GetDestination",{id:t})}getPageLabels(){return this.messageHandler.sendWithPromise("GetPageLabels",null)}getPageLayout(){return this.messageHandler.sendWithPromise("GetPageLayout",null)}getPageMode(){return this.messageHandler.sendWithPromise("GetPageMode",null)}getViewerPreferences(){return this.messageHandler.sendWithPromise("GetViewerPreferences",null)}getOpenAction(){return this.messageHandler.sendWithPromise("GetOpenAction",null)}getAttachments(){return this.messageHandler.sendWithPromise("GetAttachments",null)}getDocJSActions(){return this.#rs("GetDocJSActions")}getPageJSActions(t){return this.messageHandler.sendWithPromise("GetPageJSActions",{pageIndex:t})}getStructTree(t){return this.messageHandler.sendWithPromise("GetStructTree",{pageIndex:t})}getOutline(){return this.messageHandler.sendWithPromise("GetOutline",null)}getOptionalContentConfig(t){return this.#rs("GetOptionalContentConfig").then((e=>new xe(e,t)))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const t="GetMetadata",e=this.#es.get(t);if(e)return e;const i=this.messageHandler.sendWithPromise(t,null).then((t=>({info:t[0],metadata:t[1]?new ye(t[1]):null,contentDispositionFilename:this._fullReader?.filename??null,contentLength:this._fullReader?.contentLength??null})));return this.#es.set(t,i),i}getMarkInfo(){return this.messageHandler.sendWithPromise("GetMarkInfo",null)}async startCleanup(t=!1){if(!this.destroyed){await this.messageHandler.sendWithPromise("Cleanup",null);for(const t of this.#is.values())if(!t.cleanup())throw new Error(`startCleanup: Page ${t.pageNumber} is currently rendering.`);this.commonObjs.clear(),t||this.fontLoader.clear(),this.#es.clear(),this.filterFactory.destroy(!0),Qe.cleanup()}}cachedPageNumber(t){if(!ai(t))return null;const e=0===t.gen?`${t.num}R`:`${t.num}R${t.gen}`;return this.#ns.get(e)??null}}const pi=Symbol("INITIAL_DATA");class gi{#os=Object.create(null);#ls(t){return this.#os[t]||={...Promise.withResolvers(),data:pi}}get(t,e=null){if(e){const i=this.#ls(t);return i.promise.then((()=>e(i.data))),null}const i=this.#os[t];if(!i||i.data===pi)throw new Error(`Requesting object that isn't resolved yet ${t}.`);return i.data}has(t){const e=this.#os[t];return!!e&&e.data!==pi}resolve(t,e=null){const i=this.#ls(t);i.data=e,i.resolve()}clear(){for(const t in this.#os){const{data:e}=this.#os[t];e?.bitmap?.close()}this.#os=Object.create(null)}*[Symbol.iterator](){for(const t in this.#os){const{data:e}=this.#os[t];e!==pi&&(yield[t,e])}}}class mi{#hs=null;constructor(t){this.#hs=t,this.onContinue=null}get promise(){return this.#hs.capability.promise}cancel(t=0){this.#hs.cancel(null,t)}get separateAnnots(){const{separateAnnots:t}=this.#hs.operatorList;if(!t)return!1;const{annotationCanvasMap:e}=this.#hs;return t.form||t.canvas&&e?.size>0}}class fi{#ds=null;static#cs=new WeakSet;constructor({callback:t,params:e,objs:i,commonObjs:s,annotationCanvasMap:n,operatorList:a,pageIndex:r,canvasFactory:o,filterFactory:l,useRequestAnimationFrame:h=!1,pdfBug:d=!1,pageColors:c=null}){this.callback=t,this.params=e,this.objs=i,this.commonObjs=s,this.annotationCanvasMap=n,this.operatorListIdx=null,this.operatorList=a,this._pageIndex=r,this.canvasFactory=o,this.filterFactory=l,this._pdfBug=d,this.pageColors=c,this.running=!1,this.graphicsReadyCallback=null,this.graphicsReady=!1,this._useRequestAnimationFrame=!0===h&&"undefined"!=typeof window,this.cancelled=!1,this.capability=Promise.withResolvers(),this.task=new mi(this),this._cancelBound=this.cancel.bind(this),this._continueBound=this._continue.bind(this),this._scheduleNextBound=this._scheduleNext.bind(this),this._nextBound=this._next.bind(this),this._canvas=e.canvasContext.canvas}get completed(){return this.capability.promise.catch((function(){}))}initializeGraphics({transparency:t=!1,optionalContentConfig:e}){if(this.cancelled)return;if(this._canvas){if(fi.#cs.has(this._canvas))throw new Error("Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.");fi.#cs.add(this._canvas)}this._pdfBug&&globalThis.StepperManager?.enabled&&(this.stepper=globalThis.StepperManager.create(this._pageIndex),this.stepper.init(this.operatorList),this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint());const{canvasContext:i,viewport:s,transform:n,background:a}=this.params;this.gfx=new fe(i,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:e},this.annotationCanvasMap,this.pageColors),this.gfx.beginDrawing({transform:n,viewport:s,transparency:t,background:a}),this.operatorListIdx=0,this.graphicsReady=!0,this.graphicsReadyCallback?.()}cancel(t=null,e=0){this.running=!1,this.cancelled=!0,this.gfx?.endDrawing(),this.#ds&&(window.cancelAnimationFrame(this.#ds),this.#ds=null),fi.#cs.delete(this._canvas),this.callback(t||new st(`Rendering cancelled, page ${this._pageIndex+1}`,e))}operatorListChanged(){this.graphicsReady?(this.stepper?.updateOperatorList(this.operatorList),this.running||this._continue()):this.graphicsReadyCallback||=this._continueBound}_continue(){this.running=!0,this.cancelled||(this.task.onContinue?this.task.onContinue(this._scheduleNextBound):this._scheduleNext())}_scheduleNext(){this._useRequestAnimationFrame?this.#ds=window.requestAnimationFrame((()=>{this.#ds=null,this._nextBound().catch(this._cancelBound)})):Promise.resolve().then(this._nextBound).catch(this._cancelBound)}async _next(){this.cancelled||(this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper),this.operatorListIdx===this.operatorList.argsArray.length&&(this.running=!1,this.operatorList.lastChunk&&(this.gfx.endDrawing(),fi.#cs.delete(this._canvas),this.callback())))}}const bi="4.7.76",vi="8b73b828b";function Ai(t){return Math.floor(255*Math.max(0,Math.min(1,t))).toString(16).padStart(2,"0")}function yi(t){return Math.max(0,Math.min(255,255*t))}class wi{static CMYK_G([t,e,i,s]){return["G",1-Math.min(1,.3*t+.59*i+.11*e+s)]}static G_CMYK([t]){return["CMYK",0,0,0,1-t]}static G_RGB([t]){return["RGB",t,t,t]}static G_rgb([t]){return[t=yi(t),t,t]}static G_HTML([t]){const e=Ai(t);return`#${e}${e}${e}`}static RGB_G([t,e,i]){return["G",.3*t+.59*e+.11*i]}static RGB_rgb(t){return t.map(yi)}static RGB_HTML(t){return`#${t.map(Ai).join("")}`}static T_HTML(){return"#00000000"}static T_rgb(){return[null]}static CMYK_RGB([t,e,i,s]){return["RGB",1-Math.min(1,t+s),1-Math.min(1,i+s),1-Math.min(1,e+s)]}static CMYK_rgb([t,e,i,s]){return[yi(1-Math.min(1,t+s)),yi(1-Math.min(1,i+s)),yi(1-Math.min(1,e+s))]}static CMYK_HTML(t){const e=this.CMYK_RGB(t).slice(1);return this.RGB_HTML(e)}static RGB_CMYK([t,e,i]){const s=1-t,n=1-e,a=1-i;return["CMYK",s,n,a,Math.min(s,n,a)]}}class _i{static setupStorage(t,e,i,s,n){const a=s.getValue(e,{value:null});switch(i.name){case"textarea":if(null!==a.value&&(t.textContent=a.value),"print"===n)break;t.addEventListener("input",(t=>{s.setValue(e,{value:t.target.value})}));break;case"input":if("radio"===i.attributes.type||"checkbox"===i.attributes.type){if(a.value===i.attributes.xfaOn?t.setAttribute("checked",!0):a.value===i.attributes.xfaOff&&t.removeAttribute("checked"),"print"===n)break;t.addEventListener("change",(t=>{s.setValue(e,{value:t.target.checked?t.target.getAttribute("xfaOn"):t.target.getAttribute("xfaOff")})}))}else{if(null!==a.value&&t.setAttribute("value",a.value),"print"===n)break;t.addEventListener("input",(t=>{s.setValue(e,{value:t.target.value})}))}break;case"select":if(null!==a.value){t.setAttribute("value",a.value);for(const t of i.children)t.attributes.value===a.value?t.attributes.selected=!0:t.attributes.hasOwnProperty("selected")&&delete t.attributes.selected}t.addEventListener("input",(t=>{const i=t.target.options,n=-1===i.selectedIndex?"":i[i.selectedIndex].value;s.setValue(e,{value:n})}))}}static setAttributes({html:t,element:e,storage:i=null,intent:s,linkService:n}){const{attributes:a}=e,r=t instanceof HTMLAnchorElement;"radio"===a.type&&(a.name=`${a.name}-${s}`);for(const[e,i]of Object.entries(a))if(null!=i)switch(e){case"class":i.length&&t.setAttribute(e,i.join(" "));break;case"dataId":break;case"id":t.setAttribute("data-element-id",i);break;case"style":Object.assign(t.style,i);break;case"textContent":t.textContent=i;break;default:(!r||"href"!==e&&"newWindow"!==e)&&t.setAttribute(e,i)}r&&n.addLinkAttributes(t,a.href,a.newWindow),i&&a.dataId&&this.setupStorage(t,a.dataId,e,i)}static render(t){const e=t.annotationStorage,i=t.linkService,s=t.xfaHtml,n=t.intent||"display",a=document.createElement(s.name);s.attributes&&this.setAttributes({html:a,element:s,intent:n,linkService:i});const r="richText"!==n,o=t.div;if(o.append(a),t.viewport){const e=`matrix(${t.viewport.transform.join(",")})`;o.style.transform=e}r&&o.setAttribute("class","xfaLayer xfaFont");const l=[];if(0===s.children.length){if(s.value){const t=document.createTextNode(s.value);a.append(t),r&&Je.shouldBuildText(s.name)&&l.push(t)}return{textDivs:l}}const h=[[s,-1,a]];for(;h.length>0;){const[t,s,a]=h.at(-1);if(s+1===t.children.length){h.pop();continue}const o=t.children[++h.at(-1)[1]];if(null===o)continue;const{name:d}=o;if("#text"===d){const t=document.createTextNode(o.value);l.push(t),a.append(t);continue}const c=o?.attributes?.xmlns?document.createElementNS(o.attributes.xmlns,d):document.createElement(d);if(a.append(c),o.attributes&&this.setAttributes({html:c,element:o,storage:e,intent:n,linkService:i}),o.children?.length>0)h.push([o,-1,c]);else if(o.value){const t=document.createTextNode(o.value);r&&Je.shouldBuildText(d)&&l.push(t),c.append(t)}}for(const t of o.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))t.setAttribute("readOnly",!0);return{textDivs:l}}static update(t){const e=`matrix(${t.viewport.transform.join(",")})`;t.div.style.transform=e,t.div.hidden=!1}}const xi=1e3,Ci=new WeakSet;function Ei(t){return{width:t[2]-t[0],height:t[3]-t[1]}}class Si{static create(t){switch(t.data.annotationType){case 2:return new Mi(t);case 1:return new ki(t);case 20:switch(t.data.fieldType){case"Tx":return new Pi(t);case"Btn":return t.data.radioButton?new Li(t):t.data.checkBox?new Di(t):new Fi(t);case"Ch":return new Ni(t);case"Sig":return new Ri(t)}return new Ii(t);case 16:return new Oi(t);case 3:return new zi(t);case 4:return new Hi(t);case 5:return new ji(t);case 6:return new Ui(t);case 8:return new $i(t);case 14:return new Gi(t);case 15:return new Vi(t);case 7:return new Wi(t);case 9:return new qi(t);case 10:return new Xi(t);case 11:return new Ki(t);case 12:return new Yi(t);case 13:return new Qi(t);case 17:return new Ji(t);default:return new Ti(t)}}}class Ti{#us=null;#ps=!1;#gs=null;constructor(t,{isRenderable:e=!1,ignoreBorder:i=!1,createQuadrilaterals:s=!1}={}){this.isRenderable=e,this.data=t.data,this.layer=t.layer,this.linkService=t.linkService,this.downloadManager=t.downloadManager,this.imageResourcesPath=t.imageResourcesPath,this.renderForms=t.renderForms,this.svgFactory=t.svgFactory,this.annotationStorage=t.annotationStorage,this.enableScripting=t.enableScripting,this.hasJSActions=t.hasJSActions,this._fieldObjects=t.fieldObjects,this.parent=t.parent,e&&(this.container=this._createContainer(i)),s&&this._createQuadrilaterals()}static _hasPopupData({titleObj:t,contentsObj:e,richText:i}){return!!(t?.str||e?.str||i?.str)}get _isEditable(){return this.data.isEditable}get hasPopupData(){return Ti._hasPopupData(this.data)}updateEdited(t){if(!this.container)return;this.#us||={rect:this.data.rect.slice(0)};const{rect:e}=t;e&&this.#ms(e),this.#gs?.popup.updateEdited(t)}resetEdited(){this.#us&&(this.#ms(this.#us.rect),this.#gs?.popup.resetEdited(),this.#us=null)}#ms(t){const{container:{style:e},data:{rect:i,rotation:s},parent:{viewport:{rawDims:{pageWidth:n,pageHeight:a,pageX:r,pageY:o}}}}=this;i?.splice(0,4,...t);const{width:l,height:h}=Ei(t);e.left=100*(t[0]-r)/n+"%",e.top=100*(a-t[3]+o)/a+"%",0===s?(e.width=100*l/n+"%",e.height=100*h/a+"%"):this.setRotation(s)}_createContainer(t){const{data:e,parent:{page:i,viewport:s}}=this,n=document.createElement("section");n.setAttribute("data-annotation-id",e.id),this instanceof Ii||(n.tabIndex=xi);const{style:a}=n;if(a.zIndex=this.parent.zIndex++,e.popupRef&&n.setAttribute("aria-haspopup","dialog"),e.alternativeText&&(n.title=e.alternativeText),e.noRotate&&n.classList.add("norotate"),!e.rect||this instanceof Oi){const{rotation:t}=e;return e.hasOwnCanvas||0===t||this.setRotation(t,n),n}const{width:r,height:o}=Ei(e.rect);if(!t&&e.borderStyle.width>0){a.borderWidth=`${e.borderStyle.width}px`;const t=e.borderStyle.horizontalCornerRadius,i=e.borderStyle.verticalCornerRadius;if(t>0||i>0){const e=`calc(${t}px * var(--scale-factor)) / calc(${i}px * var(--scale-factor))`;a.borderRadius=e}else if(this instanceof Li){const t=`calc(${r}px * var(--scale-factor)) / calc(${o}px * var(--scale-factor))`;a.borderRadius=t}switch(e.borderStyle.style){case 1:a.borderStyle="solid";break;case 2:a.borderStyle="dashed";break;case 3:_("Unimplemented border style: beveled");break;case 4:_("Unimplemented border style: inset");break;case 5:a.borderBottomStyle="solid"}const s=e.borderColor||null;s?(this.#ps=!0,a.borderColor=H.makeHexColor(0|s[0],0|s[1],0|s[2])):a.borderWidth=0}const l=H.normalizeRect([e.rect[0],i.view[3]-e.rect[1]+i.view[1],e.rect[2],i.view[3]-e.rect[3]+i.view[1]]),{pageWidth:h,pageHeight:d,pageX:c,pageY:u}=s.rawDims;a.left=100*(l[0]-c)/h+"%",a.top=100*(l[1]-u)/d+"%";const{rotation:p}=e;return e.hasOwnCanvas||0===p?(a.width=100*r/h+"%",a.height=100*o/d+"%"):this.setRotation(p,n),n}setRotation(t,e=this.container){if(!this.data.rect)return;const{pageWidth:i,pageHeight:s}=this.parent.viewport.rawDims,{width:n,height:a}=Ei(this.data.rect);let r,o;t%180==0?(r=100*n/i,o=100*a/s):(r=100*a/i,o=100*n/s),e.style.width=`${r}%`,e.style.height=`${o}%`,e.setAttribute("data-main-rotation",(360-t)%360)}get _commonActions(){const t=(t,e,i)=>{const s=i.detail[t],n=s[0],a=s.slice(1);i.target.style[e]=wi[`${n}_HTML`](a),this.annotationStorage.setValue(this.data.id,{[e]:wi[`${n}_rgb`](a)})};return S(this,"_commonActions",{display:t=>{const{display:e}=t.detail,i=e%2==1;this.container.style.visibility=i?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noView:i,noPrint:1===e||2===e})},print:t=>{this.annotationStorage.setValue(this.data.id,{noPrint:!t.detail.print})},hidden:t=>{const{hidden:e}=t.detail;this.container.style.visibility=e?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noPrint:e,noView:e})},focus:t=>{setTimeout((()=>t.target.focus({preventScroll:!1})),0)},userName:t=>{t.target.title=t.detail.userName},readonly:t=>{t.target.disabled=t.detail.readonly},required:t=>{this._setRequired(t.target,t.detail.required)},bgColor:e=>{t("bgColor","backgroundColor",e)},fillColor:e=>{t("fillColor","backgroundColor",e)},fgColor:e=>{t("fgColor","color",e)},textColor:e=>{t("textColor","color",e)},borderColor:e=>{t("borderColor","borderColor",e)},strokeColor:e=>{t("strokeColor","borderColor",e)},rotation:t=>{const e=t.detail.rotation;this.setRotation(e),this.annotationStorage.setValue(this.data.id,{rotation:e})}})}_dispatchEventFromSandbox(t,e){const i=this._commonActions;for(const s of Object.keys(e.detail)){const n=t[s]||i[s];n?.(e)}}_setDefaultPropertiesFromJS(t){if(!this.enableScripting)return;const e=this.annotationStorage.getRawValue(this.data.id);if(!e)return;const i=this._commonActions;for(const[s,n]of Object.entries(e)){const a=i[s];a&&(a({detail:{[s]:n},target:t}),delete e[s])}}_createQuadrilaterals(){if(!this.container)return;const{quadPoints:t}=this.data;if(!t)return;const[e,i,s,n]=this.data.rect.map((t=>Math.fround(t)));if(8===t.length){const[a,r,o,l]=t.subarray(2,6);if(s===a&&n===r&&e===o&&i===l)return}const{style:a}=this.container;let r;if(this.#ps){const{borderColor:t,borderWidth:e}=a;a.borderWidth=0,r=["url('data:image/svg+xml;utf8,",'',``],this.container.classList.add("hasBorder")}const o=s-e,l=n-i,{svgFactory:h}=this,d=h.createElement("svg");d.classList.add("quadrilateralsContainer"),d.setAttribute("width",0),d.setAttribute("height",0);const c=h.createElement("defs");d.append(c);const u=h.createElement("clipPath"),p=`clippath_${this.data.id}`;u.setAttribute("id",p),u.setAttribute("clipPathUnits","objectBoundingBox"),c.append(u);for(let i=2,s=t.length;i`)}this.#ps&&(r.push("')"),a.backgroundImage=r.join("")),this.container.append(d),this.container.style.clipPath=`url(#${p})`}_createPopup(){const{container:t,data:e}=this;t.setAttribute("aria-haspopup","dialog");const i=this.#gs=new Oi({data:{color:e.color,titleObj:e.titleObj,modificationDate:e.modificationDate,contentsObj:e.contentsObj,richText:e.richText,parentRect:e.rect,borderStyle:0,id:`popup_${e.id}`,rotation:e.rotation},parent:this.parent,elements:[this]});this.parent.div.append(i.render())}render(){x("Abstract method `AnnotationElement.render` called")}_getElementsByName(t,e=null){const i=[];if(this._fieldObjects){const s=this._fieldObjects[t];if(s)for(const{page:t,id:n,exportValues:a}of s){if(-1===t)continue;if(n===e)continue;const s="string"==typeof a?a:null,r=document.querySelector(`[data-element-id="${n}"]`);!r||Ci.has(r)?i.push({id:n,exportValue:s,domElement:r}):_(`_getElementsByName - element not allowed: ${n}`)}return i}for(const s of document.getElementsByName(t)){const{exportValue:t}=s,n=s.getAttribute("data-element-id");n!==e&&Ci.has(s)&&i.push({id:n,exportValue:t,domElement:s})}return i}show(){this.container&&(this.container.hidden=!1),this.popup?.maybeShow()}hide(){this.container&&(this.container.hidden=!0),this.popup?.forceHide()}getElementsToTriggerPopup(){return this.container}addHighlightArea(){const t=this.getElementsToTriggerPopup();if(Array.isArray(t))for(const e of t)e.classList.add("highlightArea");else t.classList.add("highlightArea")}_editOnDoubleClick(){if(!this._isEditable)return;const{annotationEditorType:t,data:{id:e}}=this;this.container.addEventListener("dblclick",(()=>{this.linkService.eventBus?.dispatch("switchannotationeditormode",{source:this,mode:t,editId:e})}))}}class Mi extends Ti{constructor(t,e=null){super(t,{isRenderable:!0,ignoreBorder:!!e?.ignoreBorder,createQuadrilaterals:!0}),this.isTooltipOnly=t.data.isTooltipOnly}render(){const{data:t,linkService:e}=this,i=document.createElement("a");i.setAttribute("data-element-id",t.id);let s=!1;return t.url?(e.addLinkAttributes(i,t.url,t.newWindow),s=!0):t.action?(this._bindNamedAction(i,t.action),s=!0):t.attachment?(this.#fs(i,t.attachment,t.attachmentDest),s=!0):t.setOCGState?(this.#bs(i,t.setOCGState),s=!0):t.dest?(this._bindLink(i,t.dest),s=!0):(t.actions&&(t.actions.Action||t.actions["Mouse Up"]||t.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions&&(this._bindJSAction(i,t),s=!0),t.resetForm?(this._bindResetFormAction(i,t.resetForm),s=!0):this.isTooltipOnly&&!s&&(this._bindLink(i,""),s=!0)),this.container.classList.add("linkAnnotation"),s&&this.container.append(i),this.container}#vs(){this.container.setAttribute("data-internal-link","")}_bindLink(t,e){t.href=this.linkService.getDestinationHash(e),t.onclick=()=>(e&&this.linkService.goToDestination(e),!1),(e||""===e)&&this.#vs()}_bindNamedAction(t,e){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeNamedAction(e),!1),this.#vs()}#fs(t,e,i=null){t.href=this.linkService.getAnchorUrl(""),e.description&&(t.title=e.description),t.onclick=()=>(this.downloadManager?.openOrDownloadData(e.content,e.filename,i),!1),this.#vs()}#bs(t,e){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeSetOCGState(e),!1),this.#vs()}_bindJSAction(t,e){t.href=this.linkService.getAnchorUrl("");const i=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(const s of Object.keys(e.actions)){const n=i.get(s);n&&(t[n]=()=>(this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e.id,name:s}}),!1))}t.onclick||(t.onclick=()=>!1),this.#vs()}_bindResetFormAction(t,e){const i=t.onclick;if(i||(t.href=this.linkService.getAnchorUrl("")),this.#vs(),!this._fieldObjects)return _('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.'),void(i||(t.onclick=()=>!1));t.onclick=()=>{i?.();const{fields:t,refs:s,include:n}=e,a=[];if(0!==t.length||0!==s.length){const e=new Set(s);for(const i of t){const t=this._fieldObjects[i]||[];for(const{id:i}of t)e.add(i)}for(const t of Object.values(this._fieldObjects))for(const i of t)e.has(i.id)===n&&a.push(i)}else for(const t of Object.values(this._fieldObjects))a.push(...t);const r=this.annotationStorage,o=[];for(const t of a){const{id:e}=t;switch(o.push(e),t.type){case"text":{const i=t.defaultValue||"";r.setValue(e,{value:i});break}case"checkbox":case"radiobutton":{const i=t.defaultValue===t.exportValues;r.setValue(e,{value:i});break}case"combobox":case"listbox":{const i=t.defaultValue||"";r.setValue(e,{value:i});break}default:continue}const i=document.querySelector(`[data-element-id="${e}"]`);i&&(Ci.has(i)?i.dispatchEvent(new Event("resetform")):_(`_bindResetFormAction - element not allowed: ${e}`))}return this.enableScripting&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:o,name:"ResetForm"}}),!1}}}class ki extends Ti{constructor(t){super(t,{isRenderable:!0})}render(){this.container.classList.add("textAnnotation");const t=document.createElement("img");return t.src=this.imageResourcesPath+"annotation-"+this.data.name.toLowerCase()+".svg",t.setAttribute("data-l10n-id","pdfjs-text-annotation-type"),t.setAttribute("data-l10n-args",JSON.stringify({type:this.data.name})),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.append(t),this.container}}class Ii extends Ti{render(){return this.container}showElementAndHideCanvas(t){this.data.hasOwnCanvas&&("CANVAS"===t.previousSibling?.nodeName&&(t.previousSibling.hidden=!0),t.hidden=!1)}_getKeyModifier(t){return B.platform.isMac?t.metaKey:t.ctrlKey}_setEventListener(t,e,i,s,n){i.includes("mouse")?t.addEventListener(i,(t=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:s,value:n(t),shift:t.shiftKey,modifier:this._getKeyModifier(t)}})})):t.addEventListener(i,(t=>{if("blur"===i){if(!e.focused||!t.relatedTarget)return;e.focused=!1}else if("focus"===i){if(e.focused)return;e.focused=!0}n&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:s,value:n(t)}})}))}_setEventListeners(t,e,i,s){for(const[n,a]of i)("Action"===a||this.data.actions?.[a])&&("Focus"!==a&&"Blur"!==a||(e||={focused:!1}),this._setEventListener(t,e,n,a,s),"Focus"!==a||this.data.actions?.Blur?"Blur"!==a||this.data.actions?.Focus||this._setEventListener(t,e,"focus","Focus",null):this._setEventListener(t,e,"blur","Blur",null))}_setBackgroundColor(t){const e=this.data.backgroundColor||null;t.style.backgroundColor=null===e?"transparent":H.makeHexColor(e[0],e[1],e[2])}_setTextStyle(t){const{fontColor:e}=this.data.defaultAppearanceData,i=this.data.defaultAppearanceData.fontSize||9,s=t.style;let n;const a=t=>Math.round(10*t)/10;if(this.data.multiLine){const t=Math.abs(this.data.rect[3]-this.data.rect[1]-2),e=t/(Math.round(t/(l*i))||1);n=Math.min(i,a(e/l))}else{const t=Math.abs(this.data.rect[3]-this.data.rect[1]-2);n=Math.min(i,a(t/l))}s.fontSize=`calc(${n}px * var(--scale-factor))`,s.color=H.makeHexColor(e[0],e[1],e[2]),null!==this.data.textAlignment&&(s.textAlign=["left","center","right"][this.data.textAlignment])}_setRequired(t,e){e?t.setAttribute("required",!0):t.removeAttribute("required"),t.setAttribute("aria-required",e)}}class Pi extends Ii{constructor(t){super(t,{isRenderable:t.renderForms||t.data.hasOwnCanvas||!t.data.hasAppearance&&!!t.data.fieldValue})}setPropertyOnSiblings(t,e,i,s){const n=this.annotationStorage;for(const a of this._getElementsByName(t.name,t.id))a.domElement&&(a.domElement[e]=i),n.setValue(a.id,{[s]:i})}render(){const t=this.annotationStorage,e=this.data.id;this.container.classList.add("textWidgetAnnotation");let i=null;if(this.renderForms){const s=t.getValue(e,{value:this.data.fieldValue});let n=s.value||"";const a=t.getValue(e,{charLimit:this.data.maxLen}).charLimit;a&&n.length>a&&(n=n.slice(0,a));let r=s.formattedValue||this.data.textContent?.join("\n")||null;r&&this.data.comb&&(r=r.replaceAll(/\s+/g,""));const o={userValue:n,formattedValue:r,lastCommittedValue:null,commitKey:1,focused:!1};this.data.multiLine?(i=document.createElement("textarea"),i.textContent=r??n,this.data.doNotScroll&&(i.style.overflowY="hidden")):(i=document.createElement("input"),i.type="text",i.setAttribute("value",r??n),this.data.doNotScroll&&(i.style.overflowX="hidden")),this.data.hasOwnCanvas&&(i.hidden=!0),Ci.add(i),i.setAttribute("data-element-id",e),i.disabled=this.data.readOnly,i.name=this.data.fieldName,i.tabIndex=xi,this._setRequired(i,this.data.required),a&&(i.maxLength=a),i.addEventListener("input",(s=>{t.setValue(e,{value:s.target.value}),this.setPropertyOnSiblings(i,"value",s.target.value,"value"),o.formattedValue=null})),i.addEventListener("resetform",(t=>{const e=this.data.defaultFieldValue??"";i.value=o.userValue=e,o.formattedValue=null}));let l=t=>{const{formattedValue:e}=o;null!=e&&(t.target.value=e),t.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){i.addEventListener("focus",(t=>{if(o.focused)return;const{target:e}=t;o.userValue&&(e.value=o.userValue),o.lastCommittedValue=e.value,o.commitKey=1,this.data.actions?.Focus||(o.focused=!0)})),i.addEventListener("updatefromsandbox",(i=>{this.showElementAndHideCanvas(i.target);const s={value(i){o.userValue=i.detail.value??"",t.setValue(e,{value:o.userValue.toString()}),i.target.value=o.userValue},formattedValue(i){const{formattedValue:s}=i.detail;o.formattedValue=s,null!=s&&i.target!==document.activeElement&&(i.target.value=s),t.setValue(e,{formattedValue:s})},selRange(t){t.target.setSelectionRange(...t.detail.selRange)},charLimit:i=>{const{charLimit:s}=i.detail,{target:n}=i;if(0===s)return void n.removeAttribute("maxLength");n.setAttribute("maxLength",s);let a=o.userValue;!a||a.length<=s||(a=a.slice(0,s),n.value=o.userValue=a,t.setValue(e,{value:a}),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:a,willCommit:!0,commitKey:1,selStart:n.selectionStart,selEnd:n.selectionEnd}}))}};this._dispatchEventFromSandbox(s,i)})),i.addEventListener("keydown",(t=>{o.commitKey=1;let i=-1;if("Escape"===t.key?i=0:"Enter"!==t.key||this.data.multiLine?"Tab"===t.key&&(o.commitKey=3):i=2,-1===i)return;const{value:s}=t.target;o.lastCommittedValue!==s&&(o.lastCommittedValue=s,o.userValue=s,this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:s,willCommit:!0,commitKey:i,selStart:t.target.selectionStart,selEnd:t.target.selectionEnd}}))}));const s=l;l=null,i.addEventListener("blur",(t=>{if(!o.focused||!t.relatedTarget)return;this.data.actions?.Blur||(o.focused=!1);const{value:i}=t.target;o.userValue=i,o.lastCommittedValue!==i&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:i,willCommit:!0,commitKey:o.commitKey,selStart:t.target.selectionStart,selEnd:t.target.selectionEnd}}),s(t)})),this.data.actions?.Keystroke&&i.addEventListener("beforeinput",(t=>{o.lastCommittedValue=null;const{data:i,target:s}=t,{value:n,selectionStart:a,selectionEnd:r}=s;let l=a,h=r;switch(t.inputType){case"deleteWordBackward":{const t=n.substring(0,a).match(/\w*[^\w]*$/);t&&(l-=t[0].length);break}case"deleteWordForward":{const t=n.substring(a).match(/^[^\w]*\w*/);t&&(h+=t[0].length);break}case"deleteContentBackward":a===r&&(l-=1);break;case"deleteContentForward":a===r&&(h+=1)}t.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:n,change:i||"",willCommit:!1,selStart:l,selEnd:h}})})),this._setEventListeners(i,o,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(t=>t.target.value))}if(l&&i.addEventListener("blur",l),this.data.comb){const t=(this.data.rect[2]-this.data.rect[0])/a;i.classList.add("comb"),i.style.letterSpacing=`calc(${t}px * var(--scale-factor) - 1ch)`}}else i=document.createElement("div"),i.textContent=this.data.fieldValue,i.style.verticalAlign="middle",i.style.display="table-cell",this.data.hasOwnCanvas&&(i.hidden=!0);return this._setTextStyle(i),this._setBackgroundColor(i),this._setDefaultPropertiesFromJS(i),this.container.append(i),this.container}}class Ri extends Ii{constructor(t){super(t,{isRenderable:!!t.data.hasOwnCanvas})}}class Di extends Ii{constructor(t){super(t,{isRenderable:t.renderForms})}render(){const t=this.annotationStorage,e=this.data,i=e.id;let s=t.getValue(i,{value:e.exportValue===e.fieldValue}).value;"string"==typeof s&&(s="Off"!==s,t.setValue(i,{value:s})),this.container.classList.add("buttonWidgetAnnotation","checkBox");const n=document.createElement("input");return Ci.add(n),n.setAttribute("data-element-id",i),n.disabled=e.readOnly,this._setRequired(n,this.data.required),n.type="checkbox",n.name=e.fieldName,s&&n.setAttribute("checked",!0),n.setAttribute("exportValue",e.exportValue),n.tabIndex=xi,n.addEventListener("change",(s=>{const{name:n,checked:a}=s.target;for(const s of this._getElementsByName(n,i)){const i=a&&s.exportValue===e.exportValue;s.domElement&&(s.domElement.checked=i),t.setValue(s.id,{value:i})}t.setValue(i,{value:a})})),n.addEventListener("resetform",(t=>{const i=e.defaultFieldValue||"Off";t.target.checked=i===e.exportValue})),this.enableScripting&&this.hasJSActions&&(n.addEventListener("updatefromsandbox",(e=>{const s={value(e){e.target.checked="Off"!==e.detail.value,t.setValue(i,{value:e.target.checked})}};this._dispatchEventFromSandbox(s,e)})),this._setEventListeners(n,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(t=>t.target.checked))),this._setBackgroundColor(n),this._setDefaultPropertiesFromJS(n),this.container.append(n),this.container}}class Li extends Ii{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("buttonWidgetAnnotation","radioButton");const t=this.annotationStorage,e=this.data,i=e.id;let s=t.getValue(i,{value:e.fieldValue===e.buttonValue}).value;if("string"==typeof s&&(s=s!==e.buttonValue,t.setValue(i,{value:s})),s)for(const s of this._getElementsByName(e.fieldName,i))t.setValue(s.id,{value:!1});const n=document.createElement("input");if(Ci.add(n),n.setAttribute("data-element-id",i),n.disabled=e.readOnly,this._setRequired(n,this.data.required),n.type="radio",n.name=e.fieldName,s&&n.setAttribute("checked",!0),n.tabIndex=xi,n.addEventListener("change",(e=>{const{name:s,checked:n}=e.target;for(const e of this._getElementsByName(s,i))t.setValue(e.id,{value:!1});t.setValue(i,{value:n})})),n.addEventListener("resetform",(t=>{const i=e.defaultFieldValue;t.target.checked=null!=i&&i===e.buttonValue})),this.enableScripting&&this.hasJSActions){const s=e.buttonValue;n.addEventListener("updatefromsandbox",(e=>{const n={value:e=>{const n=s===e.detail.value;for(const s of this._getElementsByName(e.target.name)){const e=n&&s.id===i;s.domElement&&(s.domElement.checked=e),t.setValue(s.id,{value:e})}}};this._dispatchEventFromSandbox(n,e)})),this._setEventListeners(n,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(t=>t.target.checked))}return this._setBackgroundColor(n),this._setDefaultPropertiesFromJS(n),this.container.append(n),this.container}}class Fi extends Mi{constructor(t){super(t,{ignoreBorder:t.data.hasAppearance})}render(){const t=super.render();t.classList.add("buttonWidgetAnnotation","pushButton");const e=t.lastChild;return this.enableScripting&&this.hasJSActions&&e&&(this._setDefaultPropertiesFromJS(e),e.addEventListener("updatefromsandbox",(t=>{this._dispatchEventFromSandbox({},t)}))),t}}class Ni extends Ii{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("choiceWidgetAnnotation");const t=this.annotationStorage,e=this.data.id,i=t.getValue(e,{value:this.data.fieldValue}),s=document.createElement("select");Ci.add(s),s.setAttribute("data-element-id",e),s.disabled=this.data.readOnly,this._setRequired(s,this.data.required),s.name=this.data.fieldName,s.tabIndex=xi;let n=this.data.combo&&this.data.options.length>0;this.data.combo||(s.size=this.data.options.length,this.data.multiSelect&&(s.multiple=!0)),s.addEventListener("resetform",(t=>{const e=this.data.defaultFieldValue;for(const t of s.options)t.selected=t.value===e}));for(const t of this.data.options){const e=document.createElement("option");e.textContent=t.displayValue,e.value=t.exportValue,i.value.includes(t.exportValue)&&(e.setAttribute("selected",!0),n=!1),s.append(e)}let a=null;if(n){const t=document.createElement("option");t.value=" ",t.setAttribute("hidden",!0),t.setAttribute("selected",!0),s.prepend(t),a=()=>{t.remove(),s.removeEventListener("input",a),a=null},s.addEventListener("input",a)}const r=t=>{const e=t?"value":"textContent",{options:i,multiple:n}=s;return n?Array.prototype.filter.call(i,(t=>t.selected)).map((t=>t[e])):-1===i.selectedIndex?null:i[i.selectedIndex][e]};let o=r(!1);const l=t=>{const e=t.target.options;return Array.prototype.map.call(e,(t=>({displayValue:t.textContent,exportValue:t.value})))};return this.enableScripting&&this.hasJSActions?(s.addEventListener("updatefromsandbox",(i=>{const n={value(i){a?.();const n=i.detail.value,l=new Set(Array.isArray(n)?n:[n]);for(const t of s.options)t.selected=l.has(t.value);t.setValue(e,{value:r(!0)}),o=r(!1)},multipleSelection(t){s.multiple=!0},remove(i){const n=s.options,a=i.detail.remove;n[a].selected=!1,s.remove(a),n.length>0&&-1===Array.prototype.findIndex.call(n,(t=>t.selected))&&(n[0].selected=!0),t.setValue(e,{value:r(!0),items:l(i)}),o=r(!1)},clear(i){for(;0!==s.length;)s.remove(0);t.setValue(e,{value:null,items:[]}),o=r(!1)},insert(i){const{index:n,displayValue:a,exportValue:h}=i.detail.insert,d=s.children[n],c=document.createElement("option");c.textContent=a,c.value=h,d?d.before(c):s.append(c),t.setValue(e,{value:r(!0),items:l(i)}),o=r(!1)},items(i){const{items:n}=i.detail;for(;0!==s.length;)s.remove(0);for(const t of n){const{displayValue:e,exportValue:i}=t,n=document.createElement("option");n.textContent=e,n.value=i,s.append(n)}s.options.length>0&&(s.options[0].selected=!0),t.setValue(e,{value:r(!0),items:l(i)}),o=r(!1)},indices(i){const s=new Set(i.detail.indices);for(const t of i.target.options)t.selected=s.has(t.index);t.setValue(e,{value:r(!0)}),o=r(!1)},editable(t){t.target.disabled=!t.detail.editable}};this._dispatchEventFromSandbox(n,i)})),s.addEventListener("input",(i=>{const s=r(!0),n=r(!1);t.setValue(e,{value:s}),i.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:o,change:n,changeEx:s,willCommit:!1,commitKey:1,keyDown:!1}})})),this._setEventListeners(s,null,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"],["input","Action"],["input","Validate"]],(t=>t.target.value))):s.addEventListener("input",(function(i){t.setValue(e,{value:r(!0)})})),this.data.combo&&this._setTextStyle(s),this._setBackgroundColor(s),this._setDefaultPropertiesFromJS(s),this.container.append(s),this.container}}class Oi extends Ti{constructor(t){const{data:e,elements:i}=t;super(t,{isRenderable:Ti._hasPopupData(e)}),this.elements=i,this.popup=null}render(){this.container.classList.add("popupAnnotation");const t=this.popup=new Bi({container:this.container,color:this.data.color,titleObj:this.data.titleObj,modificationDate:this.data.modificationDate,contentsObj:this.data.contentsObj,richText:this.data.richText,rect:this.data.rect,parentRect:this.data.parentRect||null,parent:this.parent,elements:this.elements,open:this.data.open}),e=[];for(const i of this.elements)i.popup=t,e.push(i.data.id),i.addHighlightArea();return this.container.setAttribute("aria-controls",e.map((t=>`${W}${t}`)).join(",")),this.container}}class Bi{#As=this.#ys.bind(this);#ws=this.#_s.bind(this);#xs=this.#Cs.bind(this);#Es=this.#Ss.bind(this);#Ts=null;#ut=null;#Ms=null;#ks=null;#Is=null;#Ps=null;#Rs=null;#Ds=!1;#Ls=null;#S=null;#Fs=null;#Ns=null;#Os=null;#us=null;#Bs=!1;constructor({container:t,color:e,elements:i,titleObj:s,modificationDate:n,contentsObj:a,richText:r,parent:o,rect:l,parentRect:h,open:d}){this.#ut=t,this.#Os=s,this.#Ms=a,this.#Ns=r,this.#Ps=o,this.#Ts=e,this.#Fs=l,this.#Rs=h,this.#Is=i,this.#ks=pt.toDateObject(n),this.trigger=i.flatMap((t=>t.getElementsToTriggerPopup()));for(const t of this.trigger)t.addEventListener("click",this.#Es),t.addEventListener("mouseenter",this.#xs),t.addEventListener("mouseleave",this.#ws),t.classList.add("popupTriggerArea");for(const t of i)t.container?.addEventListener("keydown",this.#As);this.#ut.hidden=!0,d&&this.#Ss()}render(){if(this.#Ls)return;const t=this.#Ls=document.createElement("div");if(t.className="popup",this.#Ts){const e=t.style.outlineColor=H.makeHexColor(...this.#Ts);if(CSS.supports("background-color","color-mix(in srgb, red 30%, white)"))t.style.backgroundColor=`color-mix(in srgb, ${e} 30%, white)`;else{const e=.7;t.style.backgroundColor=H.makeHexColor(...this.#Ts.map((t=>Math.floor(e*(255-t)+t))))}}const e=document.createElement("span");e.className="header";const i=document.createElement("h1");if(e.append(i),({dir:i.dir,str:i.textContent}=this.#Os),t.append(e),this.#ks){const t=document.createElement("span");t.classList.add("popupDate"),t.setAttribute("data-l10n-id","pdfjs-annotation-date-time-string"),t.setAttribute("data-l10n-args",JSON.stringify({dateObj:this.#ks.valueOf()})),e.append(t)}const s=this.#zs;if(s)_i.render({xfaHtml:s,intent:"richText",div:t}),t.lastChild.classList.add("richText","popupContent");else{const e=this._formatContents(this.#Ms);t.append(e)}this.#ut.append(t)}get#zs(){const t=this.#Ns,e=this.#Ms;return!t?.str||e?.str&&e.str!==t.str?null:this.#Ns.html||null}get#Hs(){return this.#zs?.attributes?.style?.fontSize||0}get#js(){return this.#zs?.attributes?.style?.color||null}#Us(t){const e=[],i={str:t,html:{name:"div",attributes:{dir:"auto"},children:[{name:"p",children:e}]}},s={style:{color:this.#js,fontSize:this.#Hs?`calc(${this.#Hs}px * var(--scale-factor))`:""}};for(const i of t.split("\n"))e.push({name:"span",value:i,attributes:s});return i}_formatContents({str:t,dir:e}){const i=document.createElement("p");i.classList.add("popupContent"),i.dir=e;const s=t.split(/(?:\r\n?|\n)/);for(let t=0,e=s.length;t{"Enter"===t.key&&(s?t.metaKey:t.ctrlKey)&&this.#Ys()})),!e.popupRef&&this.hasPopupData?this._createPopup():i.classList.add("popupTriggerArea"),t.append(i),t}getElementsToTriggerPopup(){return this.#Ks}addHighlightArea(){this.container.classList.add("highlightArea")}#Ys(){this.downloadManager?.openOrDownloadData(this.content,this.filename)}}class Zi{#Qs=null;#Js=null;#Zs=new Map;#tn=null;constructor({div:t,accessibilityManager:e,annotationCanvasMap:i,annotationEditorUIManager:s,page:n,viewport:a,structTreeLayer:r}){this.div=t,this.#Qs=e,this.#Js=i,this.#tn=r||null,this.page=n,this.viewport=a,this.zIndex=0,this._annotationEditorUIManager=s}hasEditableAnnotations(){return this.#Zs.size>0}async#en(t,e){const i=t.firstChild||t,s=i.id=`${W}${e}`,n=await(this.#tn?.getAriaAttributes(s));if(n)for(const[t,e]of n)i.setAttribute(t,e);this.div.append(t),this.#Qs?.moveElementInDOM(this.div,t,i,!1)}async render(t){const{annotations:e}=t,i=this.div;vt(i,this.viewport);const s=new Map,n={data:null,layer:i,linkService:t.linkService,downloadManager:t.downloadManager,imageResourcesPath:t.imageResourcesPath||"",renderForms:!1!==t.renderForms,svgFactory:new et,annotationStorage:t.annotationStorage||new Ot,enableScripting:!0===t.enableScripting,hasJSActions:t.hasJSActions,fieldObjects:t.fieldObjects,parent:this,elements:null};for(const t of e){if(t.noHTML)continue;const e=16===t.annotationType;if(e){const e=s.get(t.id);if(!e)continue;n.elements=e}else{const{width:e,height:i}=Ei(t.rect);if(e<=0||i<=0)continue}n.data=t;const i=Si.create(n);if(!i.isRenderable)continue;if(!e&&t.popupRef){const e=s.get(t.popupRef);e?e.push(i):s.set(t.popupRef,[i])}const a=i.render();t.hidden&&(a.style.visibility="hidden"),await this.#en(a,t.id),i._isEditable&&(this.#Zs.set(i.data.id,i),this._annotationEditorUIManager?.renderAnnotationElement(i))}this.#in()}update({viewport:t}){const e=this.div;this.viewport=t,vt(e,{rotation:t.rotation}),this.#in(),e.hidden=!1}#in(){if(!this.#Js)return;const t=this.div;for(const[e,i]of this.#Js){const s=t.querySelector(`[data-annotation-id="${e}"]`);if(!s)continue;i.className="annotationContent";const{firstChild:n}=s;n?"CANVAS"===n.nodeName?n.replaceWith(i):n.classList.contains("annotationContent")?n.after(i):n.before(i):s.append(i)}this.#Js.clear()}getEditableAnnotations(){return Array.from(this.#Zs.values())}getEditableAnnotation(t){return this.#Zs.get(t)}}const ts=/\r\n?|\n/g;class es extends It{#Ts;#sn="";#nn=`${this.id}-editor`;#an=null;#Hs;static _freeTextDefaultContent="";static _internalPadding=0;static _defaultColor=null;static _defaultFontSize=10;static get _keyboardManager(){const t=es.prototype,e=t=>t.isEmpty(),i=Mt.TRANSLATE_SMALL,s=Mt.TRANSLATE_BIG;return S(this,"_keyboardManager",new St([[["ctrl+s","mac+meta+s","ctrl+p","mac+meta+p"],t.commitOrRemove,{bubbles:!0}],[["ctrl+Enter","mac+meta+Enter","Escape","mac+Escape"],t.commitOrRemove],[["ArrowLeft","mac+ArrowLeft"],t._translateEmpty,{args:[-i,0],checker:e}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t._translateEmpty,{args:[-s,0],checker:e}],[["ArrowRight","mac+ArrowRight"],t._translateEmpty,{args:[i,0],checker:e}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t._translateEmpty,{args:[s,0],checker:e}],[["ArrowUp","mac+ArrowUp"],t._translateEmpty,{args:[0,-i],checker:e}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t._translateEmpty,{args:[0,-s],checker:e}],[["ArrowDown","mac+ArrowDown"],t._translateEmpty,{args:[0,i],checker:e}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t._translateEmpty,{args:[0,s],checker:e}]]))}static _type="freetext";static _editorType=d.FREETEXT;constructor(t){super({...t,name:"freeTextEditor"}),this.#Ts=t.color||es._defaultColor||It._defaultLineColor,this.#Hs=t.fontSize||es._defaultFontSize}static initialize(t,e){It.initialize(t,e,{strings:["pdfjs-free-text-default-content"]});const i=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(i.getPropertyValue("--freetext-padding"))}static updateDefaultParams(t,e){switch(t){case c.FREETEXT_SIZE:es._defaultFontSize=e;break;case c.FREETEXT_COLOR:es._defaultColor=e}}updateParams(t,e){switch(t){case c.FREETEXT_SIZE:this.#rn(e);break;case c.FREETEXT_COLOR:this.#on(e)}}static get defaultPropertiesToUpdate(){return[[c.FREETEXT_SIZE,es._defaultFontSize],[c.FREETEXT_COLOR,es._defaultColor||It._defaultLineColor]]}get propertiesToUpdate(){return[[c.FREETEXT_SIZE,this.#Hs],[c.FREETEXT_COLOR,this.#Ts]]}#rn(t){const e=t=>{this.editorDiv.style.fontSize=`calc(${t}px * var(--scale-factor))`,this.translate(0,-(t-this.#Hs)*this.parentScale),this.#Hs=t,this.#ln()},i=this.#Hs;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:c.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})}#on(t){const e=t=>{this.#Ts=this.editorDiv.style.color=t},i=this.#Ts;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:c.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})}_translateEmpty(t,e){this._uiManager.translateSelectedEditors(t,e,!0)}getInitialTranslation(){const t=this.parentScale;return[-es._internalPadding*t,-(es._internalPadding+this.#Hs)*t]}rebuild(){this.parent&&(super.rebuild(),null!==this.div&&(this.isAttachedToDOM||this.parent.add(this)))}enableEditMode(){if(this.isInEditMode())return;this.parent.setEditingState(!1),this.parent.updateToolbar(d.FREETEXT),super.enableEditMode(),this.overlayDiv.classList.remove("enabled"),this.editorDiv.contentEditable=!0,this._isDraggable=!1,this.div.removeAttribute("aria-activedescendant"),this.#an=new AbortController;const t=this._uiManager.combinedSignal(this.#an);this.editorDiv.addEventListener("keydown",this.editorDivKeydown.bind(this),{signal:t}),this.editorDiv.addEventListener("focus",this.editorDivFocus.bind(this),{signal:t}),this.editorDiv.addEventListener("blur",this.editorDivBlur.bind(this),{signal:t}),this.editorDiv.addEventListener("input",this.editorDivInput.bind(this),{signal:t}),this.editorDiv.addEventListener("paste",this.editorDivPaste.bind(this),{signal:t})}disableEditMode(){this.isInEditMode()&&(this.parent.setEditingState(!0),super.disableEditMode(),this.overlayDiv.classList.add("enabled"),this.editorDiv.contentEditable=!1,this.div.setAttribute("aria-activedescendant",this.#nn),this._isDraggable=!0,this.#an?.abort(),this.#an=null,this.div.focus({preventScroll:!0}),this.isEditing=!1,this.parent.div.classList.add("freetextEditing"))}focusin(t){this._focusEventsAllowed&&(super.focusin(t),t.target!==this.editorDiv&&this.editorDiv.focus())}onceAdded(){this.width||(this.enableEditMode(),this.editorDiv.focus(),this._initialOptions?.isCentered&&this.center(),this._initialOptions=null)}isEmpty(){return!this.editorDiv||""===this.editorDiv.innerText.trim()}remove(){this.isEditing=!1,this.parent&&(this.parent.setEditingState(!0),this.parent.div.classList.add("freetextEditing")),super.remove()}#hn(){const t=[];this.editorDiv.normalize();let e=null;for(const i of this.editorDiv.childNodes)e?.nodeType===Node.TEXT_NODE&&"BR"===i.nodeName||(t.push(es.#dn(i)),e=i);return t.join("\n")}#ln(){const[t,e]=this.parentDimensions;let i;if(this.isAttachedToDOM)i=this.div.getBoundingClientRect();else{const{currentLayer:t,div:e}=this,s=e.style.display,n=e.classList.contains("hidden");e.classList.remove("hidden"),e.style.display="hidden",t.div.append(this.div),i=e.getBoundingClientRect(),e.remove(),e.style.display=s,e.classList.toggle("hidden",n)}this.rotation%180==this.parentRotation%180?(this.width=i.width/t,this.height=i.height/e):(this.width=i.height/t,this.height=i.width/e),this.fixAndSetPosition()}commit(){if(!this.isInEditMode())return;super.commit(),this.disableEditMode();const t=this.#sn,e=this.#sn=this.#hn().trimEnd();if(t===e)return;const i=t=>{this.#sn=t,t?(this.#cn(),this._uiManager.rebuild(this),this.#ln()):this.remove()};this.addCommands({cmd:()=>{i(e)},undo:()=>{i(t)},mustExec:!1}),this.#ln()}shouldGetKeyboardEvents(){return this.isInEditMode()}enterInEditMode(){this.enableEditMode(),this.editorDiv.focus()}dblclick(t){this.enterInEditMode()}keydown(t){t.target===this.div&&"Enter"===t.key&&(this.enterInEditMode(),t.preventDefault())}editorDivKeydown(t){es._keyboardManager.exec(this,t)}editorDivFocus(t){this.isEditing=!0}editorDivBlur(t){this.isEditing=!1}editorDivInput(t){this.parent.div.classList.toggle("freetextEditing",this.isEmpty())}disableEditing(){this.editorDiv.setAttribute("role","comment"),this.editorDiv.removeAttribute("aria-multiline")}enableEditing(){this.editorDiv.setAttribute("role","textbox"),this.editorDiv.setAttribute("aria-multiline",!0)}render(){if(this.div)return this.div;let t,e;this.width&&(t=this.x,e=this.y),super.render(),this.editorDiv=document.createElement("div"),this.editorDiv.className="internal",this.editorDiv.setAttribute("id",this.#nn),this.editorDiv.setAttribute("data-l10n-id","pdfjs-free-text"),this.enableEditing(),It._l10nPromise.get("pdfjs-free-text-default-content").then((t=>this.editorDiv?.setAttribute("default-content",t))),this.editorDiv.contentEditable=!0;const{style:i}=this.editorDiv;if(i.fontSize=`calc(${this.#Hs}px * var(--scale-factor))`,i.color=this.#Ts,this.div.append(this.editorDiv),this.overlayDiv=document.createElement("div"),this.overlayDiv.classList.add("overlay","enabled"),this.div.append(this.overlayDiv),_t(this,this.div,["dblclick","keydown"]),this.width){const[i,s]=this.parentDimensions;if(this.annotationElementId){const{position:n}=this._initialData;let[a,r]=this.getInitialTranslation();[a,r]=this.pageTranslationToScreen(a,r);const[o,l]=this.pageDimensions,[h,d]=this.pageTranslation;let c,u;switch(this.rotation){case 0:c=t+(n[0]-h)/o,u=e+this.height-(n[1]-d)/l;break;case 90:c=t+(n[0]-h)/o,u=e-(n[1]-d)/l,[a,r]=[r,-a];break;case 180:c=t-this.width+(n[0]-h)/o,u=e-(n[1]-d)/l,[a,r]=[-a,-r];break;case 270:c=t+(n[0]-h-this.height*l)/o,u=e+(n[1]-d-this.width*o)/l,[a,r]=[-r,a]}this.setAt(c*i,u*s,a,r)}else this.setAt(t*i,e*s,this.width*i,this.height*s);this.#cn(),this._isDraggable=!0,this.editorDiv.contentEditable=!1}else this._isDraggable=!1,this.editorDiv.contentEditable=!0;return this.div}static#dn(t){return(t.nodeType===Node.TEXT_NODE?t.nodeValue:t.innerText).replaceAll(ts,"")}editorDivPaste(t){const e=t.clipboardData||window.clipboardData,{types:i}=e;if(1===i.length&&"text/plain"===i[0])return;t.preventDefault();const s=es.#un(e.getData("text")||"").replaceAll(ts,"\n");if(!s)return;const n=window.getSelection();if(!n.rangeCount)return;this.editorDiv.normalize(),n.deleteFromDocument();const a=n.getRangeAt(0);if(!s.includes("\n"))return a.insertNode(document.createTextNode(s)),this.editorDiv.normalize(),void n.collapseToStart();const{startContainer:r,startOffset:o}=a,l=[],h=[];if(r.nodeType===Node.TEXT_NODE){const t=r.parentElement;if(h.push(r.nodeValue.slice(o).replaceAll(ts,"")),t!==this.editorDiv){let e=l;for(const i of this.editorDiv.childNodes)i!==t?e.push(es.#dn(i)):e=h}l.push(r.nodeValue.slice(0,o).replaceAll(ts,""))}else if(r===this.editorDiv){let t=l,e=0;for(const i of this.editorDiv.childNodes)e++===o&&(t=h),t.push(es.#dn(i))}this.#sn=`${l.join("\n")}${s}${h.join("\n")}`,this.#cn();const d=new Range;let c=l.reduce(((t,e)=>t+e.length),0);for(const{firstChild:t}of this.editorDiv.childNodes)if(t.nodeType===Node.TEXT_NODE){const e=t.nodeValue.length;if(c<=e){d.setStart(t,c),d.setEnd(t,c);break}c-=e}n.removeAllRanges(),n.addRange(d)}#cn(){if(this.editorDiv.replaceChildren(),this.#sn)for(const t of this.#sn.split("\n")){const e=document.createElement("div");e.append(t?document.createTextNode(t):document.createElement("br")),this.editorDiv.append(e)}}#pn(){return this.#sn.replaceAll(" "," ")}static#un(t){return t.replaceAll(" "," ")}get contentDiv(){return this.editorDiv}static async deserialize(t,e,i){let s=null;if(t instanceof zi){const{data:{defaultAppearanceData:{fontSize:e,fontColor:i},rect:n,rotation:a,id:r,popupRef:o},textContent:l,textPosition:h,parent:{page:{pageNumber:c}}}=t;if(!l||0===l.length)return null;s=t={annotationType:d.FREETEXT,color:Array.from(i),fontSize:e,value:l.join("\n"),position:h,pageIndex:c-1,rect:n.slice(0),rotation:a,id:r,deleted:!1,popupRef:o}}const n=await super.deserialize(t,e,i);return n.#Hs=t.fontSize,n.#Ts=H.makeHexColor(...t.color),n.#sn=es.#un(t.value),n.annotationElementId=t.id||null,n._initialData=s,n}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const e=es._internalPadding*this.parentScale,i=this.getRect(e,e),s=It._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:this.#Ts),n={annotationType:d.FREETEXT,color:s,fontSize:this.#Hs,value:this.#pn(),pageIndex:this.pageIndex,rect:i,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return t?n:this.annotationElementId&&!this.#gn(n)?null:(n.id=this.annotationElementId,n)}#gn(t){const{value:e,fontSize:i,color:s,pageIndex:n}=this._initialData;return this._hasBeenMoved||t.value!==e||t.fontSize!==i||t.color.some(((t,e)=>t!==s[e]))||t.pageIndex!==n}renderAnnotationElement(t){const e=super.renderAnnotationElement(t);if(this.deleted)return e;const{style:i}=e;i.fontSize=`calc(${this.#Hs}px * var(--scale-factor))`,i.color=this.#Ts,e.replaceChildren();for(const t of this.#sn.split("\n")){const i=document.createElement("div");i.append(t?document.createTextNode(t):document.createElement("br")),e.append(i)}const s=es._internalPadding*this.parentScale;return t.updateEdited({rect:this.getRect(s,s),popupContent:this.#sn}),e}resetAnnotationElement(t){super.resetAnnotationElement(t),t.resetEdited()}}class is{#mn;#fn=[];#bn=[];constructor(t,e=0,i=0,s=!0){let n=1/0,a=-1/0,r=1/0,o=-1/0;const l=10**-4;for(const{x:i,y:s,width:h,height:d}of t){const t=Math.floor((i-e)/l)*l,c=Math.ceil((i+h+e)/l)*l,u=Math.floor((s-e)/l)*l,p=Math.ceil((s+d+e)/l)*l,g=[t,u,p,!0],m=[c,u,p,!1];this.#fn.push(g,m),n=Math.min(n,t),a=Math.max(a,c),r=Math.min(r,u),o=Math.max(o,p)}const h=a-n+2*i,d=o-r+2*i,c=n-i,u=r-i,p=this.#fn.at(s?-1:-2),g=[p[0],p[2]];for(const t of this.#fn){const[e,i,s]=t;t[0]=(e-c)/h,t[1]=(i-u)/d,t[2]=(s-u)/d}this.#mn={x:c,y:u,width:h,height:d,lastPoint:g}}getOutlines(){this.#fn.sort(((t,e)=>t[0]-e[0]||t[1]-e[1]||t[2]-e[2]));const t=[];for(const e of this.#fn)e[3]?(t.push(...this.#vn(e)),this.#An(e)):(this.#yn(e),t.push(...this.#vn(e)));return this.#wn(t)}#wn(t){const e=[],i=new Set;for(const i of t){const[t,s,n]=i;e.push([t,s,i],[t,n,i])}e.sort(((t,e)=>t[1]-e[1]||t[0]-e[0]));for(let t=0,s=e.length;t0;){const t=i.values().next().value;let[e,a,r,o,l]=t;i.delete(t);let h=e,d=a;for(n=[e,r],s.push(n);;){let t;if(i.has(o))t=o;else{if(!i.has(l))break;t=l}i.delete(t),[e,a,r,o,l]=t,h!==e&&(n.push(h,d,e,d===a?a:r),h=e),d=d===a?r:a}n.push(h,d)}return new ns(s,this.#mn)}#_n(t){const e=this.#bn;let i=0,s=e.length-1;for(;i<=s;){const n=i+s>>1,a=e[n][0];if(a===t)return n;a=0;s--){const[i,n]=this.#bn[s];if(i!==t)break;if(i===t&&n===e)return void this.#bn.splice(s,1)}}#vn(t){const[e,i,s]=t,n=[[e,i,s]],a=this.#_n(s);for(let t=0;t=i)if(o>s)n[t][1]=s;else{if(1===a)return[];n.splice(t,1),t--,a--}else n[t][2]=i,o>s&&n.push([e,s,o])}}return n}}class ss{toSVGPath(){throw new Error("Abstract method `toSVGPath` must be implemented.")}get box(){throw new Error("Abstract getter `box` must be implemented.")}serialize(t,e){throw new Error("Abstract method `serialize` must be implemented.")}get free(){return this instanceof rs}}class ns extends ss{#mn;#xn;constructor(t,e){super(),this.#xn=t,this.#mn=e}toSVGPath(){const t=[];for(const e of this.#xn){let[i,s]=e;t.push(`M${i} ${s}`);for(let n=2;n=6;t-=6)isNaN(e[t])?u.push(`L${e[t+4]} ${e[t+5]}`):u.push(`C${e[t]} ${e[t+1]} ${e[t+2]} ${e[t+3]} ${e[t+4]} ${e[t+5]}`);return u.push(`L${e[4]} ${e[5]} Z`),u.join(" ")}getOutlines(){const t=this.#Tn,e=this.#Cn,i=this.#Mn,s=i.subarray(4,6),n=i.subarray(16,18),[a,r,o,l]=this.#mn,h=new Float64Array((this.#Fn?.length??0)+2);for(let t=0,e=h.length-2;t=6;t-=6)for(let i=0;i<6;i+=2)isNaN(e[t+i])?(g[m]=g[m+1]=NaN,m+=2):(g[m]=e[t+i],g[m+1]=e[t+i+1],m+=2);return g.set([NaN,NaN,NaN,NaN,e[4],e[5]],m),new rs(g,h,this.#mn,this.#Dn,this.#En,this.#Sn)}}class rs extends ss{#mn;#Hn=null;#En;#Sn;#Fn;#Dn;#jn;constructor(t,e,i,s,n,a){super(),this.#jn=t,this.#Fn=e,this.#mn=i,this.#Dn=s,this.#En=n,this.#Sn=a,this.#Un(a);const{x:r,y:o,width:l,height:h}=this.#Hn;for(let e=0,i=t.length;e-1?(this.#ga=!0,this.#ya(t),this.#wa()):this.#oa&&(this.#aa=t.anchorNode,this.#ra=t.anchorOffset,this.#da=t.focusNode,this.#ca=t.focusOffset,this.#_a(),this.#wa(),this.rotate(this.rotation))}get telemetryInitialData(){return{action:"added",type:this.#ga?"free_highlight":"highlight",color:this._uiManager.highlightColorNames.get(this.color),thickness:this.#Ln,methodOfCreation:this.#Aa}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.highlightColorNames.get(this.color)}}static computeTelemetryFinalData(t){return{numberOfColors:t.get("color").size}}#_a(){const t=new is(this.#oa,.001);this.#pa=t.getOutlines(),({x:this.x,y:this.y,width:this.width,height:this.height}=this.#pa.box);const e=new is(this.#oa,.0025,.001,"ltr"===this._uiManager.direction);this.#ha=e.getOutlines();const{lastPoint:i}=this.#ha.box;this.#ma=[(i[0]-this.x)/this.width,(i[1]-this.y)/this.height]}#ya({highlightOutlines:t,highlightId:e,clipPathId:i}){if(this.#pa=t,this.#ha=t.getNewOutline(this.#Ln/2+1.5,.0025),e>=0)this.#A=e,this.#la=i,this.parent.drawLayer.finalizeLine(e,t),this.#ba=this.parent.drawLayer.highlightOutline(this.#ha);else if(this.parent){const e=this.parent.viewport.rotation;this.parent.drawLayer.updateLine(this.#A,t),this.parent.drawLayer.updateBox(this.#A,ls.#xa(this.#pa.box,(e-this.rotation+360)%360)),this.parent.drawLayer.updateLine(this.#ba,this.#ha),this.parent.drawLayer.updateBox(this.#ba,ls.#xa(this.#ha.box,e))}const{x:s,y:n,width:a,height:r}=t.box;switch(this.rotation){case 0:this.x=s,this.y=n,this.width=a,this.height=r;break;case 90:{const[t,e]=this.parentDimensions;this.x=n,this.y=1-s,this.width=a*e/t,this.height=r*t/e;break}case 180:this.x=1-s,this.y=1-n,this.width=a,this.height=r;break;case 270:{const[t,e]=this.parentDimensions;this.x=1-n,this.y=s,this.width=a*e/t,this.height=r*t/e;break}}const{lastPoint:o}=this.#ha.box;this.#ma=[(o[0]-s)/a,(o[1]-n)/r]}static initialize(t,e){It.initialize(t,e),ls._defaultColor||=e.highlightColors?.values().next().value||"#fff066"}static updateDefaultParams(t,e){switch(t){case c.HIGHLIGHT_DEFAULT_COLOR:ls._defaultColor=e;break;case c.HIGHLIGHT_THICKNESS:ls._defaultThickness=e}}translateInPage(t,e){}get toolbarPosition(){return this.#ma}updateParams(t,e){switch(t){case c.HIGHLIGHT_COLOR:this.#on(e);break;case c.HIGHLIGHT_THICKNESS:this.#Ca(e)}}static get defaultPropertiesToUpdate(){return[[c.HIGHLIGHT_DEFAULT_COLOR,ls._defaultColor],[c.HIGHLIGHT_THICKNESS,ls._defaultThickness]]}get propertiesToUpdate(){return[[c.HIGHLIGHT_COLOR,this.color||ls._defaultColor],[c.HIGHLIGHT_THICKNESS,this.#Ln||ls._defaultThickness],[c.HIGHLIGHT_FREE,this.#ga]]}#on(t){const e=(t,e)=>{this.color=t,this.parent?.drawLayer.changeColor(this.#A,t),this.#n?.updateColor(t),this.#fa=e,this.parent?.drawLayer.changeOpacity(this.#A,e)},i=this.color,s=this.#fa;this.addCommands({cmd:e.bind(this,t,ls._defaultOpacity),undo:e.bind(this,i,s),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:c.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"color_changed",color:this._uiManager.highlightColorNames.get(t)},!0)}#Ca(t){const e=this.#Ln,i=t=>{this.#Ln=t,this.#Ea(t)};this.addCommands({cmd:i.bind(this,t),undo:i.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:c.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"thickness_changed",thickness:t},!0)}async addEditToolbar(){const t=await super.addEditToolbar();return t?(this._uiManager.highlightColors&&(this.#n=new os({editor:this}),t.addColorPicker(this.#n)),t):null}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(this.#Sa())}getBaseTranslation(){return[0,0]}getRect(t,e){return super.getRect(t,e,this.#Sa())}onceAdded(){this.annotationElementId||this.parent.addUndoableEditor(this),this.div.focus()}remove(){this.#Ta(),this._reportTelemetry({action:"deleted"}),super.remove()}rebuild(){this.parent&&(super.rebuild(),null!==this.div&&(this.#wa(),this.isAttachedToDOM||this.parent.add(this)))}setParent(t){let e=!1;this.parent&&!t?this.#Ta():t&&(this.#wa(t),e=!this.parent&&this.div?.classList.contains("selectedEditor")),super.setParent(t),this.show(this._isVisible),e&&this.select()}#Ea(t){if(!this.#ga)return;this.#ya({highlightOutlines:this.#pa.getNewOutline(t/2)}),this.fixAndSetPosition();const[e,i]=this.parentDimensions;this.setDims(this.width*e,this.height*i)}#Ta(){null!==this.#A&&this.parent&&(this.parent.drawLayer.remove(this.#A),this.#A=null,this.parent.drawLayer.remove(this.#ba),this.#ba=null)}#wa(t=this.parent){null===this.#A&&(({id:this.#A,clipPathId:this.#la}=t.drawLayer.highlight(this.#pa,this.color,this.#fa)),this.#ba=t.drawLayer.highlightOutline(this.#ha),this.#ua&&(this.#ua.style.clipPath=this.#la))}static#xa({x:t,y:e,width:i,height:s},n){switch(n){case 90:return{x:1-e-s,y:t,width:s,height:i};case 180:return{x:1-t-i,y:1-e-s,width:i,height:s};case 270:return{x:e,y:1-t-i,width:s,height:i}}return{x:t,y:e,width:i,height:s}}rotate(t){const{drawLayer:e}=this.parent;let i;this.#ga?(t=(t-this.rotation+360)%360,i=ls.#xa(this.#pa.box,t)):i=ls.#xa(this,t),e.rotate(this.#A,t),e.rotate(this.#ba,t),e.updateBox(this.#A,i),e.updateBox(this.#ba,ls.#xa(this.#ha.box,t))}render(){if(this.div)return this.div;const t=super.render();this.#va&&(t.setAttribute("aria-label",this.#va),t.setAttribute("role","mark")),this.#ga?t.classList.add("free"):this.div.addEventListener("keydown",this.#Ma.bind(this),{signal:this._uiManager._signal});const e=this.#ua=document.createElement("div");t.append(e),e.setAttribute("aria-hidden","true"),e.className="internal",e.style.clipPath=this.#la;const[i,s]=this.parentDimensions;return this.setDims(this.width*i,this.height*s),_t(this,this.#ua,["pointerover","pointerleave"]),this.enableEditing(),t}pointerover(){this.parent.drawLayer.addClass(this.#ba,"hovered")}pointerleave(){this.parent.drawLayer.removeClass(this.#ba,"hovered")}#Ma(t){ls._keyboardManager.exec(this,t)}_moveCaret(t){switch(this.parent.unselect(this),t){case 0:case 2:this.#ka(!0);break;case 1:case 3:this.#ka(!1)}}#ka(t){if(!this.#aa)return;const e=window.getSelection();t?e.setPosition(this.#aa,this.#ra):e.setPosition(this.#da,this.#ca)}select(){super.select(),this.#ba&&(this.parent?.drawLayer.removeClass(this.#ba,"hovered"),this.parent?.drawLayer.addClass(this.#ba,"selected"))}unselect(){super.unselect(),this.#ba&&(this.parent?.drawLayer.removeClass(this.#ba,"selected"),this.#ga||this.#ka(!1))}get _mustFixPosition(){return!this.#ga}show(t=this._isVisible){super.show(t),this.parent&&(this.parent.drawLayer.show(this.#A,t),this.parent.drawLayer.show(this.#ba,t))}#Sa(){return this.#ga?this.rotation:0}#Ia(){if(this.#ga)return null;const[t,e]=this.pageDimensions,[i,s]=this.pageTranslation,n=this.#oa,a=new Float32Array(8*n.length);let r=0;for(const{x:o,y:l,width:h,height:d}of n){const n=o*t+i,c=(1-l-d)*e+s;a[r]=a[r+4]=n,a[r+1]=a[r+3]=c,a[r+2]=a[r+6]=n+h*t,a[r+5]=a[r+7]=c+d*e,r+=8}return a}#Pa(t){return this.#pa.serialize(t,this.#Sa())}static startHighlighting(t,e,{target:i,x:s,y:n}){const{x:a,y:r,width:o,height:l}=i.getBoundingClientRect(),h=new AbortController,d=t.combinedSignal(h),c=e=>{h.abort(),this.#Ra(t,e)};window.addEventListener("blur",c,{signal:d}),window.addEventListener("pointerup",c,{signal:d}),window.addEventListener("pointerdown",(t=>{t.preventDefault(),t.stopPropagation()}),{capture:!0,passive:!1,signal:d}),window.addEventListener("contextmenu",dt,{signal:d}),i.addEventListener("pointermove",this.#Da.bind(this,t),{signal:d}),this._freeHighlight=new as({x:s,y:n},[a,r,o,l],t.scale,this._defaultThickness/2,e,.001),({id:this._freeHighlightId,clipPathId:this._freeHighlightClipId}=t.drawLayer.highlight(this._freeHighlight,this._defaultColor,this._defaultOpacity,!0))}static#Da(t,e){this._freeHighlight.add(e)&&t.drawLayer.updatePath(this._freeHighlightId,this._freeHighlight)}static#Ra(t,e){this._freeHighlight.isEmpty()?t.drawLayer.removeFreeHighlight(this._freeHighlightId):t.createAndAddNewEditor(e,!1,{highlightId:this._freeHighlightId,highlightOutlines:this._freeHighlight.getOutlines(),clipPathId:this._freeHighlightClipId,methodOfCreation:"main_toolbar"}),this._freeHighlightId=-1,this._freeHighlight=null,this._freeHighlightClipId=""}static async deserialize(t,e,i){let s=null;if(t instanceof qi){const{data:{quadPoints:e,rect:i,rotation:n,id:a,color:r,opacity:o,popupRef:l},parent:{page:{pageNumber:h}}}=t;s=t={annotationType:d.HIGHLIGHT,color:Array.from(r),opacity:o,quadPoints:e,boxes:null,pageIndex:h-1,rect:i.slice(0),rotation:n,id:a,deleted:!1,popupRef:l}}else if(t instanceof Vi){const{data:{inkLists:e,rect:i,rotation:n,id:a,color:r,borderStyle:{rawWidth:o},popupRef:l},parent:{page:{pageNumber:h}}}=t;s=t={annotationType:d.HIGHLIGHT,color:Array.from(r),thickness:o,inkLists:e,boxes:null,pageIndex:h-1,rect:i.slice(0),rotation:n,id:a,deleted:!1,popupRef:l}}const{color:n,quadPoints:a,inkLists:r,opacity:o}=t,l=await super.deserialize(t,e,i);l.color=H.makeHexColor(...n),l.#fa=o||1,r&&(l.#Ln=t.thickness),l.annotationElementId=t.id||null,l._initialData=s;const[h,c]=l.pageDimensions,[u,p]=l.pageTranslation;if(a){const t=l.#oa=[];for(let e=0;et!==e[i]))}renderAnnotationElement(t){return t.updateEdited({rect:this.getRect(0,0)}),null}static canCreateNewEmptyEditor(){return!1}}class hs extends It{#La=0;#Fa=0;#Na=null;#Oa=new Path2D;#Ba=!1;#za=null;#Ha=!1;#ja=!1;#Ua=null;#$a=null;#Wa=0;#Ga=0;#Va=null;static _defaultColor=null;static _defaultOpacity=1;static _defaultThickness=1;static _type="ink";static _editorType=d.INK;constructor(t){super({...t,name:"inkEditor"}),this.color=t.color||null,this.thickness=t.thickness||null,this.opacity=t.opacity||null,this.paths=[],this.bezierPath2D=[],this.allRawPaths=[],this.currentPath=[],this.scaleFactor=1,this.translationX=this.translationY=0,this.x=0,this.y=0,this._willKeepAspectRatio=!0}static initialize(t,e){It.initialize(t,e)}static updateDefaultParams(t,e){switch(t){case c.INK_THICKNESS:hs._defaultThickness=e;break;case c.INK_COLOR:hs._defaultColor=e;break;case c.INK_OPACITY:hs._defaultOpacity=e/100}}updateParams(t,e){switch(t){case c.INK_THICKNESS:this.#Ca(e);break;case c.INK_COLOR:this.#on(e);break;case c.INK_OPACITY:this.#qa(e)}}static get defaultPropertiesToUpdate(){return[[c.INK_THICKNESS,hs._defaultThickness],[c.INK_COLOR,hs._defaultColor||It._defaultLineColor],[c.INK_OPACITY,Math.round(100*hs._defaultOpacity)]]}get propertiesToUpdate(){return[[c.INK_THICKNESS,this.thickness||hs._defaultThickness],[c.INK_COLOR,this.color||hs._defaultColor||It._defaultLineColor],[c.INK_OPACITY,Math.round(100*(this.opacity??hs._defaultOpacity))]]}#Ca(t){const e=t=>{this.thickness=t,this.#Xa()},i=this.thickness;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:c.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0})}#on(t){const e=t=>{this.color=t,this.#Ka()},i=this.color;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:c.INK_COLOR,overwriteIfSameType:!0,keepUndo:!0})}#qa(t){const e=t=>{this.opacity=t,this.#Ka()};t/=100;const i=this.opacity;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:c.INK_OPACITY,overwriteIfSameType:!0,keepUndo:!0})}rebuild(){this.parent&&(super.rebuild(),null!==this.div&&(this.canvas||(this.#Ya(),this.#Qa()),this.isAttachedToDOM||(this.parent.add(this),this.#Ja()),this.#Xa()))}remove(){null!==this.canvas&&(this.isEmpty()||this.commit(),this.canvas.width=this.canvas.height=0,this.canvas.remove(),this.canvas=null,this.#Na&&(clearTimeout(this.#Na),this.#Na=null),this.#Ua?.disconnect(),this.#Ua=null,super.remove())}setParent(t){!this.parent&&t?this._uiManager.removeShouldRescale(this):this.parent&&null===t&&this._uiManager.addShouldRescale(this),super.setParent(t)}onScaleChanging(){const[t,e]=this.parentDimensions,i=this.width*t,s=this.height*e;this.setDimensions(i,s)}enableEditMode(){this.#Ba||null===this.canvas||(super.enableEditMode(),this._isDraggable=!1,this.#Za())}disableEditMode(){this.isInEditMode()&&null!==this.canvas&&(super.disableEditMode(),this._isDraggable=!this.isEmpty(),this.div.classList.remove("editing"),this.#tr())}onceAdded(){this._isDraggable=!this.isEmpty()}isEmpty(){return 0===this.paths.length||1===this.paths.length&&0===this.paths[0].length}#er(){const{parentRotation:t,parentDimensions:[e,i]}=this;switch(t){case 90:return[0,i,i,e];case 180:return[e,i,e,i];case 270:return[e,0,i,e];default:return[0,0,e,i]}}#ir(){const{ctx:t,color:e,opacity:i,thickness:s,parentScale:n,scaleFactor:a}=this;t.lineWidth=s*n/a,t.lineCap="round",t.lineJoin="round",t.miterLimit=10,t.strokeStyle=`${e}${function(t){return Math.round(Math.min(255,Math.max(1,255*t))).toString(16).padStart(2,"0")}(i)}`}#sr(t,e){this.canvas.addEventListener("contextmenu",dt,{signal:this._uiManager._signal}),this.#tr(),this.#za=new AbortController;const i=this._uiManager.combinedSignal(this.#za);this.canvas.addEventListener("pointerleave",this.canvasPointerleave.bind(this),{signal:i}),this.canvas.addEventListener("pointermove",this.canvasPointermove.bind(this),{signal:i}),this.canvas.addEventListener("pointerup",this.canvasPointerup.bind(this),{signal:i}),this.isEditing=!0,this.#ja||(this.#ja=!0,this.#Ja(),this.thickness||=hs._defaultThickness,this.color||=hs._defaultColor||It._defaultLineColor,this.opacity??=hs._defaultOpacity),this.currentPath.push([t,e]),this.#Ha=!1,this.#ir(),this.#Va=()=>{this.#nr(),this.#Va&&window.requestAnimationFrame(this.#Va)},window.requestAnimationFrame(this.#Va)}#ar(t,e){const[i,s]=this.currentPath.at(-1);if(this.currentPath.length>1&&t===i&&e===s)return;const n=this.currentPath;let a=this.#Oa;if(n.push([t,e]),this.#Ha=!0,n.length<=2)return a.moveTo(...n[0]),void a.lineTo(t,e);3===n.length&&(this.#Oa=a=new Path2D,a.moveTo(...n[0])),this.#rr(a,...n.at(-3),...n.at(-2),t,e)}#or(){if(0===this.currentPath.length)return;const t=this.currentPath.at(-1);this.#Oa.lineTo(...t)}#lr(t,e){let i;if(this.#Va=null,t=Math.min(Math.max(t,0),this.canvas.width),e=Math.min(Math.max(e,0),this.canvas.height),this.#ar(t,e),this.#or(),1!==this.currentPath.length)i=this.#hr();else{const s=[t,e];i=[[s,s.slice(),s.slice(),s]]}const s=this.#Oa,n=this.currentPath;this.currentPath=[],this.#Oa=new Path2D,this.addCommands({cmd:()=>{this.allRawPaths.push(n),this.paths.push(i),this.bezierPath2D.push(s),this._uiManager.rebuild(this)},undo:()=>{this.allRawPaths.pop(),this.paths.pop(),this.bezierPath2D.pop(),0===this.paths.length?this.remove():(this.canvas||(this.#Ya(),this.#Qa()),this.#Xa())},mustExec:!0})}#nr(){if(!this.#Ha)return;this.#Ha=!1;Math.ceil(this.thickness*this.parentScale);const t=this.currentPath.slice(-3),e=t.map((t=>t[0])),i=t.map((t=>t[1])),{ctx:s}=(Math.min(...e),Math.max(...e),Math.min(...i),Math.max(...i),this);s.save(),s.clearRect(0,0,this.canvas.width,this.canvas.height);for(const t of this.bezierPath2D)s.stroke(t);s.stroke(this.#Oa),s.restore()}#rr(t,e,i,s,n,a,r){const o=(e+s)/2,l=(i+n)/2,h=(s+a)/2,d=(n+r)/2;t.bezierCurveTo(o+2*(s-o)/3,l+2*(n-l)/3,h+2*(s-h)/3,d+2*(n-d)/3,h,d)}#hr(){const t=this.currentPath;if(t.length<=2)return[[t[0],t[0],t.at(-1),t.at(-1)]];const e=[];let i,[s,n]=t[0];for(i=1;i{this.#Na=null,this.canvas.removeEventListener("contextmenu",dt)}),10),this.#lr(t.offsetX,t.offsetY),this.addToAnnotationStorage(),this.setInBackground()}#Ya(){this.canvas=document.createElement("canvas"),this.canvas.width=this.canvas.height=0,this.canvas.className="inkEditorCanvas",this.canvas.setAttribute("data-l10n-id","pdfjs-ink-canvas"),this.div.append(this.canvas),this.ctx=this.canvas.getContext("2d")}#Qa(){this.#Ua=new ResizeObserver((t=>{const e=t[0].contentRect;e.width&&e.height&&this.setDimensions(e.width,e.height)})),this.#Ua.observe(this.div),this._uiManager._signal.addEventListener("abort",(()=>{this.#Ua?.disconnect(),this.#Ua=null}),{once:!0})}get isResizable(){return!this.isEmpty()&&this.#Ba}render(){if(this.div)return this.div;let t,e;this.width&&(t=this.x,e=this.y),super.render(),this.div.setAttribute("data-l10n-id","pdfjs-ink");const[i,s,n,a]=this.#er();if(this.setAt(i,s,0,0),this.setDims(n,a),this.#Ya(),this.width){const[i,s]=this.parentDimensions;this.setAspectRatio(this.width*i,this.height*s),this.setAt(t*i,e*s,this.width*i,this.height*s),this.#ja=!0,this.#Ja(),this.setDims(this.width*i,this.height*s),this.#Ka(),this.div.classList.add("disabled")}else this.div.classList.add("editing"),this.enableEditMode();return this.#Qa(),this.div}#Ja(){if(!this.#ja)return;const[t,e]=this.parentDimensions;this.canvas.width=Math.ceil(this.width*t),this.canvas.height=Math.ceil(this.height*e),this.#dr()}setDimensions(t,e){const i=Math.round(t),s=Math.round(e);if(this.#Wa===i&&this.#Ga===s)return;this.#Wa=i,this.#Ga=s,this.canvas.style.visibility="hidden";const[n,a]=this.parentDimensions;this.width=t/n,this.height=e/a,this.fixAndSetPosition(),this.#Ba&&this.#ur(t,e),this.#Ja(),this.#Ka(),this.canvas.style.visibility="visible",this.fixDims()}#ur(t,e){const i=this.#pr(),s=(t-i)/this.#Fa,n=(e-i)/this.#La;this.scaleFactor=Math.min(s,n)}#dr(){const t=this.#pr()/2;this.ctx.setTransform(this.scaleFactor,0,0,this.scaleFactor,this.translationX*this.scaleFactor+t,this.translationY*this.scaleFactor+t)}static#gr(t){const e=new Path2D;for(let i=0,s=t.length;i`image/${t}`)))}static get supportedTypesStr(){return S(this,"supportedTypesStr",this.supportedTypes.join(","))}static isHandlingMimeForPasting(t){return this.supportedTypes.includes(t)}static paste(t,e){e.pasteEditor(d.STAMP,{bitmapFile:t.getAsFile()})}altTextFinish(){this._uiManager.useNewAltTextFlow&&(this.div.hidden=!1),super.altTextFinish()}get telemetryFinalData(){return{type:"stamp",hasAltText:!!this.altTextData?.altText}}static computeTelemetryFinalData(t){const e=t.get("hasAltText");return{hasAltText:e.get(!0)??0,hasNoAltText:e.get(!1)??0}}#kr(t,e=!1){t?(this.#Ar=t.bitmap,e||(this.#yr=t.id,this.#Tr=t.isSvg),t.file&&(this.#Cr=t.file.name),this.#Ya()):this.remove()}#Ir(){if(this.#wr=null,this._uiManager.enableWaiting(!1),this.#Er){if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#Ar)return this._editToolbar.hide(),void this._uiManager.editAltText(this,!0);if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#Ar){this._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:!1,alt_text_type:"empty"}});try{this.mlGuessAltText()}catch{}}this.div.focus()}}async mlGuessAltText(t=null,e=!0){if(this.hasAltTextData())return null;const{mlManager:i}=this._uiManager;if(!i)throw new Error("No ML.");if(!await i.isEnabledFor("altText"))throw new Error("ML isn't enabled for alt text.");const{data:s,width:n,height:a}=t||this.copyCanvas(null,null,!0).imageData,r=await i.guess({name:"altText",request:{data:s,width:n,height:a,channels:s.length/(n*a)}});if(!r)throw new Error("No response from the AI service.");if(r.error)throw new Error("Error from the AI service.");if(r.cancel)return null;if(!r.output)throw new Error("No valid response from the AI service.");const o=r.output;return await this.setGuessedAltText(o),e&&!this.hasAltTextData()&&(this.altTextData={alt:o,decorative:!1}),o}#Pr(){if(this.#yr)return this._uiManager.enableWaiting(!0),void this._uiManager.imageManager.getFromId(this.#yr).then((t=>this.#kr(t,!0))).finally((()=>this.#Ir()));if(this.#_r){const t=this.#_r;return this.#_r=null,this._uiManager.enableWaiting(!0),void(this.#wr=this._uiManager.imageManager.getFromUrl(t).then((t=>this.#kr(t))).finally((()=>this.#Ir())))}if(this.#xr){const t=this.#xr;return this.#xr=null,this._uiManager.enableWaiting(!0),void(this.#wr=this._uiManager.imageManager.getFromFile(t).then((t=>this.#kr(t))).finally((()=>this.#Ir())))}const t=document.createElement("input");t.type="file",t.accept=ds.supportedTypesStr;const e=this._uiManager._signal;this.#wr=new Promise((i=>{t.addEventListener("change",(async()=>{if(t.files&&0!==t.files.length){this._uiManager.enableWaiting(!0);const e=await this._uiManager.imageManager.getFromFile(t.files[0]);this._reportTelemetry({action:"pdfjs.image.image_selected",data:{alt_text_modal:this._uiManager.useNewAltTextFlow}}),this.#kr(e)}else this.remove();i()}),{signal:e}),t.addEventListener("cancel",(()=>{this.remove(),i()}),{signal:e})})).finally((()=>this.#Ir())),t.click()}remove(){this.#yr&&(this.#Ar=null,this._uiManager.imageManager.deleteId(this.#yr),this.#Er?.remove(),this.#Er=null,this.#Ua?.disconnect(),this.#Ua=null,this.#Sr&&(clearTimeout(this.#Sr),this.#Sr=null)),super.remove()}rebuild(){this.parent?(super.rebuild(),null!==this.div&&(this.#yr&&null===this.#Er&&this.#Pr(),this.isAttachedToDOM||this.parent.add(this))):this.#yr&&this.#Pr()}onceAdded(){this._isDraggable=!0,this.div.focus()}isEmpty(){return!(this.#wr||this.#Ar||this.#_r||this.#xr||this.#yr)}get isResizable(){return!0}render(){if(this.div)return this.div;let t,e;if(this.width&&(t=this.x,e=this.y),super.render(),this.div.hidden=!0,this.div.setAttribute("role","figure"),this.addAltTextButton(),this.#Ar?this.#Ya():this.#Pr(),this.width&&!this.annotationElementId){const[i,s]=this.parentDimensions;this.setAt(t*i,e*s,this.width*i,this.height*s)}return this.div}#Ya(){const{div:t}=this;let{width:e,height:i}=this.#Ar;const[s,n]=this.pageDimensions,a=.75;if(this.width)e=this.width*s,i=this.height*n;else if(e>a*s||i>a*n){const t=Math.min(a*s/e,a*n/i);e*=t,i*=t}const[r,o]=this.parentDimensions;this.setDims(e*r/s,i*o/n),this._uiManager.enableWaiting(!1);const l=this.#Er=document.createElement("canvas");l.setAttribute("role","img"),this.addContainer(l),this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&!this.annotationElementId||(t.hidden=!1),this.#Rr(e,i),this.#Qa(),this.#Mr||(this.parent.addUndoableEditor(this),this.#Mr=!0),this._reportTelemetry({action:"inserted_image"}),this.#Cr&&l.setAttribute("aria-label",this.#Cr)}copyCanvas(t,e,i=!1){t||(t=224);const{width:s,height:n}=this.#Ar,a=new At;let r=this.#Ar,o=s,l=n,h=null;if(e){if(s>e||n>e){const t=Math.min(e/s,e/n);o=Math.floor(s*t),l=Math.floor(n*t)}h=document.createElement("canvas");const t=h.width=Math.ceil(o*a.sx),i=h.height=Math.ceil(l*a.sy);this.#Tr||(r=this.#Dr(t,i));const d=h.getContext("2d");d.filter=this._uiManager.hcmFilter;let c="white",u="#cfcfd8";"none"!==this._uiManager.hcmFilter?u="black":window.matchMedia?.("(prefers-color-scheme: dark)").matches&&(c="#8f8f9d",u="#42414d");const p=15,g=p*a.sx,m=p*a.sy,f=new OffscreenCanvas(2*g,2*m),b=f.getContext("2d");b.fillStyle=c,b.fillRect(0,0,2*g,2*m),b.fillStyle=u,b.fillRect(0,0,g,m),b.fillRect(g,m,g,m),d.fillStyle=d.createPattern(f,"repeat"),d.fillRect(0,0,t,i),d.drawImage(r,0,0,r.width,r.height,0,0,t,i)}let d=null;if(i){let e,i;if(a.symmetric&&r.widtht||n>t){const a=Math.min(t/s,t/n);e=Math.floor(s*a),i=Math.floor(n*a),this.#Tr||(r=this.#Dr(e,i))}const o=new OffscreenCanvas(e,i).getContext("2d",{willReadFrequently:!0});o.drawImage(r,0,0,r.width,r.height,0,0,e,i),d={width:e,height:i,data:o.getImageData(0,0,e,i).data}}return{canvas:h,width:o,height:l,imageData:d}}#Lr(t,e){const[i,s]=this.parentDimensions;this.width=t/i,this.height=e/s,this._initialOptions?.isCentered?this.center():this.fixAndSetPosition(),this._initialOptions=null,null!==this.#Sr&&clearTimeout(this.#Sr),this.#Sr=setTimeout((()=>{this.#Sr=null,this.#Rr(t,e)}),200)}#Dr(t,e){const{width:i,height:s}=this.#Ar;let n=i,a=s,r=this.#Ar;for(;n>2*t||a>2*e;){const i=n,s=a;n>2*t&&(n=n>=16384?Math.floor(n/2)-1:Math.ceil(n/2)),a>2*e&&(a=a>=16384?Math.floor(a/2)-1:Math.ceil(a/2));const o=new OffscreenCanvas(n,a);o.getContext("2d").drawImage(r,0,0,i,s,0,0,n,a),r=o.transferToImageBitmap()}return r}#Rr(t,e){const i=new At,s=Math.ceil(t*i.sx),n=Math.ceil(e*i.sy),a=this.#Er;if(!a||a.width===s&&a.height===n)return;a.width=s,a.height=n;const r=this.#Tr?this.#Ar:this.#Dr(s,n),o=a.getContext("2d");o.filter=this._uiManager.hcmFilter,o.drawImage(r,0,0,r.width,r.height,0,0,s,n)}getImageForAltText(){return this.#Er}#Fr(t){if(t){if(this.#Tr){const t=this._uiManager.imageManager.getSvgUrl(this.#yr);if(t)return t}const t=document.createElement("canvas");return({width:t.width,height:t.height}=this.#Ar),t.getContext("2d").drawImage(this.#Ar,0,0),t.toDataURL()}if(this.#Tr){const[t,e]=this.pageDimensions,i=Math.round(this.width*t*Q.PDF_TO_CSS_UNITS),s=Math.round(this.height*e*Q.PDF_TO_CSS_UNITS),n=new OffscreenCanvas(i,s);return n.getContext("2d").drawImage(this.#Ar,0,0,this.#Ar.width,this.#Ar.height,0,0,i,s),n.transferToImageBitmap()}return structuredClone(this.#Ar)}#Qa(){this._uiManager._signal&&(this.#Ua=new ResizeObserver((t=>{const e=t[0].contentRect;e.width&&e.height&&this.#Lr(e.width,e.height)})),this.#Ua.observe(this.div),this._uiManager._signal.addEventListener("abort",(()=>{this.#Ua?.disconnect(),this.#Ua=null}),{once:!0}))}static async deserialize(t,e,i){let s=null;if(t instanceof Qi){const{data:{rect:n,rotation:a,id:r,structParent:o,popupRef:l},container:h,parent:{page:{pageNumber:c}}}=t,u=h.querySelector("canvas"),p=i.imageManager.getFromCanvas(h.id,u);u.remove();const g=(await e._structTree.getAriaAttributes(`${W}${r}`))?.get("aria-label")||"";s=t={annotationType:d.STAMP,bitmapId:p.id,bitmap:p.bitmap,pageIndex:c-1,rect:n.slice(0),rotation:a,id:r,deleted:!1,accessibilityData:{decorative:!1,altText:g},isSvg:!1,structParent:o,popupRef:l}}const n=await super.deserialize(t,e,i),{rect:a,bitmap:r,bitmapUrl:o,bitmapId:l,isSvg:h,accessibilityData:c}=t;l&&i.imageManager.isValidId(l)?(n.#yr=l,r&&(n.#Ar=r)):n.#_r=o,n.#Tr=h;const[u,p]=n.pageDimensions;return n.width=(a[2]-a[0])/u,n.height=(a[3]-a[1])/p,n.annotationElementId=t.id||null,c&&(n.altTextData=c),n._initialData=s,n.#Mr=!!s,n}serialize(t=!1,e=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const i={annotationType:d.STAMP,bitmapId:this.#yr,pageIndex:this.pageIndex,rect:this.getRect(0,0),rotation:this.rotation,isSvg:this.#Tr,structTreeParentId:this._structTreeParentId};if(t)return i.bitmapUrl=this.#Fr(!0),i.accessibilityData=this.serializeAltText(!0),i;const{decorative:s,altText:n}=this.serializeAltText(!1);if(!s&&n&&(i.accessibilityData={type:"Figure",alt:n}),this.annotationElementId){const t=this.#gn(i);if(t.isSame)return null;t.isSameAltText?delete i.accessibilityData:i.accessibilityData.structParent=this._initialData.structParent??-1}if(i.id=this.annotationElementId,null===e)return i;e.stamps||=new Map;const a=this.#Tr?(i.rect[2]-i.rect[0])*(i.rect[3]-i.rect[1]):null;if(e.stamps.has(this.#yr)){if(this.#Tr){const t=e.stamps.get(this.#yr);a>t.area&&(t.area=a,t.serialized.bitmap.close(),t.serialized.bitmap=this.#Fr(!1))}}else e.stamps.set(this.#yr,{area:a,serialized:i}),i.bitmap=this.#Fr(!1);return i}#gn(t){const{rect:e,pageIndex:i,accessibilityData:{altText:s}}=this._initialData,n=t.rect.every(((t,i)=>Math.abs(t-e[i])<1)),a=t.pageIndex===i,r=(t.accessibilityData?.alt||"")===s;return{isSame:n&&a&&r,isSameAltText:r}}renderAnnotationElement(t){return t.updateEdited({rect:this.getRect(0,0)}),null}}class cs{#Qs;#Nr=!1;#Or=null;#Br=null;#zr=null;#Hr=new Map;#jr=!1;#Ur=!1;#$r=!1;#Wr=null;#Gr=null;#m;static _initialized=!1;static#H=new Map([es,hs,ds,ls].map((t=>[t._editorType,t])));constructor({uiManager:t,pageIndex:e,div:i,structTreeLayer:s,accessibilityManager:n,annotationLayer:a,drawLayer:r,textLayer:o,viewport:l,l10n:h}){const d=[...cs.#H.values()];if(!cs._initialized){cs._initialized=!0;for(const e of d)e.initialize(h,t)}t.registerEditorTypes(d),this.#m=t,this.pageIndex=e,this.div=i,this.#Qs=n,this.#Or=a,this.viewport=l,this.#Wr=o,this.drawLayer=r,this._structTree=s,this.#m.addLayer(this)}get isEmpty(){return 0===this.#Hr.size}get isInvisible(){return this.isEmpty&&this.#m.getMode()===d.NONE}updateToolbar(t){this.#m.updateToolbar(t)}updateMode(t=this.#m.getMode()){switch(this.#Vr(),t){case d.NONE:return this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),void this.disableClick();case d.INK:this.addInkEditorIfNeeded(!1),this.disableTextSelection(),this.togglePointerEvents(!0),this.disableClick();break;case d.HIGHLIGHT:this.enableTextSelection(),this.togglePointerEvents(!1),this.disableClick();break;default:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick()}this.toggleAnnotationLayerPointerEvents(!1);const{classList:e}=this.div;for(const i of cs.#H.values())e.toggle(`${i._type}Editing`,t===i._editorType);this.div.hidden=!1}hasTextLayer(t){return t===this.#Wr?.div}addInkEditorIfNeeded(t){if(this.#m.getMode()===d.INK){if(!t)for(const t of this.#Hr.values())if(t.isEmpty())return void t.setInBackground();this.createAndAddNewEditor({offsetX:0,offsetY:0},!1).setInBackground()}}setEditingState(t){this.#m.setEditingState(t)}addCommands(t){this.#m.addCommands(t)}toggleDrawing(t=!1){this.div.classList.toggle("drawing",!t)}togglePointerEvents(t=!1){this.div.classList.toggle("disabled",!t)}toggleAnnotationLayerPointerEvents(t=!1){this.#Or?.div.classList.toggle("disabled",!t)}async enable(){this.div.tabIndex=0,this.togglePointerEvents(!0);const t=new Set;for(const e of this.#Hr.values())e.enableEditing(),e.show(!0),e.annotationElementId&&(this.#m.removeChangedExistingAnnotation(e),t.add(e.annotationElementId));if(!this.#Or)return;const e=this.#Or.getEditableAnnotations();for(const i of e){if(i.hide(),this.#m.isDeletedAnnotationElement(i.data.id))continue;if(t.has(i.data.id))continue;const e=await this.deserialize(i);e&&(this.addOrRebuild(e),e.enableEditing())}}disable(){this.#$r=!0,this.div.tabIndex=-1,this.togglePointerEvents(!1);const t=new Map,e=new Map;for(const i of this.#Hr.values())i.disableEditing(),i.annotationElementId&&(null===i.serialize()?(e.set(i.annotationElementId,i),this.getEditableAnnotation(i.annotationElementId)?.show(),i.remove()):t.set(i.annotationElementId,i));if(this.#Or){const i=this.#Or.getEditableAnnotations();for(const s of i){const{id:i}=s.data;if(this.#m.isDeletedAnnotationElement(i))continue;let n=e.get(i);n?(n.resetAnnotationElement(s),n.show(!1),s.show()):(n=t.get(i),n&&(this.#m.addChangedExistingAnnotation(n),n.renderAnnotationElement(s)&&n.show(!1)),s.show())}}this.#Vr(),this.isEmpty&&(this.div.hidden=!0);const{classList:i}=this.div;for(const t of cs.#H.values())i.remove(`${t._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),this.#$r=!1}getEditableAnnotation(t){return this.#Or?.getEditableAnnotation(t)||null}setActiveEditor(t){this.#m.getActive()!==t&&this.#m.setActiveEditor(t)}enableTextSelection(){if(this.div.tabIndex=-1,this.#Wr?.div&&!this.#Gr){this.#Gr=new AbortController;const t=this.#m.combinedSignal(this.#Gr);this.#Wr.div.addEventListener("pointerdown",this.#qr.bind(this),{signal:t}),this.#Wr.div.classList.add("highlighting")}}disableTextSelection(){this.div.tabIndex=0,this.#Wr?.div&&this.#Gr&&(this.#Gr.abort(),this.#Gr=null,this.#Wr.div.classList.remove("highlighting"))}#qr(t){this.#m.unselectAll();const{target:e}=t;if(e===this.#Wr.div||("img"===e.getAttribute("role")||e.classList.contains("endOfContent"))&&this.#Wr.div.contains(e)){const{isMac:e}=B.platform;if(0!==t.button||t.ctrlKey&&e)return;this.#m.showAllEditors("highlight",!0,!0),this.#Wr.div.classList.add("free"),this.toggleDrawing(),ls.startHighlighting(this,"ltr"===this.#m.direction,{target:this.#Wr.div,x:t.x,y:t.y}),this.#Wr.div.addEventListener("pointerup",(()=>{this.#Wr.div.classList.remove("free"),this.toggleDrawing(!0)}),{once:!0,signal:this.#m._signal}),t.preventDefault()}}enableClick(){if(this.#Br)return;this.#Br=new AbortController;const t=this.#m.combinedSignal(this.#Br);this.div.addEventListener("pointerdown",this.pointerdown.bind(this),{signal:t}),this.div.addEventListener("pointerup",this.pointerup.bind(this),{signal:t})}disableClick(){this.#Br?.abort(),this.#Br=null}attach(t){this.#Hr.set(t.id,t);const{annotationElementId:e}=t;e&&this.#m.isDeletedAnnotationElement(e)&&this.#m.removeDeletedAnnotationElement(t)}detach(t){this.#Hr.delete(t.id),this.#Qs?.removePointerInTextLayer(t.contentDiv),!this.#$r&&t.annotationElementId&&this.#m.addDeletedAnnotationElement(t)}remove(t){this.detach(t),this.#m.removeEditor(t),t.div.remove(),t.isAttachedToDOM=!1,this.#Ur||this.addInkEditorIfNeeded(!1)}changeParent(t){t.parent!==this&&(t.parent&&t.annotationElementId&&(this.#m.addDeletedAnnotationElement(t.annotationElementId),It.deleteAnnotationElement(t),t.annotationElementId=null),this.attach(t),t.parent?.detach(t),t.setParent(this),t.div&&t.isAttachedToDOM&&(t.div.remove(),this.div.append(t.div)))}add(t){if(t.parent!==this||!t.isAttachedToDOM){if(this.changeParent(t),this.#m.addEditor(t),this.attach(t),!t.isAttachedToDOM){const e=t.render();this.div.append(e),t.isAttachedToDOM=!0}t.fixAndSetPosition(),t.onceAdded(),this.#m.addToAnnotationStorage(t),t._reportTelemetry(t.telemetryInitialData)}}moveEditorInDOM(t){if(!t.isAttachedToDOM)return;const{activeElement:e}=document;t.div.contains(e)&&!this.#zr&&(t._focusEventsAllowed=!1,this.#zr=setTimeout((()=>{this.#zr=null,t.div.contains(document.activeElement)?t._focusEventsAllowed=!0:(t.div.addEventListener("focusin",(()=>{t._focusEventsAllowed=!0}),{once:!0,signal:this.#m._signal}),e.focus())}),0)),t._structTreeParentId=this.#Qs?.moveElementInDOM(this.div,t.div,t.contentDiv,!0)}addOrRebuild(t){t.needsToBeRebuilt()?(t.parent||=this,t.rebuild(),t.show()):this.add(t)}addUndoableEditor(t){this.addCommands({cmd:()=>t._uiManager.rebuild(t),undo:()=>{t.remove()},mustExec:!1})}getNextId(){return this.#m.getId()}get#Xr(){return cs.#H.get(this.#m.getMode())}combinedSignal(t){return this.#m.combinedSignal(t)}#Kr(t){const e=this.#Xr;return e?new e.prototype.constructor(t):null}canCreateNewEmptyEditor(){return this.#Xr?.canCreateNewEmptyEditor()}pasteEditor(t,e){this.#m.updateToolbar(t),this.#m.updateMode(t);const{offsetX:i,offsetY:s}=this.#Yr(),n=this.getNextId(),a=this.#Kr({parent:this,id:n,x:i,y:s,uiManager:this.#m,isCentered:!0,...e});a&&this.add(a)}async deserialize(t){return await(cs.#H.get(t.annotationType??t.annotationEditorType)?.deserialize(t,this,this.#m))||null}createAndAddNewEditor(t,e,i={}){const s=this.getNextId(),n=this.#Kr({parent:this,id:s,x:t.offsetX,y:t.offsetY,uiManager:this.#m,isCentered:e,...i});return n&&this.add(n),n}#Yr(){const{x:t,y:e,width:i,height:s}=this.div.getBoundingClientRect(),n=Math.max(0,t),a=Math.max(0,e),r=(n+Math.min(window.innerWidth,t+i))/2-t,o=(a+Math.min(window.innerHeight,e+s))/2-e,[l,h]=this.viewport.rotation%180==0?[r,o]:[o,r];return{offsetX:l,offsetY:h}}addNewEditor(){this.createAndAddNewEditor(this.#Yr(),!0)}setSelected(t){this.#m.setSelected(t)}toggleSelected(t){this.#m.toggleSelected(t)}isSelected(t){return this.#m.isSelected(t)}unselect(t){this.#m.unselect(t)}pointerup(t){const{isMac:e}=B.platform;0!==t.button||t.ctrlKey&&e||t.target===this.div&&this.#jr&&(this.#jr=!1,this.#Nr?this.#m.getMode()!==d.STAMP?this.createAndAddNewEditor(t,!1):this.#m.unselectAll():this.#Nr=!0)}pointerdown(t){if(this.#m.getMode()===d.HIGHLIGHT&&this.enableTextSelection(),this.#jr)return void(this.#jr=!1);const{isMac:e}=B.platform;if(0!==t.button||t.ctrlKey&&e)return;if(t.target!==this.div)return;this.#jr=!0;const i=this.#m.getActive();this.#Nr=!i||i.isEmpty()}findNewParent(t,e,i){const s=this.#m.findParent(e,i);return null!==s&&s!==this&&(s.changeParent(t),!0)}destroy(){this.#m.getActive()?.parent===this&&(this.#m.commitOrRemove(),this.#m.setActiveEditor(null)),this.#zr&&(clearTimeout(this.#zr),this.#zr=null);for(const t of this.#Hr.values())this.#Qs?.removePointerInTextLayer(t.contentDiv),t.setParent(null),t.isAttachedToDOM=!1,t.div.remove();this.div=null,this.#Hr.clear(),this.#m.removeLayer(this)}#Vr(){this.#Ur=!0;for(const t of this.#Hr.values())t.isEmpty()&&t.remove();this.#Ur=!1}render({viewport:t}){this.viewport=t,vt(this.div,t);for(const t of this.#m.getEditors(this.pageIndex))this.add(t),t.rebuild();this.updateMode()}update({viewport:t}){this.#m.commitOrRemove(),this.#Vr();const e=this.viewport.rotation,i=t.rotation;if(this.viewport=t,vt(this.div,{rotation:i}),e!==i)for(const t of this.#Hr.values())t.rotate(i);this.addInkEditorIfNeeded(!1)}get pageDimensions(){const{pageWidth:t,pageHeight:e}=this.viewport.rawDims;return[t,e]}get scale(){return this.#m.viewParameters.realScale}}class us{#Ps=null;#A=0;#Qr=new Map;#Jr=new Map;constructor({pageIndex:t}){this.pageIndex=t}setParent(t){if(this.#Ps){if(this.#Ps!==t){if(this.#Qr.size>0)for(const e of this.#Qr.values())e.remove(),t.append(e);this.#Ps=t}}else this.#Ps=t}static get _svgFactory(){return S(this,"_svgFactory",new et)}static#Zr(t,{x:e=0,y:i=0,width:s=1,height:n=1}={}){const{style:a}=t;a.top=100*i+"%",a.left=100*e+"%",a.width=100*s+"%",a.height=100*n+"%"}#to(t){const e=us._svgFactory.create(1,1,!0);return this.#Ps.append(e),e.setAttribute("aria-hidden",!0),us.#Zr(e,t),e}#eo(t,e){const i=us._svgFactory.createElement("clipPath");t.append(i);const s=`clip_${e}`;i.setAttribute("id",s),i.setAttribute("clipPathUnits","objectBoundingBox");const n=us._svgFactory.createElement("use");return i.append(n),n.setAttribute("href",`#${e}`),n.classList.add("clip"),s}highlight(t,e,i,s=!1){const n=this.#A++,a=this.#to(t.box);a.classList.add("highlight"),t.free&&a.classList.add("free");const r=us._svgFactory.createElement("defs");a.append(r);const o=us._svgFactory.createElement("path");r.append(o);const l=`path_p${this.pageIndex}_${n}`;o.setAttribute("id",l),o.setAttribute("d",t.toSVGPath()),s&&this.#Jr.set(n,o);const h=this.#eo(r,l),d=us._svgFactory.createElement("use");return a.append(d),a.setAttribute("fill",e),a.setAttribute("fill-opacity",i),d.setAttribute("href",`#${l}`),this.#Qr.set(n,a),{id:n,clipPathId:`url(#${h})`}}highlightOutline(t){const e=this.#A++,i=this.#to(t.box);i.classList.add("highlightOutline");const s=us._svgFactory.createElement("defs");i.append(s);const n=us._svgFactory.createElement("path");s.append(n);const a=`path_p${this.pageIndex}_${e}`;let r;if(n.setAttribute("id",a),n.setAttribute("d",t.toSVGPath()),n.setAttribute("vector-effect","non-scaling-stroke"),t.free){i.classList.add("free");const t=us._svgFactory.createElement("mask");s.append(t),r=`mask_p${this.pageIndex}_${e}`,t.setAttribute("id",r),t.setAttribute("maskUnits","objectBoundingBox");const n=us._svgFactory.createElement("rect");t.append(n),n.setAttribute("width","1"),n.setAttribute("height","1"),n.setAttribute("fill","white");const o=us._svgFactory.createElement("use");t.append(o),o.setAttribute("href",`#${a}`),o.setAttribute("stroke","none"),o.setAttribute("fill","black"),o.setAttribute("fill-rule","nonzero"),o.classList.add("mask")}const o=us._svgFactory.createElement("use");i.append(o),o.setAttribute("href",`#${a}`),r&&o.setAttribute("mask",`url(#${r})`);const l=o.cloneNode();return i.append(l),o.classList.add("mainOutline"),l.classList.add("secondaryOutline"),this.#Qr.set(e,i),e}finalizeLine(t,e){const i=this.#Jr.get(t);this.#Jr.delete(t),this.updateBox(t,e.box),i.setAttribute("d",e.toSVGPath())}updateLine(t,e){this.#Qr.get(t).firstChild.firstChild.setAttribute("d",e.toSVGPath())}removeFreeHighlight(t){this.remove(t),this.#Jr.delete(t)}updatePath(t,e){this.#Jr.get(t).setAttribute("d",e.toSVGPath())}updateBox(t,e){us.#Zr(this.#Qr.get(t),e)}show(t,e){this.#Qr.get(t).classList.toggle("hidden",!e)}rotate(t,e){this.#Qr.get(t).setAttribute("data-main-rotation",e)}changeColor(t,e){this.#Qr.get(t).setAttribute("fill",e)}changeOpacity(t,e){this.#Qr.get(t).setAttribute("fill-opacity",e)}addClass(t,e){this.#Qr.get(t).classList.add(e)}removeClass(t,e){this.#Qr.get(t).classList.remove(e)}getSVGRoot(t){return this.#Qr.get(t)}remove(t){null!==this.#Ps&&(this.#Qr.get(t).remove(),this.#Qr.delete(t))}destroy(){this.#Ps=null;for(const t of this.#Qr.values())t.remove();this.#Qr.clear()}}var ps=n.AbortException,gs=n.AnnotationEditorLayer,ms=n.AnnotationEditorParamsType,fs=n.AnnotationEditorType,bs=n.AnnotationEditorUIManager,vs=n.AnnotationLayer,As=n.AnnotationMode,ys=n.CMapCompressionType,ws=n.ColorPicker,_s=n.DOMSVGFactory,xs=n.DrawLayer,Cs=n.FeatureTest,Es=n.GlobalWorkerOptions,Ss=n.ImageKind,Ts=n.InvalidPDFException,Ms=n.MissingPDFException,ks=n.OPS,Is=n.OutputScale,Ps=n.PDFDataRangeTransport,Rs=n.PDFDateString,Ds=n.PDFWorker,Ls=n.PasswordResponses,Fs=n.PermissionFlag,Ns=n.PixelsPerInch,Os=n.RenderingCancelledException,Bs=n.TextLayer,zs=n.UnexpectedResponseException,Hs=n.Util,js=n.VerbosityLevel,Us=n.XfaLayer,$s=n.build,Ws=n.createValidAbsoluteUrl,Gs=n.fetchData,Vs=n.getDocument,qs=n.getFilenameFromUrl,Xs=n.getPdfFilenameFromUrl,Ks=n.getXfaPageViewport,Ys=n.isDataScheme,Qs=n.isPdfFile,Js=n.noContextMenu,Zs=n.normalizeUnicode,tn=n.setLayerDimensions,en=n.shadow,sn=n.version;"undefined"!=typeof window&&"Worker"in window&&(Es.workerPort=new Worker(new URL(i.p+i.u(332),i.b),{type:void 0}))}}]); \ No newline at end of file diff --git a/dist/560.index.js b/dist/840.index.js similarity index 99% rename from dist/560.index.js rename to dist/840.index.js index 900aef5..1e5e2b7 100644 --- a/dist/560.index.js +++ b/dist/840.index.js @@ -1,2 +1,2 @@ -/*! For license information please see 560.index.js.LICENSE.txt */ -"use strict";(self.webpackChunkFileViewer=self.webpackChunkFileViewer||[]).push([[560],{560:(t,e,i)=>{i.r(e),i.d(e,{AbortException:()=>cs,AnnotationEditorLayer:()=>us,AnnotationEditorParamsType:()=>ps,AnnotationEditorType:()=>gs,AnnotationEditorUIManager:()=>ms,AnnotationLayer:()=>fs,AnnotationMode:()=>bs,CMapCompressionType:()=>vs,ColorPicker:()=>As,DOMSVGFactory:()=>ys,DrawLayer:()=>ws,FeatureTest:()=>_s,GlobalWorkerOptions:()=>xs,ImageKind:()=>Cs,InvalidPDFException:()=>Es,MissingPDFException:()=>Ss,OPS:()=>Ts,OutputScale:()=>Ms,PDFDataRangeTransport:()=>ks,PDFDateString:()=>Is,PDFWorker:()=>Ps,PasswordResponses:()=>Rs,PermissionFlag:()=>Ds,PixelsPerInch:()=>Ls,RenderingCancelledException:()=>Fs,TextLayer:()=>Ns,UnexpectedResponseException:()=>Os,Util:()=>Bs,VerbosityLevel:()=>zs,XfaLayer:()=>Hs,build:()=>js,createValidAbsoluteUrl:()=>Us,fetchData:()=>$s,getDocument:()=>Ws,getFilenameFromUrl:()=>Gs,getPdfFilenameFromUrl:()=>Vs,getXfaPageViewport:()=>qs,isDataScheme:()=>Xs,isPdfFile:()=>Ks,noContextMenu:()=>Ys,normalizeUnicode:()=>Qs,setLayerDimensions:()=>Js,shadow:()=>Zs,version:()=>tn});var s={d:(t,e)=>{for(var i in e)s.o(e,i)&&!s.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e)};e=globalThis.pdfjsLib={},s.d(e,{AbortException:()=>D,AnnotationEditorLayer:()=>hs,AnnotationEditorParamsType:()=>d,AnnotationEditorType:()=>h,AnnotationEditorUIManager:()=>Tt,AnnotationLayer:()=>Qi,AnnotationMode:()=>l,CMapCompressionType:()=>g,ColorPicker:()=>as,DOMSVGFactory:()=>tt,DrawLayer:()=>ds,FeatureTest:()=>O,GlobalWorkerOptions:()=>fe,ImageKind:()=>u,InvalidPDFException:()=>k,MissingPDFException:()=>I,OPS:()=>m,OutputScale:()=>vt,PDFDataRangeTransport:()=>ai,PDFDateString:()=>ut,PDFWorker:()=>hi,PasswordResponses:()=>f,PermissionFlag:()=>c,PixelsPerInch:()=>Y,RenderingCancelledException:()=>it,TextLayer:()=>Ye,UnexpectedResponseException:()=>P,Util:()=>z,VerbosityLevel:()=>p,XfaLayer:()=>yi,build:()=>fi,createValidAbsoluteUrl:()=>C,fetchData:()=>Q,getDocument:()=>ii,getFilenameFromUrl:()=>at,getPdfFilenameFromUrl:()=>rt,getXfaPageViewport:()=>pt,isDataScheme:()=>st,isPdfFile:()=>nt,noContextMenu:()=>ht,normalizeUnicode:()=>U,setLayerDimensions:()=>bt,shadow:()=>E,version:()=>mi});const n=!("object"!=typeof process||process+""!="[object process]"||process.versions.nw||process.versions.electron&&process.type&&"browser"!==process.type),a=[1,0,0,1,0,0],r=[.001,0,0,.001,0,0],o=1.35,l={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},h={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15},d={RESIZE:1,CREATE:2,FREETEXT_SIZE:11,FREETEXT_COLOR:12,FREETEXT_OPACITY:13,INK_COLOR:21,INK_THICKNESS:22,INK_OPACITY:23,HIGHLIGHT_COLOR:31,HIGHLIGHT_DEFAULT_COLOR:32,HIGHLIGHT_THICKNESS:33,HIGHLIGHT_FREE:34,HIGHLIGHT_SHOW_ALL:35},c={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},u={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},p={ERRORS:0,WARNINGS:1,INFOS:5},g={NONE:0,BINARY:1},m={dependency:1,setLineWidth:2,setLineCap:3,setLineJoin:4,setMiterLimit:5,setDash:6,setRenderingIntent:7,setFlatness:8,setGState:9,save:10,restore:11,transform:12,moveTo:13,lineTo:14,curveTo:15,curveTo2:16,curveTo3:17,closePath:18,rectangle:19,stroke:20,closeStroke:21,fill:22,eoFill:23,fillStroke:24,eoFillStroke:25,closeFillStroke:26,closeEOFillStroke:27,endPath:28,clip:29,eoClip:30,beginText:31,endText:32,setCharSpacing:33,setWordSpacing:34,setHScale:35,setLeading:36,setFont:37,setTextRenderingMode:38,setTextRise:39,moveText:40,setLeadingMoveText:41,setTextMatrix:42,nextLine:43,showText:44,showSpacedText:45,nextLineShowText:46,nextLineSetSpacingShowText:47,setCharWidth:48,setCharWidthAndBounds:49,setStrokeColorSpace:50,setFillColorSpace:51,setStrokeColor:52,setStrokeColorN:53,setFillColor:54,setFillColorN:55,setStrokeGray:56,setFillGray:57,setStrokeRGBColor:58,setFillRGBColor:59,setStrokeCMYKColor:60,setFillCMYKColor:61,shadingFill:62,beginInlineImage:63,beginImageData:64,endInlineImage:65,paintXObject:66,markPoint:67,markPointProps:68,beginMarkedContent:69,beginMarkedContentProps:70,endMarkedContent:71,beginCompat:72,endCompat:73,paintFormXObjectBegin:74,paintFormXObjectEnd:75,beginGroup:76,endGroup:77,beginAnnotation:80,endAnnotation:81,paintImageMaskXObject:83,paintImageMaskXObjectGroup:84,paintImageXObject:85,paintInlineImageXObject:86,paintInlineImageXObjectGroup:87,paintImageXObjectRepeat:88,paintImageMaskXObjectRepeat:89,paintSolidColorImageMask:90,constructPath:91,setStrokeTransparent:92,setFillTransparent:93},f={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let b=p.WARNINGS;function v(t){Number.isInteger(t)&&(b=t)}function A(){return b}function y(t){b>=p.INFOS&&console.log(`Info: ${t}`)}function w(t){b>=p.WARNINGS&&console.log(`Warning: ${t}`)}function _(t){throw new Error(t)}function x(t,e){t||_(e)}function C(t,e=null,i=null){if(!t)return null;try{if(i&&"string"==typeof t&&(i.addDefaultProtocol&&t.startsWith("www.")&&t.match(/\./g)?.length>=2&&(t=`http://${t}`),i.tryConvertEncoding))try{t=decodeURIComponent(escape(t))}catch{}const s=e?new URL(t,e):new URL(t);if(function(t){switch(t?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}(s))return s}catch{}return null}function E(t,e,i,s=!1){return Object.defineProperty(t,e,{value:i,enumerable:!s,configurable:!0,writable:!1}),i}const S=function(){function t(t,e){this.message=t,this.name=e}return t.prototype=new Error,t.constructor=t,t}();class T extends S{constructor(t,e){super(t,"PasswordException"),this.code=e}}class M extends S{constructor(t,e){super(t,"UnknownErrorException"),this.details=e}}class k extends S{constructor(t){super(t,"InvalidPDFException")}}class I extends S{constructor(t){super(t,"MissingPDFException")}}class P extends S{constructor(t,e){super(t,"UnexpectedResponseException"),this.status=e}}class R extends S{constructor(t){super(t,"FormatError")}}class D extends S{constructor(t){super(t,"AbortException")}}function L(t){"object"==typeof t&&void 0!==t?.length||_("Invalid argument for bytesToString");const e=t.length,i=8192;if(et.toString(16).padStart(2,"0")));class z{static makeHexColor(t,e,i){return`#${B[t]}${B[e]}${B[i]}`}static scaleMinMax(t,e){let i;t[0]?(t[0]<0&&(i=e[0],e[0]=e[2],e[2]=i),e[0]*=t[0],e[2]*=t[0],t[3]<0&&(i=e[1],e[1]=e[3],e[3]=i),e[1]*=t[3],e[3]*=t[3]):(i=e[0],e[0]=e[1],e[1]=i,i=e[2],e[2]=e[3],e[3]=i,t[1]<0&&(i=e[1],e[1]=e[3],e[3]=i),e[1]*=t[1],e[3]*=t[1],t[2]<0&&(i=e[0],e[0]=e[2],e[2]=i),e[0]*=t[2],e[2]*=t[2]),e[0]+=t[4],e[1]+=t[5],e[2]+=t[4],e[3]+=t[5]}static transform(t,e){return[t[0]*e[0]+t[2]*e[1],t[1]*e[0]+t[3]*e[1],t[0]*e[2]+t[2]*e[3],t[1]*e[2]+t[3]*e[3],t[0]*e[4]+t[2]*e[5]+t[4],t[1]*e[4]+t[3]*e[5]+t[5]]}static applyTransform(t,e){return[t[0]*e[0]+t[1]*e[2]+e[4],t[0]*e[1]+t[1]*e[3]+e[5]]}static applyInverseTransform(t,e){const i=e[0]*e[3]-e[1]*e[2];return[(t[0]*e[3]-t[1]*e[2]+e[2]*e[5]-e[4]*e[3])/i,(-t[0]*e[1]+t[1]*e[0]+e[4]*e[1]-e[5]*e[0])/i]}static getAxialAlignedBoundingBox(t,e){const i=this.applyTransform(t,e),s=this.applyTransform(t.slice(2,4),e),n=this.applyTransform([t[0],t[3]],e),a=this.applyTransform([t[2],t[1]],e);return[Math.min(i[0],s[0],n[0],a[0]),Math.min(i[1],s[1],n[1],a[1]),Math.max(i[0],s[0],n[0],a[0]),Math.max(i[1],s[1],n[1],a[1])]}static inverseTransform(t){const e=t[0]*t[3]-t[1]*t[2];return[t[3]/e,-t[1]/e,-t[2]/e,t[0]/e,(t[2]*t[5]-t[4]*t[3])/e,(t[4]*t[1]-t[5]*t[0])/e]}static singularValueDecompose2dScale(t){const e=[t[0],t[2],t[1],t[3]],i=t[0]*e[0]+t[1]*e[2],s=t[0]*e[1]+t[1]*e[3],n=t[2]*e[0]+t[3]*e[2],a=t[2]*e[1]+t[3]*e[3],r=(i+a)/2,o=Math.sqrt((i+a)**2-4*(i*a-n*s))/2,l=r+o||1,h=r-o||1;return[Math.sqrt(l),Math.sqrt(h)]}static normalizeRect(t){const e=t.slice(0);return t[0]>t[2]&&(e[0]=t[2],e[2]=t[0]),t[1]>t[3]&&(e[1]=t[3],e[3]=t[1]),e}static intersect(t,e){const i=Math.max(Math.min(t[0],t[2]),Math.min(e[0],e[2])),s=Math.min(Math.max(t[0],t[2]),Math.max(e[0],e[2]));if(i>s)return null;const n=Math.max(Math.min(t[1],t[3]),Math.min(e[1],e[3])),a=Math.min(Math.max(t[1],t[3]),Math.max(e[1],e[3]));return n>a?null:[i,n,s,a]}static#t(t,e,i,s,n,a,r,o,l,h){if(l<=0||l>=1)return;const d=1-l,c=l*l,u=c*l,p=d*(d*(d*t+3*l*e)+3*c*i)+u*s,g=d*(d*(d*n+3*l*a)+3*c*r)+u*o;h[0]=Math.min(h[0],p),h[1]=Math.min(h[1],g),h[2]=Math.max(h[2],p),h[3]=Math.max(h[3],g)}static#e(t,e,i,s,n,a,r,o,l,h,d,c){if(Math.abs(l)<1e-12)return void(Math.abs(h)>=1e-12&&this.#t(t,e,i,s,n,a,r,o,-d/h,c));const u=h**2-4*d*l;if(u<0)return;const p=Math.sqrt(u),g=2*l;this.#t(t,e,i,s,n,a,r,o,(-h+p)/g,c),this.#t(t,e,i,s,n,a,r,o,(-h-p)/g,c)}static bezierBoundingBox(t,e,i,s,n,a,r,o,l){return l?(l[0]=Math.min(l[0],t,r),l[1]=Math.min(l[1],e,o),l[2]=Math.max(l[2],t,r),l[3]=Math.max(l[3],e,o)):l=[Math.min(t,r),Math.min(e,o),Math.max(t,r),Math.max(e,o)],this.#e(t,i,n,r,e,s,a,o,3*(3*(i-n)-t+r),6*(t-2*i+n),3*(i-t),l),this.#e(t,i,n,r,e,s,a,o,3*(3*(s-a)-e+o),6*(e-2*s+a),3*(s-e),l),l}}let H=null,j=null;function U(t){return H||(H=/([\u00a0\u00b5\u037e\u0eb3\u2000-\u200a\u202f\u2126\ufb00-\ufb04\ufb06\ufb20-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufba1\ufba4-\ufba9\ufbae-\ufbb1\ufbd3-\ufbdc\ufbde-\ufbe7\ufbea-\ufbf8\ufbfc-\ufbfd\ufc00-\ufc5d\ufc64-\ufcf1\ufcf5-\ufd3d\ufd88\ufdf4\ufdfa-\ufdfb\ufe71\ufe77\ufe79\ufe7b\ufe7d]+)|(\ufb05+)/gu,j=new Map([["ſt","ſt"]])),t.replaceAll(H,((t,e,i)=>e?e.normalize("NFKC"):j.get(i)))}const $="pdfjs_internal_id_";class W{addFilter(t){return"none"}addHCMFilter(t,e){return"none"}addAlphaFilter(t){return"none"}addLuminosityFilter(t){return"none"}addHighlightHCMFilter(t,e,i,s,n){return"none"}destroy(t=!1){}}class G{#i=!1;constructor({enableHWA:t=!1}){this.#i=t}create(t,e){if(t<=0||e<=0)throw new Error("Invalid canvas size");const i=this._createCanvas(t,e);return{canvas:i,context:i.getContext("2d",{willReadFrequently:!this.#i})}}reset(t,e,i){if(!t.canvas)throw new Error("Canvas is not specified");if(e<=0||i<=0)throw new Error("Invalid canvas size");t.canvas.width=e,t.canvas.height=i}destroy(t){if(!t.canvas)throw new Error("Canvas is not specified");t.canvas.width=0,t.canvas.height=0,t.canvas=null,t.context=null}_createCanvas(t,e){_("Abstract method `_createCanvas` called.")}}class V{constructor({baseUrl:t=null,isCompressed:e=!0}){this.baseUrl=t,this.isCompressed=e}async fetch({name:t}){if(!this.baseUrl)throw new Error("Ensure that the `cMapUrl` and `cMapPacked` API parameters are provided.");if(!t)throw new Error("CMap name must be specified.");const e=this.baseUrl+t+(this.isCompressed?".bcmap":""),i=this.isCompressed?g.BINARY:g.NONE;return this._fetchData(e,i).catch((t=>{throw new Error(`Unable to load ${this.isCompressed?"binary ":""}CMap at: ${e}`)}))}_fetchData(t,e){_("Abstract method `_fetchData` called.")}}class q{constructor({baseUrl:t=null}){this.baseUrl=t}async fetch({filename:t}){if(!this.baseUrl)throw new Error("Ensure that the `standardFontDataUrl` API parameter is provided.");if(!t)throw new Error("Font filename must be specified.");const e=`${this.baseUrl}${t}`;return this._fetchData(e).catch((t=>{throw new Error(`Unable to load font data at: ${e}`)}))}_fetchData(t){_("Abstract method `_fetchData` called.")}}class X{create(t,e,i=!1){if(t<=0||e<=0)throw new Error("Invalid SVG dimensions");const s=this._createSVG("svg:svg");return s.setAttribute("version","1.1"),i||(s.setAttribute("width",`${t}px`),s.setAttribute("height",`${e}px`)),s.setAttribute("preserveAspectRatio","none"),s.setAttribute("viewBox",`0 0 ${t} ${e}`),s}createElement(t){if("string"!=typeof t)throw new Error("Invalid SVG element type");return this._createSVG(t)}_createSVG(t){_("Abstract method `_createSVG` called.")}}const K="http://www.w3.org/2000/svg";class Y{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF}async function Q(t,e="text"){if(lt(t,document.baseURI)){const i=await fetch(t);if(!i.ok)throw new Error(i.statusText);switch(e){case"arraybuffer":return i.arrayBuffer();case"blob":return i.blob();case"json":return i.json()}return i.text()}return new Promise(((i,s)=>{const n=new XMLHttpRequest;n.open("GET",t,!0),n.responseType=e,n.onreadystatechange=()=>{if(n.readyState===XMLHttpRequest.DONE)if(200!==n.status&&0!==n.status)s(new Error(n.statusText));else{switch(e){case"arraybuffer":case"blob":case"json":return void i(n.response)}i(n.responseText)}},n.send(null)}))}class J extends V{_fetchData(t,e){return Q(t,this.isCompressed?"arraybuffer":"text").then((t=>({cMapData:t instanceof ArrayBuffer?new Uint8Array(t):F(t),compressionType:e})))}}class Z extends q{_fetchData(t){return Q(t,"arraybuffer").then((t=>new Uint8Array(t)))}}class tt extends X{_createSVG(t){return document.createElementNS(K,t)}}class et{constructor({viewBox:t,scale:e,rotation:i,offsetX:s=0,offsetY:n=0,dontFlip:a=!1}){this.viewBox=t,this.scale=e,this.rotation=i,this.offsetX=s,this.offsetY=n;const r=(t[2]+t[0])/2,o=(t[3]+t[1])/2;let l,h,d,c,u,p,g,m;switch((i%=360)<0&&(i+=360),i){case 180:l=-1,h=0,d=0,c=1;break;case 90:l=0,h=1,d=1,c=0;break;case 270:l=0,h=-1,d=-1,c=0;break;case 0:l=1,h=0,d=0,c=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}a&&(d=-d,c=-c),0===l?(u=Math.abs(o-t[1])*e+s,p=Math.abs(r-t[0])*e+n,g=(t[3]-t[1])*e,m=(t[2]-t[0])*e):(u=Math.abs(r-t[0])*e+s,p=Math.abs(o-t[1])*e+n,g=(t[2]-t[0])*e,m=(t[3]-t[1])*e),this.transform=[l*e,h*e,d*e,c*e,u-l*e*r-d*e*o,p-h*e*r-c*e*o],this.width=g,this.height=m}get rawDims(){const{viewBox:t}=this;return E(this,"rawDims",{pageWidth:t[2]-t[0],pageHeight:t[3]-t[1],pageX:t[0],pageY:t[1]})}clone({scale:t=this.scale,rotation:e=this.rotation,offsetX:i=this.offsetX,offsetY:s=this.offsetY,dontFlip:n=!1}={}){return new et({viewBox:this.viewBox.slice(),scale:t,rotation:e,offsetX:i,offsetY:s,dontFlip:n})}convertToViewportPoint(t,e){return z.applyTransform([t,e],this.transform)}convertToViewportRectangle(t){const e=z.applyTransform([t[0],t[1]],this.transform),i=z.applyTransform([t[2],t[3]],this.transform);return[e[0],e[1],i[0],i[1]]}convertToPdfPoint(t,e){return z.applyInverseTransform([t,e],this.transform)}}class it extends S{constructor(t,e=0){super(t,"RenderingCancelledException"),this.extraDelay=e}}function st(t){const e=t.length;let i=0;for(;i=1&&s<=12?s-1:0;let n=parseInt(e[3],10);n=n>=1&&n<=31?n:1;let a=parseInt(e[4],10);a=a>=0&&a<=23?a:0;let r=parseInt(e[5],10);r=r>=0&&r<=59?r:0;let o=parseInt(e[6],10);o=o>=0&&o<=59?o:0;const l=e[7]||"Z";let h=parseInt(e[8],10);h=h>=0&&h<=23?h:0;let d=parseInt(e[9],10)||0;return d=d>=0&&d<=59?d:0,"-"===l?(a+=h,r+=d):"+"===l&&(a-=h,r-=d),new Date(Date.UTC(i,s,n,a,r,o))}}function pt(t,{scale:e=1,rotation:i=0}){const{width:s,height:n}=t.attributes.style,a=[0,0,parseInt(s),parseInt(n)];return new et({viewBox:a,scale:e,rotation:i})}function gt(t){if(t.startsWith("#")){const e=parseInt(t.slice(1),16);return[(16711680&e)>>16,(65280&e)>>8,255&e]}return t.startsWith("rgb(")?t.slice(4,-1).split(",").map((t=>parseInt(t))):t.startsWith("rgba(")?t.slice(5,-1).split(",").map((t=>parseInt(t))).slice(0,3):(w(`Not a valid color format: "${t}"`),[0,0,0])}function mt(t){const{a:e,b:i,c:s,d:n,e:a,f:r}=t.getTransform();return[e,i,s,n,a,r]}function ft(t){const{a:e,b:i,c:s,d:n,e:a,f:r}=t.getTransform().invertSelf();return[e,i,s,n,a,r]}function bt(t,e,i=!1,s=!0){if(e instanceof et){const{pageWidth:s,pageHeight:n}=e.rawDims,{style:a}=t,r=O.isCSSRoundSupported,o=`var(--scale-factor) * ${s}px`,l=`var(--scale-factor) * ${n}px`,h=r?`round(down, ${o}, var(--scale-round-x, 1px))`:`calc(${o})`,d=r?`round(down, ${l}, var(--scale-round-y, 1px))`:`calc(${l})`;i&&e.rotation%180!=0?(a.width=d,a.height=h):(a.width=h,a.height=d)}s&&t.setAttribute("data-main-rotation",e.rotation)}class vt{constructor(){const t=window.devicePixelRatio||1;this.sx=t,this.sy=t}get scaled(){return 1!==this.sx||1!==this.sy}get symmetric(){return this.sx===this.sy}}class At{#s=null;#n=null;#a;#r=null;#o=null;static#l=null;constructor(t){this.#a=t,At.#l||=Object.freeze({freetext:"pdfjs-editor-remove-freetext-button",highlight:"pdfjs-editor-remove-highlight-button",ink:"pdfjs-editor-remove-ink-button",stamp:"pdfjs-editor-remove-stamp-button"})}render(){const t=this.#s=document.createElement("div");t.classList.add("editToolbar","hidden"),t.setAttribute("role","toolbar");const e=this.#a._uiManager._signal;t.addEventListener("contextmenu",ht,{signal:e}),t.addEventListener("pointerdown",At.#h,{signal:e});const i=this.#r=document.createElement("div");i.className="buttons",t.append(i);const s=this.#a.toolbarPosition;if(s){const{style:e}=t,i="ltr"===this.#a._uiManager.direction?1-s[0]:s[0];e.insetInlineEnd=100*i+"%",e.top=`calc(${100*s[1]}% + var(--editor-toolbar-vert-offset))`}return this.#d(),t}get div(){return this.#s}static#h(t){t.stopPropagation()}#c(t){this.#a._focusEventsAllowed=!1,t.preventDefault(),t.stopPropagation()}#u(t){this.#a._focusEventsAllowed=!0,t.preventDefault(),t.stopPropagation()}#p(t){const e=this.#a._uiManager._signal;t.addEventListener("focusin",this.#c.bind(this),{capture:!0,signal:e}),t.addEventListener("focusout",this.#u.bind(this),{capture:!0,signal:e}),t.addEventListener("contextmenu",ht,{signal:e})}hide(){this.#s.classList.add("hidden"),this.#n?.hideDropdown()}show(){this.#s.classList.remove("hidden"),this.#o?.shown()}#d(){const{editorType:t,_uiManager:e}=this.#a,i=document.createElement("button");i.className="delete",i.tabIndex=0,i.setAttribute("data-l10n-id",At.#l[t]),this.#p(i),i.addEventListener("click",(t=>{e.delete()}),{signal:e._signal}),this.#r.append(i)}get#g(){const t=document.createElement("div");return t.className="divider",t}async addAltText(t){const e=await t.render();this.#p(e),this.#r.prepend(e,this.#g),this.#o=t}addColorPicker(t){this.#n=t;const e=t.renderButton();this.#p(e),this.#r.prepend(e,this.#g)}remove(){this.#s.remove(),this.#n?.destroy(),this.#n=null}}class yt{#r=null;#s=null;#m;constructor(t){this.#m=t}#f(){const t=this.#s=document.createElement("div");t.className="editToolbar",t.setAttribute("role","toolbar"),t.addEventListener("contextmenu",ht,{signal:this.#m._signal});const e=this.#r=document.createElement("div");return e.className="buttons",t.append(e),this.#b(),t}#v(t,e){let i=0,s=0;for(const n of t){const t=n.y+n.height;if(ti?(s=a,i=t):e?a>s&&(s=a):a{this.#m.highlightSelection("floating_button")}),{signal:i}),this.#r.append(t)}}function wt(t,e,i){for(const s of i)e.addEventListener(s,t[s].bind(t))}class _t{#A=0;get id(){return"pdfjs_internal_editor_"+this.#A++}}class xt{#y=function(){if("undefined"!=typeof crypto&&"function"==typeof crypto?.randomUUID)return crypto.randomUUID();const t=new Uint8Array(32);if("undefined"!=typeof crypto&&"function"==typeof crypto?.getRandomValues)crypto.getRandomValues(t);else for(let e=0;e<32;e++)t[e]=Math.floor(255*Math.random());return L(t)}();#A=0;#w=null;static get _isSVGFittingCanvas(){const t=new OffscreenCanvas(1,3).getContext("2d",{willReadFrequently:!0}),e=new Image;return e.src='data:image/svg+xml;charset=UTF-8,',E(this,"_isSVGFittingCanvas",e.decode().then((()=>(t.drawImage(e,0,0,1,1,0,0,1,3),0===new Uint32Array(t.getImageData(0,0,1,1).data.buffer)[0]))))}async#_(t,e){this.#w||=new Map;let i=this.#w.get(t);if(null===i)return null;if(i?.bitmap)return i.refCounter+=1,i;try{let t;if(i||={bitmap:null,id:`image_${this.#y}_${this.#A++}`,refCounter:0,isSvg:!1},"string"==typeof e?(i.url=e,t=await Q(e,"blob")):e instanceof File?t=i.file=e:e instanceof Blob&&(t=e),"image/svg+xml"===t.type){const e=xt._isSVGFittingCanvas,s=new FileReader,n=new Image,a=new Promise(((t,a)=>{n.onload=()=>{i.bitmap=n,i.isSvg=!0,t()},s.onload=async()=>{const t=i.svgUrl=s.result;n.src=await e?`${t}#svgView(preserveAspectRatio(none))`:t},n.onerror=s.onerror=a}));s.readAsDataURL(t),await a}else i.bitmap=await createImageBitmap(t);i.refCounter=1}catch(t){console.error(t),i=null}return this.#w.set(t,i),i&&this.#w.set(i.id,i),i}async getFromFile(t){const{lastModified:e,name:i,size:s,type:n}=t;return this.#_(`${e}_${i}_${s}_${n}`,t)}async getFromUrl(t){return this.#_(t,t)}async getFromBlob(t,e){const i=await e;return this.#_(t,i)}async getFromId(t){this.#w||=new Map;const e=this.#w.get(t);if(!e)return null;if(e.bitmap)return e.refCounter+=1,e;if(e.file)return this.getFromFile(e.file);if(e.blobPromise){const{blobPromise:t}=e;return delete e.blobPromise,this.getFromBlob(e.id,t)}return this.getFromUrl(e.url)}getFromCanvas(t,e){this.#w||=new Map;let i=this.#w.get(t);if(i?.bitmap)return i.refCounter+=1,i;const s=new OffscreenCanvas(e.width,e.height);return s.getContext("2d").drawImage(e,0,0),i={bitmap:s.transferToImageBitmap(),id:`image_${this.#y}_${this.#A++}`,refCounter:1,isSvg:!1},this.#w.set(t,i),this.#w.set(i.id,i),i}getSvgUrl(t){const e=this.#w.get(t);return e?.isSvg?e.svgUrl:null}deleteId(t){this.#w||=new Map;const e=this.#w.get(t);if(!e)return;if(e.refCounter-=1,0!==e.refCounter)return;const{bitmap:i}=e;if(!e.url&&!e.file){const t=new OffscreenCanvas(i.width,i.height);t.getContext("bitmaprenderer").transferFromImageBitmap(i),e.blobPromise=t.convertToBlob()}i.close?.(),e.bitmap=null}isValidId(t){return t.startsWith(`image_${this.#y}_`)}}class Ct{#x=[];#C=!1;#E;#S=-1;constructor(t=128){this.#E=t}add({cmd:t,undo:e,post:i,mustExec:s,type:n=NaN,overwriteIfSameType:a=!1,keepUndo:r=!1}){if(s&&t(),this.#C)return;const o={cmd:t,undo:e,post:i,type:n};if(-1===this.#S)return this.#x.length>0&&(this.#x.length=0),this.#S=0,void this.#x.push(o);if(a&&this.#x[this.#S].type===n)return r&&(o.undo=this.#x[this.#S].undo),void(this.#x[this.#S]=o);const l=this.#S+1;l===this.#E?this.#x.splice(0,1):(this.#S=l,lt===e[i])))return St._colorsMapping.get(t);return e}getHexCode(t){const e=this._colors.get(t);return e?z.makeHexColor(...e):t}}class Tt{#M=new AbortController;#k=null;#I=new Map;#P=new Map;#R=null;#D=null;#L=null;#F=new Ct;#N=null;#O=0;#B=new Set;#z=null;#H=null;#j=new Set;#U=!1;#$=!1;#W=!1;#G=null;#V=null;#q=null;#X=null;#K=!1;#Y=null;#Q=new _t;#J=!1;#Z=!1;#tt=null;#et=null;#it=null;#st=null;#nt=h.NONE;#at=new Set;#rt=null;#ot=null;#lt=null;#ht={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1};#dt=[0,0];#ct=null;#ut=null;#pt=null;#gt=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){const t=Tt.prototype,e=t=>t.#ut.contains(document.activeElement)&&"BUTTON"!==document.activeElement.tagName&&t.hasSomethingToControl(),i=(t,{target:e})=>{if(e instanceof HTMLInputElement){const{type:t}=e;return"text"!==t&&"number"!==t}return!0},s=this.TRANSLATE_SMALL,n=this.TRANSLATE_BIG;return E(this,"_keyboardManager",new Et([[["ctrl+a","mac+meta+a"],t.selectAll,{checker:i}],[["ctrl+z","mac+meta+z"],t.undo,{checker:i}],[["ctrl+y","ctrl+shift+z","mac+meta+shift+z","ctrl+shift+Z","mac+meta+shift+Z"],t.redo,{checker:i}],[["Backspace","alt+Backspace","ctrl+Backspace","shift+Backspace","mac+Backspace","mac+alt+Backspace","mac+ctrl+Backspace","Delete","ctrl+Delete","shift+Delete","mac+Delete"],t.delete,{checker:i}],[["Enter","mac+Enter"],t.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#ut.contains(e)&&!t.isEnterHandled}],[[" ","mac+ "],t.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#ut.contains(document.activeElement)}],[["Escape","mac+Escape"],t.unselectAll],[["ArrowLeft","mac+ArrowLeft"],t.translateSelectedEditors,{args:[-s,0],checker:e}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t.translateSelectedEditors,{args:[-n,0],checker:e}],[["ArrowRight","mac+ArrowRight"],t.translateSelectedEditors,{args:[s,0],checker:e}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t.translateSelectedEditors,{args:[n,0],checker:e}],[["ArrowUp","mac+ArrowUp"],t.translateSelectedEditors,{args:[0,-s],checker:e}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t.translateSelectedEditors,{args:[0,-n],checker:e}],[["ArrowDown","mac+ArrowDown"],t.translateSelectedEditors,{args:[0,s],checker:e}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t.translateSelectedEditors,{args:[0,n],checker:e}]]))}constructor(t,e,i,s,n,a,r,o,l,h,d){const c=this._signal=this.#M.signal;this.#ut=t,this.#pt=e,this.#R=i,this._eventBus=s,s._on("editingaction",this.onEditingAction.bind(this),{signal:c}),s._on("pagechanging",this.onPageChanging.bind(this),{signal:c}),s._on("scalechanging",this.onScaleChanging.bind(this),{signal:c}),s._on("rotationchanging",this.onRotationChanging.bind(this),{signal:c}),s._on("setpreference",this.onSetPreference.bind(this),{signal:c}),s._on("switchannotationeditorparams",(t=>this.updateParams(t.type,t.value)),{signal:c}),this.#mt(),this.#ft(),this.#bt(),this.#D=n.annotationStorage,this.#G=n.filterFactory,this.#ot=a,this.#X=r||null,this.#U=o,this.#$=l,this.#W=h,this.#st=d||null,this.viewParameters={realScale:Y.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1}destroy(){this.#gt?.resolve(),this.#gt=null,this.#M?.abort(),this.#M=null,this._signal=null;for(const t of this.#P.values())t.destroy();this.#P.clear(),this.#I.clear(),this.#j.clear(),this.#k=null,this.#at.clear(),this.#F.destroy(),this.#R?.destroy(),this.#Y?.hide(),this.#Y=null,this.#V&&(clearTimeout(this.#V),this.#V=null),this.#ct&&(clearTimeout(this.#ct),this.#ct=null)}combinedSignal(t){return AbortSignal.any([this._signal,t.signal])}get mlManager(){return this.#st}get useNewAltTextFlow(){return this.#$}get useNewAltTextWhenAddingImage(){return this.#W}get hcmFilter(){return E(this,"hcmFilter",this.#ot?this.#G.addHCMFilter(this.#ot.foreground,this.#ot.background):"none")}get direction(){return E(this,"direction",getComputedStyle(this.#ut).direction)}get highlightColors(){return E(this,"highlightColors",this.#X?new Map(this.#X.split(",").map((t=>t.split("=").map((t=>t.trim()))))):null)}get highlightColorNames(){return E(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,(t=>t.reverse()))):null)}setMainHighlightColorPicker(t){this.#it=t}editAltText(t,e=!1){this.#R?.editAltText(this,t,e)}switchToMode(t,e){this._eventBus.on("annotationeditormodechanged",e,{once:!0,signal:this._signal}),this._eventBus.dispatch("showannotationeditorui",{source:this,mode:t})}setPreference(t,e){this._eventBus.dispatch("setpreference",{source:this,name:t,value:e})}onSetPreference({name:t,value:e}){"enableNewAltTextWhenAddingImage"===t&&(this.#W=e)}onPageChanging({pageNumber:t}){this.#O=t-1}focusMainContainer(){this.#ut.focus()}findParent(t,e){for(const i of this.#P.values()){const{x:s,y:n,width:a,height:r}=i.div.getBoundingClientRect();if(t>=s&&t<=s+a&&e>=n&&e<=n+r)return i}return null}disableUserSelect(t=!1){this.#pt.classList.toggle("noUserSelect",t)}addShouldRescale(t){this.#j.add(t)}removeShouldRescale(t){this.#j.delete(t)}onScaleChanging({scale:t}){this.commitOrRemove(),this.viewParameters.realScale=t*Y.PDF_TO_CSS_UNITS;for(const t of this.#j)t.onScaleChanging()}onRotationChanging({pagesRotation:t}){this.commitOrRemove(),this.viewParameters.rotation=t}#vt({anchorNode:t}){return t.nodeType===Node.TEXT_NODE?t.parentElement:t}#At(t){const{currentLayer:e}=this;if(e.hasTextLayer(t))return e;for(const e of this.#P.values())if(e.hasTextLayer(t))return e;return null}highlightSelection(t=""){const e=document.getSelection();if(!e||e.isCollapsed)return;const{anchorNode:i,anchorOffset:s,focusNode:n,focusOffset:a}=e,r=e.toString(),o=this.#vt(e).closest(".textLayer"),l=this.getSelectionBoxes(o);if(!l)return;e.empty();const d=this.#At(o),c=this.#nt===h.NONE,u=()=>{d?.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:t,boxes:l,anchorNode:i,anchorOffset:s,focusNode:n,focusOffset:a,text:r}),c&&this.showAllEditors("highlight",!0,!0)};c?this.switchToMode(h.HIGHLIGHT,u):u()}#yt(){const t=document.getSelection();if(!t||t.isCollapsed)return;const e=this.#vt(t).closest(".textLayer"),i=this.getSelectionBoxes(e);i&&(this.#Y||=new yt(this),this.#Y.show(e,i,"ltr"===this.direction))}addToAnnotationStorage(t){t.isEmpty()||!this.#D||this.#D.has(t.id)||this.#D.setValue(t.id,t)}#wt(){const t=document.getSelection();if(!t||t.isCollapsed)return void(this.#rt&&(this.#Y?.hide(),this.#rt=null,this.#_t({hasSelectedText:!1})));const{anchorNode:e}=t;if(e===this.#rt)return;const i=this.#vt(t).closest(".textLayer");if(i){if(this.#Y?.hide(),this.#rt=e,this.#_t({hasSelectedText:!0}),(this.#nt===h.HIGHLIGHT||this.#nt===h.NONE)&&(this.#nt===h.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0),this.#K=this.isShiftKeyDown,!this.isShiftKeyDown)){const t=this.#nt===h.HIGHLIGHT?this.#At(i):null;t?.toggleDrawing();const e=new AbortController,s=this.combinedSignal(e),n=i=>{"pointerup"===i.type&&0!==i.button||(e.abort(),t?.toggleDrawing(!0),"pointerup"===i.type&&this.#xt("main_toolbar"))};window.addEventListener("pointerup",n,{signal:s}),window.addEventListener("blur",n,{signal:s})}}else this.#rt&&(this.#Y?.hide(),this.#rt=null,this.#_t({hasSelectedText:!1}))}#xt(t=""){this.#nt===h.HIGHLIGHT?this.highlightSelection(t):this.#U&&this.#yt()}#mt(){document.addEventListener("selectionchange",this.#wt.bind(this),{signal:this._signal})}#Ct(){if(this.#q)return;this.#q=new AbortController;const t=this.combinedSignal(this.#q);window.addEventListener("focus",this.focus.bind(this),{signal:t}),window.addEventListener("blur",this.blur.bind(this),{signal:t})}#Et(){this.#q?.abort(),this.#q=null}blur(){if(this.isShiftKeyDown=!1,this.#K&&(this.#K=!1,this.#xt("main_toolbar")),!this.hasSelection)return;const{activeElement:t}=document;for(const e of this.#at)if(e.div.contains(t)){this.#et=[e,t],e._focusEventsAllowed=!1;break}}focus(){if(!this.#et)return;const[t,e]=this.#et;this.#et=null,e.addEventListener("focusin",(()=>{t._focusEventsAllowed=!0}),{once:!0,signal:this._signal}),e.focus()}#bt(){if(this.#tt)return;this.#tt=new AbortController;const t=this.combinedSignal(this.#tt);window.addEventListener("keydown",this.keydown.bind(this),{signal:t}),window.addEventListener("keyup",this.keyup.bind(this),{signal:t})}#St(){this.#tt?.abort(),this.#tt=null}#Tt(){if(this.#N)return;this.#N=new AbortController;const t=this.combinedSignal(this.#N);document.addEventListener("copy",this.copy.bind(this),{signal:t}),document.addEventListener("cut",this.cut.bind(this),{signal:t}),document.addEventListener("paste",this.paste.bind(this),{signal:t})}#Mt(){this.#N?.abort(),this.#N=null}#ft(){const t=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:t}),document.addEventListener("drop",this.drop.bind(this),{signal:t})}addEditListeners(){this.#bt(),this.#Tt()}removeEditListeners(){this.#St(),this.#Mt()}dragOver(t){for(const{type:e}of t.dataTransfer.items)for(const i of this.#H)if(i.isHandlingMimeForPasting(e))return t.dataTransfer.dropEffect="copy",void t.preventDefault()}drop(t){for(const e of t.dataTransfer.items)for(const i of this.#H)if(i.isHandlingMimeForPasting(e.type))return i.paste(e,this.currentLayer),void t.preventDefault()}copy(t){if(t.preventDefault(),this.#k?.commitOrRemove(),!this.hasSelection)return;const e=[];for(const t of this.#at){const i=t.serialize(!0);i&&e.push(i)}0!==e.length&&t.clipboardData.setData("application/pdfjs",JSON.stringify(e))}cut(t){this.copy(t),this.delete()}async paste(t){t.preventDefault();const{clipboardData:e}=t;for(const t of e.items)for(const e of this.#H)if(e.isHandlingMimeForPasting(t.type))return void e.paste(t,this.currentLayer);let i=e.getData("application/pdfjs");if(!i)return;try{i=JSON.parse(i)}catch(t){return void w(`paste: "${t.message}".`)}if(!Array.isArray(i))return;this.unselectAll();const s=this.currentLayer;try{const t=[];for(const e of i){const i=await s.deserialize(e);if(!i)return;t.push(i)}const e=()=>{for(const e of t)this.#kt(e);this.#It(t)},n=()=>{for(const e of t)e.remove()};this.addCommands({cmd:e,undo:n,mustExec:!0})}catch(t){w(`paste: "${t.message}".`)}}keydown(t){this.isShiftKeyDown||"Shift"!==t.key||(this.isShiftKeyDown=!0),this.#nt===h.NONE||this.isEditorHandlingKeyboard||Tt._keyboardManager.exec(this,t)}keyup(t){this.isShiftKeyDown&&"Shift"===t.key&&(this.isShiftKeyDown=!1,this.#K&&(this.#K=!1,this.#xt("main_toolbar")))}onEditingAction({name:t}){switch(t){case"undo":case"redo":case"delete":case"selectAll":this[t]();break;case"highlightSelection":this.highlightSelection("context_menu")}}#_t(t){Object.entries(t).some((([t,e])=>this.#ht[t]!==e))&&(this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(this.#ht,t)}),this.#nt===h.HIGHLIGHT&&!1===t.hasSelectedEditor&&this.#Pt([[d.HIGHLIGHT_FREE,!0]]))}#Pt(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})}setEditingState(t){t?(this.#Ct(),this.#Tt(),this.#_t({isEditing:this.#nt!==h.NONE,isEmpty:this.#Rt(),hasSomethingToUndo:this.#F.hasSomethingToUndo(),hasSomethingToRedo:this.#F.hasSomethingToRedo(),hasSelectedEditor:!1})):(this.#Et(),this.#Mt(),this.#_t({isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(t){if(!this.#H){this.#H=t;for(const t of this.#H)this.#Pt(t.defaultPropertiesToUpdate)}}getId(){return this.#Q.id}get currentLayer(){return this.#P.get(this.#O)}getLayer(t){return this.#P.get(t)}get currentPageIndex(){return this.#O}addLayer(t){this.#P.set(t.pageIndex,t),this.#J?t.enable():t.disable()}removeLayer(t){this.#P.delete(t.pageIndex)}async updateMode(t,e=null,i=!1){if(this.#nt!==t&&(!this.#gt||(await this.#gt.promise,this.#gt))){if(this.#gt=Promise.withResolvers(),this.#nt=t,t===h.NONE)return this.setEditingState(!1),this.#Dt(),void this.#gt.resolve();this.setEditingState(!0),await this.#Lt(),this.unselectAll();for(const e of this.#P.values())e.updateMode(t);if(!e)return i&&this.addNewEditorFromKeyboard(),void this.#gt.resolve();for(const t of this.#I.values())t.annotationElementId===e?(this.setSelected(t),t.enterInEditMode()):t.unselect();this.#gt.resolve()}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t!==this.#nt&&this._eventBus.dispatch("switchannotationeditormode",{source:this,mode:t})}updateParams(t,e){if(this.#H){switch(t){case d.CREATE:return void this.currentLayer.addNewEditor();case d.HIGHLIGHT_DEFAULT_COLOR:this.#it?.updateColor(e);break;case d.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}}),(this.#lt||=new Map).set(t,e),this.showAllEditors("highlight",e)}for(const i of this.#at)i.updateParams(t,e);for(const i of this.#H)i.updateDefaultParams(t,e)}}showAllEditors(t,e,i=!1){for(const i of this.#I.values())i.editorType===t&&i.show(e);(this.#lt?.get(d.HIGHLIGHT_SHOW_ALL)??!0)!==e&&this.#Pt([[d.HIGHLIGHT_SHOW_ALL,e]])}enableWaiting(t=!1){if(this.#Z!==t){this.#Z=t;for(const e of this.#P.values())t?e.disableClick():e.enableClick(),e.div.classList.toggle("waiting",t)}}async#Lt(){if(!this.#J){this.#J=!0;const t=[];for(const e of this.#P.values())t.push(e.enable());await Promise.all(t);for(const t of this.#I.values())t.enable()}}#Dt(){if(this.unselectAll(),this.#J){this.#J=!1;for(const t of this.#P.values())t.disable();for(const t of this.#I.values())t.disable()}}getEditors(t){const e=[];for(const i of this.#I.values())i.pageIndex===t&&e.push(i);return e}getEditor(t){return this.#I.get(t)}addEditor(t){this.#I.set(t.id,t)}removeEditor(t){t.div.contains(document.activeElement)&&(this.#V&&clearTimeout(this.#V),this.#V=setTimeout((()=>{this.focusMainContainer(),this.#V=null}),0)),this.#I.delete(t.id),this.unselect(t),t.annotationElementId&&this.#B.has(t.annotationElementId)||this.#D?.remove(t.id)}addDeletedAnnotationElement(t){this.#B.add(t.annotationElementId),this.addChangedExistingAnnotation(t),t.deleted=!0}isDeletedAnnotationElement(t){return this.#B.has(t)}removeDeletedAnnotationElement(t){this.#B.delete(t.annotationElementId),this.removeChangedExistingAnnotation(t),t.deleted=!1}#kt(t){const e=this.#P.get(t.pageIndex);e?e.addOrRebuild(t):(this.addEditor(t),this.addToAnnotationStorage(t))}setActiveEditor(t){this.#k!==t&&(this.#k=t,t&&this.#Pt(t.propertiesToUpdate))}get#Ft(){let t=null;for(t of this.#at);return t}updateUI(t){this.#Ft===t&&this.#Pt(t.propertiesToUpdate)}toggleSelected(t){if(this.#at.has(t))return this.#at.delete(t),t.unselect(),void this.#_t({hasSelectedEditor:this.hasSelection});this.#at.add(t),t.select(),this.#Pt(t.propertiesToUpdate),this.#_t({hasSelectedEditor:!0})}setSelected(t){for(const e of this.#at)e!==t&&e.unselect();this.#at.clear(),this.#at.add(t),t.select(),this.#Pt(t.propertiesToUpdate),this.#_t({hasSelectedEditor:!0})}isSelected(t){return this.#at.has(t)}get firstSelectedEditor(){return this.#at.values().next().value}unselect(t){t.unselect(),this.#at.delete(t),this.#_t({hasSelectedEditor:this.hasSelection})}get hasSelection(){return 0!==this.#at.size}get isEnterHandled(){return 1===this.#at.size&&this.firstSelectedEditor.isEnterHandled}undo(){this.#F.undo(),this.#_t({hasSomethingToUndo:this.#F.hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:this.#Rt()})}redo(){this.#F.redo(),this.#_t({hasSomethingToUndo:!0,hasSomethingToRedo:this.#F.hasSomethingToRedo(),isEmpty:this.#Rt()})}addCommands(t){this.#F.add(t),this.#_t({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#Rt()})}#Rt(){if(0===this.#I.size)return!0;if(1===this.#I.size)for(const t of this.#I.values())return t.isEmpty();return!1}delete(){if(this.commitOrRemove(),!this.hasSelection)return;const t=[...this.#at];this.addCommands({cmd:()=>{for(const e of t)e.remove()},undo:()=>{for(const e of t)this.#kt(e)},mustExec:!0})}commitOrRemove(){this.#k?.commitOrRemove()}hasSomethingToControl(){return this.#k||this.hasSelection}#It(t){for(const t of this.#at)t.unselect();this.#at.clear();for(const e of t)e.isEmpty()||(this.#at.add(e),e.select());this.#_t({hasSelectedEditor:this.hasSelection})}selectAll(){for(const t of this.#at)t.commit();this.#It(this.#I.values())}unselectAll(){if((!this.#k||(this.#k.commitOrRemove(),this.#nt===h.NONE))&&this.hasSelection){for(const t of this.#at)t.unselect();this.#at.clear(),this.#_t({hasSelectedEditor:!1})}}translateSelectedEditors(t,e,i=!1){if(i||this.commitOrRemove(),!this.hasSelection)return;this.#dt[0]+=t,this.#dt[1]+=e;const[s,n]=this.#dt,a=[...this.#at];this.#ct&&clearTimeout(this.#ct),this.#ct=setTimeout((()=>{this.#ct=null,this.#dt[0]=this.#dt[1]=0,this.addCommands({cmd:()=>{for(const t of a)this.#I.has(t.id)&&t.translateInPage(s,n)},undo:()=>{for(const t of a)this.#I.has(t.id)&&t.translateInPage(-s,-n)},mustExec:!1})}),1e3);for(const i of a)i.translateInPage(t,e)}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0),this.#z=new Map;for(const t of this.#at)this.#z.set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!this.#z)return!1;this.disableUserSelect(!1);const t=this.#z;this.#z=null;let e=!1;for(const[{x:i,y:s,pageIndex:n},a]of t)a.newX=i,a.newY=s,a.newPageIndex=n,e||=i!==a.savedX||s!==a.savedY||n!==a.savedPageIndex;if(!e)return!1;const i=(t,e,i,s)=>{if(this.#I.has(t.id)){const n=this.#P.get(s);n?t._setParentAndPosition(n,e,i):(t.pageIndex=s,t.x=e,t.y=i)}};return this.addCommands({cmd:()=>{for(const[e,{newX:s,newY:n,newPageIndex:a}]of t)i(e,s,n,a)},undo:()=>{for(const[e,{savedX:s,savedY:n,savedPageIndex:a}]of t)i(e,s,n,a)},mustExec:!0}),!0}dragSelectedEditors(t,e){if(this.#z)for(const i of this.#z.keys())i.drag(t,e)}rebuild(t){if(null===t.parent){const e=this.getLayer(t.pageIndex);e?(e.changeParent(t),e.addOrRebuild(t)):(this.addEditor(t),this.addToAnnotationStorage(t),t.rebuild())}else t.parent.addOrRebuild(t)}get isEditorHandlingKeyboard(){return this.getActive()?.shouldGetKeyboardEvents()||1===this.#at.size&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(t){return this.#k===t}getActive(){return this.#k}getMode(){return this.#nt}get imageManager(){return E(this,"imageManager",new xt)}getSelectionBoxes(t){if(!t)return null;const e=document.getSelection();for(let i=0,s=e.rangeCount;i({x:(e-s)/a,y:1-(t+r-i)/n,width:o/a,height:r/n});break;case"180":r=(t,e,r,o)=>({x:1-(t+r-i)/n,y:1-(e+o-s)/a,width:r/n,height:o/a});break;case"270":r=(t,e,r,o)=>({x:1-(e+o-s)/a,y:(t-i)/n,width:o/a,height:r/n});break;default:r=(t,e,r,o)=>({x:(t-i)/n,y:(e-s)/a,width:r/n,height:o/a})}const o=[];for(let t=0,i=e.rangeCount;tt.stopPropagation()),{signal:i});const s=t=>{t.preventDefault(),this.#a._uiManager.editAltText(this.#a),this.#Wt&&this.#a._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:this.#Vt}})};return t.addEventListener("click",s,{capture:!0,signal:i}),t.addEventListener("keydown",(e=>{e.target===t&&"Enter"===e.key&&(this.#Ht=!0,s(e))}),{signal:i}),await this.#qt(),t}get#Vt(){return(this.#o?"added":null===this.#o&&this.guessedText&&"review")||"missing"}finish(){this.#Ot&&(this.#Ot.focus({focusVisible:this.#Ht}),this.#Ht=!1)}isEmpty(){return this.#Wt?null===this.#o:!this.#o&&!this.#Nt}hasData(){return this.#Wt?null!==this.#o||!!this.#Ut:this.isEmpty()}get guessedText(){return this.#Ut}async setGuessedText(t){null===this.#o&&(this.#Ut=t,this.#$t=await Mt._l10nPromise.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer")({generatedAltText:t}),this.#qt())}toggleAltTextBadge(t=!1){if(!this.#Wt||this.#o)return this.#jt?.remove(),void(this.#jt=null);if(!this.#jt){const t=this.#jt=document.createElement("div");t.className="noAltTextBadge",this.#a.div.append(t)}this.#jt.classList.toggle("hidden",!t)}serialize(t){let e=this.#o;return t||this.#Ut!==e||(e=this.#$t),{altText:e,decorative:this.#Nt,guessedText:this.#Ut,textWithDisclaimer:this.#$t}}get data(){return{altText:this.#o,decorative:this.#Nt}}set data({altText:t,decorative:e,guessedText:i,textWithDisclaimer:s,cancel:n=!1}){i&&(this.#Ut=i,this.#$t=s),this.#o===t&&this.#Nt===e||(n||(this.#o=t,this.#Nt=e),this.#qt())}toggle(t=!1){this.#Ot&&(!t&&this.#zt&&(clearTimeout(this.#zt),this.#zt=null),this.#Ot.disabled=!t)}shown(){this.#a._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:this.#Vt}})}destroy(){this.#Ot?.remove(),this.#Ot=null,this.#Bt=null,this.#jt?.remove(),this.#jt=null}async#qt(){const t=this.#Ot;if(!t)return;if(this.#Wt){if(t.classList.toggle("done",!!this.#o),Mt._l10nPromise.get(Mt.#Gt[this.#Vt]).then((e=>{t.setAttribute("aria-label",e);for(const i of t.childNodes)if(i.nodeType===Node.TEXT_NODE){i.textContent=e;break}})),!this.#o)return void this.#Bt?.remove()}else{if(!this.#o&&!this.#Nt)return t.classList.remove("done"),void this.#Bt?.remove();t.classList.add("done"),Mt._l10nPromise.get("pdfjs-editor-alt-text-edit-button-label").then((e=>{t.setAttribute("aria-label",e)}))}let e=this.#Bt;if(!e){this.#Bt=e=document.createElement("span"),e.className="tooltip",e.setAttribute("role","tooltip"),e.id=`alt-text-tooltip-${this.#a.id}`;const i=100,s=this.#a._uiManager._signal;s.addEventListener("abort",(()=>{clearTimeout(this.#zt),this.#zt=null}),{once:!0}),t.addEventListener("mouseenter",(()=>{this.#zt=setTimeout((()=>{this.#zt=null,this.#Bt.classList.add("show"),this.#a._reportTelemetry({action:"alt_text_tooltip"})}),i)}),{signal:s}),t.addEventListener("mouseleave",(()=>{this.#zt&&(clearTimeout(this.#zt),this.#zt=null),this.#Bt?.classList.remove("show")}),{signal:s})}e.innerText=this.#Nt?await Mt._l10nPromise.get("pdfjs-editor-alt-text-decorative-tooltip"):this.#o,e.parentNode||t.append(e),this.#a.getImageForAltText()?.setAttribute("aria-describedby",e.id)}}class kt{#Xt=null;#Kt=null;#o=null;#Yt=!1;#Qt=!1;#Jt=null;#Zt=null;#te=null;#ee="";#ie=!1;#se=null;#ne=!1;#ae=!1;#re=!1;#oe=null;#le=0;#he=0;#de=null;_editToolbar=null;_initialOptions=Object.create(null);_initialData=null;_isVisible=!0;_uiManager=null;_focusEventsAllowed=!0;static _l10nPromise=null;static _l10nResizer=null;#ce=!1;#ue=kt._zIndex++;static _borderLineWidth=-1;static _colorManager=new St;static _zIndex=1;static _telemetryTimeout=1e3;static get _resizerKeyboardManager(){const t=kt.prototype._resizeWithKeyboard,e=Tt.TRANSLATE_SMALL,i=Tt.TRANSLATE_BIG;return E(this,"_resizerKeyboardManager",new Et([[["ArrowLeft","mac+ArrowLeft"],t,{args:[-e,0]}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t,{args:[-i,0]}],[["ArrowRight","mac+ArrowRight"],t,{args:[e,0]}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t,{args:[i,0]}],[["ArrowUp","mac+ArrowUp"],t,{args:[0,-e]}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t,{args:[0,-i]}],[["ArrowDown","mac+ArrowDown"],t,{args:[0,e]}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t,{args:[0,i]}],[["Escape","mac+Escape"],kt.prototype._stopResizingWithKeyboard]]))}constructor(t){this.parent=t.parent,this.id=t.id,this.width=this.height=null,this.pageIndex=t.parent.pageIndex,this.name=t.name,this.div=null,this._uiManager=t.uiManager,this.annotationElementId=null,this._willKeepAspectRatio=!1,this._initialOptions.isCentered=t.isCentered,this._structTreeParentId=null;const{rotation:e,rawDims:{pageWidth:i,pageHeight:s,pageX:n,pageY:a}}=this.parent.viewport;this.rotation=e,this.pageRotation=(360+e-this._uiManager.viewParameters.rotation)%360,this.pageDimensions=[i,s],this.pageTranslation=[n,a];const[r,o]=this.parentDimensions;this.x=t.x/r,this.y=t.y/o,this.isAttachedToDOM=!1,this.deleted=!1}get editorType(){return Object.getPrototypeOf(this).constructor._type}static get _defaultLineColor(){return E(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){const e=new It({id:t.parent.getNextId(),parent:t.parent,uiManager:t._uiManager});e.annotationElementId=t.annotationElementId,e.deleted=!0,e._uiManager.addToAnnotationStorage(e)}static initialize(t,e,i){if(kt._l10nResizer||=Object.freeze({topLeft:"pdfjs-editor-resizer-top-left",topMiddle:"pdfjs-editor-resizer-top-middle",topRight:"pdfjs-editor-resizer-top-right",middleRight:"pdfjs-editor-resizer-middle-right",bottomRight:"pdfjs-editor-resizer-bottom-right",bottomMiddle:"pdfjs-editor-resizer-bottom-middle",bottomLeft:"pdfjs-editor-resizer-bottom-left",middleLeft:"pdfjs-editor-resizer-middle-left"}),kt._l10nPromise||=new Map([...["pdfjs-editor-alt-text-button-label","pdfjs-editor-alt-text-edit-button-label","pdfjs-editor-alt-text-decorative-tooltip","pdfjs-editor-new-alt-text-added-button-label","pdfjs-editor-new-alt-text-missing-button-label","pdfjs-editor-new-alt-text-to-review-button-label"].map((e=>[e,t.get(e)])),...["pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer"].map((e=>[e,t.get.bind(t,e)]))]),i?.strings)for(const e of i.strings)kt._l10nPromise.set(e,t.get(e));if(-1!==kt._borderLineWidth)return;const s=getComputedStyle(document.documentElement);kt._borderLineWidth=parseFloat(s.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,e){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return!1}static paste(t,e){_("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return this.#ce}set _isDraggable(t){this.#ce=t,this.div?.classList.toggle("draggable",t)}get isEnterHandled(){return!0}center(){const[t,e]=this.pageDimensions;switch(this.parentRotation){case 90:this.x-=this.height*e/(2*t),this.y+=this.width*t/(2*e);break;case 180:this.x+=this.width/2,this.y+=this.height/2;break;case 270:this.x+=this.height*e/(2*t),this.y-=this.width*t/(2*e);break;default:this.x-=this.width/2,this.y-=this.height/2}this.fixAndSetPosition()}addCommands(t){this._uiManager.addCommands(t)}get currentLayer(){return this._uiManager.currentLayer}setInBackground(){this.div.style.zIndex=0}setInForeground(){this.div.style.zIndex=this.#ue}setParent(t){null!==t?(this.pageIndex=t.pageIndex,this.pageDimensions=t.pageDimensions):this.#pe(),this.parent=t}focusin(t){this._focusEventsAllowed&&(this.#ie?this.#ie=!1:this.parent.setSelected(this))}focusout(t){this._focusEventsAllowed&&this.isAttachedToDOM&&(t.relatedTarget?.closest(`#${this.id}`)||(t.preventDefault(),this.parent?.isMultipleSelection||this.commitOrRemove()))}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.addToAnnotationStorage()}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(t,e,i,s){const[n,a]=this.parentDimensions;[i,s]=this.screenToPageTranslation(i,s),this.x=(t+i)/n,this.y=(e+s)/a,this.fixAndSetPosition()}#ge([t,e],i,s){[i,s]=this.screenToPageTranslation(i,s),this.x+=i/t,this.y+=s/e,this.fixAndSetPosition()}translate(t,e){this.#ge(this.parentDimensions,t,e)}translateInPage(t,e){this.#se||=[this.x,this.y],this.#ge(this.pageDimensions,t,e),this.div.scrollIntoView({block:"nearest"})}drag(t,e){this.#se||=[this.x,this.y];const[i,s]=this.parentDimensions;if(this.x+=t/i,this.y+=e/s,this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){const{x:t,y:e}=this.div.getBoundingClientRect();this.parent.findNewParent(this,t,e)&&(this.x-=Math.floor(this.x),this.y-=Math.floor(this.y))}let{x:n,y:a}=this;const[r,o]=this.getBaseTranslation();n+=r,a+=o,this.div.style.left=`${(100*n).toFixed(2)}%`,this.div.style.top=`${(100*a).toFixed(2)}%`,this.div.scrollIntoView({block:"nearest"})}get _hasBeenMoved(){return!!this.#se&&(this.#se[0]!==this.x||this.#se[1]!==this.y)}getBaseTranslation(){const[t,e]=this.parentDimensions,{_borderLineWidth:i}=kt,s=i/t,n=i/e;switch(this.rotation){case 90:return[-s,n];case 180:return[s,n];case 270:return[s,-n];default:return[-s,-n]}}get _mustFixPosition(){return!0}fixAndSetPosition(t=this.rotation){const[e,i]=this.pageDimensions;let{x:s,y:n,width:a,height:r}=this;if(a*=e,r*=i,s*=e,n*=i,this._mustFixPosition)switch(t){case 0:s=Math.max(0,Math.min(e-a,s)),n=Math.max(0,Math.min(i-r,n));break;case 90:s=Math.max(0,Math.min(e-r,s)),n=Math.min(i,Math.max(a,n));break;case 180:s=Math.min(e,Math.max(a,s)),n=Math.min(i,Math.max(r,n));break;case 270:s=Math.min(e,Math.max(r,s)),n=Math.max(0,Math.min(i-a,n))}this.x=s/=e,this.y=n/=i;const[o,l]=this.getBaseTranslation();s+=o,n+=l;const{style:h}=this.div;h.left=`${(100*s).toFixed(2)}%`,h.top=`${(100*n).toFixed(2)}%`,this.moveInDOM()}static#me(t,e,i){switch(i){case 90:return[e,-t];case 180:return[-t,-e];case 270:return[-e,t];default:return[t,e]}}screenToPageTranslation(t,e){return kt.#me(t,e,this.parentRotation)}pageTranslationToScreen(t,e){return kt.#me(t,e,360-this.parentRotation)}#fe(t){switch(t){case 90:{const[t,e]=this.pageDimensions;return[0,-t/e,e/t,0]}case 180:return[-1,0,0,-1];case 270:{const[t,e]=this.pageDimensions;return[0,t/e,-e/t,0]}default:return[1,0,0,1]}}get parentScale(){return this._uiManager.viewParameters.realScale}get parentRotation(){return(this._uiManager.viewParameters.rotation+this.pageRotation)%360}get parentDimensions(){const{parentScale:t,pageDimensions:[e,i]}=this;return[e*t,i*t]}setDims(t,e){const[i,s]=this.parentDimensions;this.div.style.width=`${(100*t/i).toFixed(2)}%`,this.#Qt||(this.div.style.height=`${(100*e/s).toFixed(2)}%`)}fixDims(){const{style:t}=this.div,{height:e,width:i}=t,s=i.endsWith("%"),n=!this.#Qt&&e.endsWith("%");if(s&&n)return;const[a,r]=this.parentDimensions;s||(t.width=`${(100*parseFloat(i)/a).toFixed(2)}%`),this.#Qt||n||(t.height=`${(100*parseFloat(e)/r).toFixed(2)}%`)}getInitialTranslation(){return[0,0]}#be(){if(this.#Jt)return;this.#Jt=document.createElement("div"),this.#Jt.classList.add("resizers");const t=this._willKeepAspectRatio?["topLeft","topRight","bottomRight","bottomLeft"]:["topLeft","topMiddle","topRight","middleRight","bottomRight","bottomMiddle","bottomLeft","middleLeft"],e=this._uiManager._signal;for(const i of t){const t=document.createElement("div");this.#Jt.append(t),t.classList.add("resizer",i),t.setAttribute("data-resizer-name",i),t.addEventListener("pointerdown",this.#ve.bind(this,i),{signal:e}),t.addEventListener("contextmenu",ht,{signal:e}),t.tabIndex=-1}this.div.prepend(this.#Jt)}#ve(t,e){e.preventDefault();const{isMac:i}=O.platform;if(0!==e.button||e.ctrlKey&&i)return;this.#o?.toggle(!1);const s=this._isDraggable;this._isDraggable=!1;const n=new AbortController,a=this._uiManager.combinedSignal(n);this.parent.togglePointerEvents(!1),window.addEventListener("pointermove",this.#Ae.bind(this,t),{passive:!0,capture:!0,signal:a}),window.addEventListener("contextmenu",ht,{signal:a});const r=this.x,o=this.y,l=this.width,h=this.height,d=this.parent.div.style.cursor,c=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(e.target).cursor;const u=()=>{n.abort(),this.parent.togglePointerEvents(!0),this.#o?.toggle(!0),this._isDraggable=s,this.parent.div.style.cursor=d,this.div.style.cursor=c,this.#ye(r,o,l,h)};window.addEventListener("pointerup",u,{signal:a}),window.addEventListener("blur",u,{signal:a})}#ye(t,e,i,s){const n=this.x,a=this.y,r=this.width,o=this.height;n===t&&a===e&&r===i&&o===s||this.addCommands({cmd:()=>{this.width=r,this.height=o,this.x=n,this.y=a;const[t,e]=this.parentDimensions;this.setDims(t*r,e*o),this.fixAndSetPosition()},undo:()=>{this.width=i,this.height=s,this.x=t,this.y=e;const[n,a]=this.parentDimensions;this.setDims(n*i,a*s),this.fixAndSetPosition()},mustExec:!0})}#Ae(t,e){const[i,s]=this.parentDimensions,n=this.x,a=this.y,r=this.width,o=this.height,l=kt.MIN_SIZE/i,h=kt.MIN_SIZE/s,d=t=>Math.round(1e4*t)/1e4,c=this.#fe(this.rotation),u=(t,e)=>[c[0]*t+c[2]*e,c[1]*t+c[3]*e],p=this.#fe(360-this.rotation);let g,m,f=!1,b=!1;switch(t){case"topLeft":f=!0,g=(t,e)=>[0,0],m=(t,e)=>[t,e];break;case"topMiddle":g=(t,e)=>[t/2,0],m=(t,e)=>[t/2,e];break;case"topRight":f=!0,g=(t,e)=>[t,0],m=(t,e)=>[0,e];break;case"middleRight":b=!0,g=(t,e)=>[t,e/2],m=(t,e)=>[0,e/2];break;case"bottomRight":f=!0,g=(t,e)=>[t,e],m=(t,e)=>[0,0];break;case"bottomMiddle":g=(t,e)=>[t/2,e],m=(t,e)=>[t/2,0];break;case"bottomLeft":f=!0,g=(t,e)=>[0,e],m=(t,e)=>[t,0];break;case"middleLeft":b=!0,g=(t,e)=>[0,e/2],m=(t,e)=>[t,e/2]}const v=g(r,o),A=m(r,o);let y=u(...A);const w=d(n+y[0]),_=d(a+y[1]);let x=1,C=1,[E,S]=this.screenToPageTranslation(e.movementX,e.movementY);var T,M;if([E,S]=(T=E/i,M=S/s,[p[0]*T+p[2]*M,p[1]*T+p[3]*M]),f){const t=Math.hypot(r,o);x=C=Math.max(Math.min(Math.hypot(A[0]-v[0]-E,A[1]-v[1]-S)/t,1/r,1/o),l/r,h/o)}else b?x=Math.max(l,Math.min(1,Math.abs(A[0]-v[0]-E)))/r:C=Math.max(h,Math.min(1,Math.abs(A[1]-v[1]-S)))/o;const k=d(r*x),I=d(o*C);y=u(...m(k,I));const P=w-y[0],R=_-y[1];this.width=k,this.height=I,this.x=P,this.y=R,this.setDims(i*k,s*I),this.fixAndSetPosition()}altTextFinish(){this.#o?.finish()}async addEditToolbar(){return this._editToolbar||this.#ae||(this._editToolbar=new At(this),this.div.append(this._editToolbar.render()),this.#o&&await this._editToolbar.addAltText(this.#o)),this._editToolbar}removeEditToolbar(){this._editToolbar&&(this._editToolbar.remove(),this._editToolbar=null,this.#o?.destroy())}addContainer(t){const e=this._editToolbar?.div;e?e.before(t):this.div.append(t)}getClientDimensions(){return this.div.getBoundingClientRect()}async addAltTextButton(){this.#o||(Mt.initialize(kt._l10nPromise),this.#o=new Mt(this),this.#Xt&&(this.#o.data=this.#Xt,this.#Xt=null),await this.addEditToolbar())}get altTextData(){return this.#o?.data}set altTextData(t){this.#o&&(this.#o.data=t)}get guessedAltText(){return this.#o?.guessedText}async setGuessedAltText(t){await(this.#o?.setGuessedText(t))}serializeAltText(t){return this.#o?.serialize(t)}hasAltText(){return!!this.#o&&!this.#o.isEmpty()}hasAltTextData(){return this.#o?.hasData()??!1}render(){this.div=document.createElement("div"),this.div.setAttribute("data-editor-rotation",(360-this.rotation)%360),this.div.className=this.name,this.div.setAttribute("id",this.id),this.div.tabIndex=this.#Yt?-1:0,this._isVisible||this.div.classList.add("hidden"),this.setInForeground(),this.#we();const[t,e]=this.parentDimensions;this.parentRotation%180!=0&&(this.div.style.maxWidth=`${(100*e/t).toFixed(2)}%`,this.div.style.maxHeight=`${(100*t/e).toFixed(2)}%`);const[i,s]=this.getInitialTranslation();return this.translate(i,s),wt(this,this.div,["pointerdown"]),this.div}pointerdown(t){const{isMac:e}=O.platform;0!==t.button||t.ctrlKey&&e?t.preventDefault():(this.#ie=!0,this._isDraggable?this.#_e(t):this.#xe(t))}#xe(t){const{isMac:e}=O.platform;t.ctrlKey&&!e||t.shiftKey||t.metaKey&&e?this.parent.toggleSelected(this):this.parent.setSelected(this)}#_e(t){const e=this._uiManager.isSelected(this);this._uiManager.setUpDragSession();const i=new AbortController,s=this._uiManager.combinedSignal(i);if(e){this.div.classList.add("moving"),this.#le=t.clientX,this.#he=t.clientY;const e=t=>{const{clientX:e,clientY:i}=t,[s,n]=this.screenToPageTranslation(e-this.#le,i-this.#he);this.#le=e,this.#he=i,this._uiManager.dragSelectedEditors(s,n)};window.addEventListener("pointermove",e,{passive:!0,capture:!0,signal:s})}const n=()=>{i.abort(),e&&this.div.classList.remove("moving"),this.#ie=!1,this._uiManager.endDragSession()||this.#xe(t)};window.addEventListener("pointerup",n,{signal:s}),window.addEventListener("blur",n,{signal:s})}moveInDOM(){this.#oe&&clearTimeout(this.#oe),this.#oe=setTimeout((()=>{this.#oe=null,this.parent?.moveEditorInDOM(this)}),0)}_setParentAndPosition(t,e,i){t.changeParent(this),this.x=e,this.y=i,this.fixAndSetPosition()}getRect(t,e,i=this.rotation){const s=this.parentScale,[n,a]=this.pageDimensions,[r,o]=this.pageTranslation,l=t/s,h=e/s,d=this.x*n,c=this.y*a,u=this.width*n,p=this.height*a;switch(i){case 0:return[d+l+r,a-c-h-p+o,d+l+u+r,a-c-h+o];case 90:return[d+h+r,a-c+l+o,d+h+p+r,a-c+l+u+o];case 180:return[d-l-u+r,a-c+h+o,d-l+r,a-c+h+p+o];case 270:return[d-h-p+r,a-c-l-u+o,d-h+r,a-c-l+o];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(t,e){const[i,s,n,a]=t,r=n-i,o=a-s;switch(this.rotation){case 0:return[i,e-a,r,o];case 90:return[i,e-s,o,r];case 180:return[n,e-s,r,o];case 270:return[n,e-a,o,r];default:throw new Error("Invalid rotation")}}onceAdded(){}isEmpty(){return!1}enableEditMode(){this.#ae=!0}disableEditMode(){this.#ae=!1}isInEditMode(){return this.#ae}shouldGetKeyboardEvents(){return this.#re}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}#we(){if(this.#te||!this.div)return;this.#te=new AbortController;const t=this._uiManager.combinedSignal(this.#te);this.div.addEventListener("focusin",this.focusin.bind(this),{signal:t}),this.div.addEventListener("focusout",this.focusout.bind(this),{signal:t})}rebuild(){this.#we()}rotate(t){}serializeDeleted(){return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex,popupRef:this._initialData?.popupRef||""}}serialize(t=!1,e=null){_("An editor must be serializable")}static async deserialize(t,e,i){const s=new this.prototype.constructor({parent:e,id:e.getNextId(),uiManager:i});s.rotation=t.rotation,s.#Xt=t.accessibilityData;const[n,a]=s.pageDimensions,[r,o,l,h]=s.getRectInCurrentCoords(t.rect,a);return s.x=r/n,s.y=o/a,s.width=l/n,s.height=h/a,s}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||null!==this.serialize())}remove(){if(this.#te?.abort(),this.#te=null,this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),this.#oe&&(clearTimeout(this.#oe),this.#oe=null),this.#pe(),this.removeEditToolbar(),this.#de){for(const t of this.#de.values())clearTimeout(t);this.#de=null}this.parent=null}get isResizable(){return!1}makeResizable(){this.isResizable&&(this.#be(),this.#Jt.classList.remove("hidden"),wt(this,this.div,["keydown"]))}get toolbarPosition(){return null}keydown(t){if(!this.isResizable||t.target!==this.div||"Enter"!==t.key)return;this._uiManager.setSelected(this),this.#Zt={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const e=this.#Jt.children;if(!this.#Kt){this.#Kt=Array.from(e);const t=this.#Ce.bind(this),i=this.#Ee.bind(this),s=this._uiManager._signal;for(const e of this.#Kt){const n=e.getAttribute("data-resizer-name");e.setAttribute("role","spinbutton"),e.addEventListener("keydown",t,{signal:s}),e.addEventListener("blur",i,{signal:s}),e.addEventListener("focus",this.#Se.bind(this,n),{signal:s}),e.setAttribute("data-l10n-id",kt._l10nResizer[n])}}const i=this.#Kt[0];let s=0;for(const t of e){if(t===i)break;s++}const n=(360-this.rotation+this.parentRotation)%360/90*(this.#Kt.length/4);if(n!==s){if(ns)for(let t=0;t{this.div?.classList.contains("selectedEditor")&&this._editToolbar?.show()}))}unselect(){this.#Jt?.classList.add("hidden"),this.div?.classList.remove("selectedEditor"),this.div?.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0}),this._editToolbar?.hide(),this.#o?.toggleAltTextBadge(!0)}updateParams(t,e){}disableEditing(){}enableEditing(){}enterInEditMode(){}getImageForAltText(){return null}get contentDiv(){return this.div}get isEditing(){return this.#ne}set isEditing(t){this.#ne=t,this.parent&&(t?(this.parent.setSelected(this),this.parent.setActiveEditor(this)):this.parent.setActiveEditor(null))}setAspectRatio(t,e){this.#Qt=!0;const i=t/e,{style:s}=this.div;s.aspectRatio=i,s.height="auto"}static get MIN_SIZE(){return 16}static canCreateNewEmptyEditor(){return!0}get telemetryInitialData(){return{action:"added"}}get telemetryFinalData(){return null}_reportTelemetry(t,e=!1){if(e){this.#de||=new Map;const{action:e}=t;let i=this.#de.get(e);return i&&clearTimeout(i),i=setTimeout((()=>{this._reportTelemetry(t),this.#de.delete(e),0===this.#de.size&&(this.#de=null)}),kt._telemetryTimeout),void this.#de.set(e,i)}t.type||=this.editorType,this._uiManager._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:t}})}show(t=this._isVisible){this.div.classList.toggle("hidden",!t),this._isVisible=t}enable(){this.div&&(this.div.tabIndex=0),this.#Yt=!1}disable(){this.div&&(this.div.tabIndex=-1),this.#Yt=!0}renderAnnotationElement(t){let e=t.container.querySelector(".annotationContent");if(e){if("CANVAS"===e.nodeName){const t=e;e=document.createElement("div"),e.classList.add("annotationContent",this.editorType),t.before(e)}}else e=document.createElement("div"),e.classList.add("annotationContent",this.editorType),t.container.prepend(e);return e}resetAnnotationElement(t){const{firstChild:e}=t.container;"DIV"===e?.nodeName&&e.classList.contains("annotationContent")&&e.remove()}}class It extends kt{constructor(t){super(t),this.annotationElementId=t.annotationElementId,this.deleted=!0}serialize(){return this.serializeDeleted()}}const Pt=3285377520,Rt=4294901760,Dt=65535;class Lt{constructor(t){this.h1=t?4294967295&t:Pt,this.h2=t?4294967295&t:Pt}update(t){let e,i;if("string"==typeof t){e=new Uint8Array(2*t.length),i=0;for(let s=0,n=t.length;s>>8,e[i++]=255&n)}}else{if(!ArrayBuffer.isView(t))throw new Error("Invalid data format, must be a string or TypedArray.");e=t.slice(),i=e.byteLength}const s=i>>2,n=i-4*s,a=new Uint32Array(e.buffer,0,s);let r=0,o=0,l=this.h1,h=this.h2;const d=3432918353,c=461845907,u=11601,p=13715;for(let t=0;t>>17,r=r*c&Rt|r*p&Dt,l^=r,l=l<<13|l>>>19,l=5*l+3864292196):(o=a[t],o=o*d&Rt|o*u&Dt,o=o<<15|o>>>17,o=o*c&Rt|o*p&Dt,h^=o,h=h<<13|h>>>19,h=5*h+3864292196);switch(r=0,n){case 3:r^=e[4*s+2]<<16;case 2:r^=e[4*s+1]<<8;case 1:r^=e[4*s],r=r*d&Rt|r*u&Dt,r=r<<15|r>>>17,r=r*c&Rt|r*p&Dt,1&s?l^=r:h^=r}this.h1=l,this.h2=h}hexdigest(){let t=this.h1,e=this.h2;return t^=e>>>1,t=3981806797*t&Rt|36045*t&Dt,e=4283543511*e&Rt|(2950163797*(e<<16|t>>>16)&Rt)>>>16,t^=e>>>1,t=444984403*t&Rt|60499*t&Dt,e=3301882366*e&Rt|(3120437893*(e<<16|t>>>16)&Rt)>>>16,t^=e>>>1,(t>>>0).toString(16).padStart(8,"0")+(e>>>0).toString(16).padStart(8,"0")}}const Ft=Object.freeze({map:null,hash:"",transfer:void 0});class Nt{#Me=!1;#ke=null;#Ie=new Map;constructor(){this.onSetModified=null,this.onResetModified=null,this.onAnnotationEditor=null}getValue(t,e){const i=this.#Ie.get(t);return void 0===i?e:Object.assign(e,i)}getRawValue(t){return this.#Ie.get(t)}remove(t){if(this.#Ie.delete(t),0===this.#Ie.size&&this.resetModified(),"function"==typeof this.onAnnotationEditor){for(const t of this.#Ie.values())if(t instanceof kt)return;this.onAnnotationEditor(null)}}setValue(t,e){const i=this.#Ie.get(t);let s=!1;if(void 0!==i)for(const[t,n]of Object.entries(e))i[t]!==n&&(s=!0,i[t]=n);else s=!0,this.#Ie.set(t,e);s&&this.#Pe(),e instanceof kt&&"function"==typeof this.onAnnotationEditor&&this.onAnnotationEditor(e.constructor._type)}has(t){return this.#Ie.has(t)}getAll(){return this.#Ie.size>0?N(this.#Ie):null}setAll(t){for(const[e,i]of Object.entries(t))this.setValue(e,i)}get size(){return this.#Ie.size}#Pe(){this.#Me||(this.#Me=!0,"function"==typeof this.onSetModified&&this.onSetModified())}resetModified(){this.#Me&&(this.#Me=!1,"function"==typeof this.onResetModified&&this.onResetModified())}get print(){return new Ot(this)}get serializable(){if(0===this.#Ie.size)return Ft;const t=new Map,e=new Lt,i=[],s=Object.create(null);let n=!1;for(const[i,a]of this.#Ie){const r=a instanceof kt?a.serialize(!1,s):a;r&&(t.set(i,r),e.update(`${i}:${JSON.stringify(r)}`),n||=!!r.bitmap)}if(n)for(const e of t.values())e.bitmap&&i.push(e.bitmap);return t.size>0?{map:t,hash:e.hexdigest(),transfer:i}:Ft}get editorStats(){let t=null;const e=new Map;for(const i of this.#Ie.values()){if(!(i instanceof kt))continue;const s=i.telemetryFinalData;if(!s)continue;const{type:n}=s;e.has(n)||e.set(n,Object.getPrototypeOf(i).constructor),t||=Object.create(null);const a=t[n]||=new Map;for(const[t,e]of Object.entries(s)){if("type"===t)continue;let i=a.get(t);i||(i=new Map,a.set(t,i));const s=i.get(e)??0;i.set(e,s+1)}}for(const[i,s]of e)t[i]=s.computeTelemetryFinalData(t[i]);return t}resetModifiedIds(){this.#ke=null}get modifiedIds(){if(this.#ke)return this.#ke;const t=[];for(const e of this.#Ie.values())e instanceof kt&&e.annotationElementId&&e.serialize()&&t.push(e.annotationElementId);return this.#ke={ids:new Set(t),hash:t.join(",")}}}class Ot extends Nt{#Re;constructor(t){super();const{map:e,hash:i,transfer:s}=t.serializable,n=structuredClone(e,s?{transfer:s}:null);this.#Re={map:n,hash:i,transfer:s}}get print(){_("Should not call PrintAnnotationStorage.print")}get serializable(){return this.#Re}get modifiedIds(){return E(this,"modifiedIds",{ids:new Set,hash:""})}}class Bt{#De=new Set;constructor({ownerDocument:t=globalThis.document,styleElement:e=null}){this._document=t,this.nativeFontFaces=new Set,this.styleElement=null,this.loadingRequests=[],this.loadTestFontId=0}addNativeFontFace(t){this.nativeFontFaces.add(t),this._document.fonts.add(t)}removeNativeFontFace(t){this.nativeFontFaces.delete(t),this._document.fonts.delete(t)}insertRule(t){this.styleElement||(this.styleElement=this._document.createElement("style"),this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement));const e=this.styleElement.sheet;e.insertRule(t,e.cssRules.length)}clear(){for(const t of this.nativeFontFaces)this._document.fonts.delete(t);this.nativeFontFaces.clear(),this.#De.clear(),this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}async loadSystemFont({systemFontInfo:t,_inspectFont:e}){if(t&&!this.#De.has(t.loadedName))if(x(!this.disableFontFace,"loadSystemFont shouldn't be called when `disableFontFace` is set."),this.isFontLoadingAPISupported){const{loadedName:i,src:s,style:n}=t,a=new FontFace(i,s,n);this.addNativeFontFace(a);try{await a.load(),this.#De.add(i),e?.(t)}catch{w(`Cannot load system font: ${t.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(a)}}else _("Not implemented: loadSystemFont without the Font Loading API.")}async bind(t){if(t.attached||t.missingFile&&!t.systemFontInfo)return;if(t.attached=!0,t.systemFontInfo)return void await this.loadSystemFont(t);if(this.isFontLoadingAPISupported){const e=t.createNativeFontFace();if(e){this.addNativeFontFace(e);try{await e.loaded}catch(i){throw w(`Failed to load font '${e.family}': '${i}'.`),t.disableFontFace=!0,i}}return}const e=t.createFontFaceRule();if(e){if(this.insertRule(e),this.isSyncFontLoadingSupported)return;await new Promise((e=>{const i=this._queueLoadingCallback(e);this._prepareFontLoadEvent(t,i)}))}}get isFontLoadingAPISupported(){return E(this,"isFontLoadingAPISupported",!!this._document?.fonts)}get isSyncFontLoadingSupported(){let t=!1;return(n||"undefined"!=typeof navigator&&"string"==typeof navigator?.userAgent&&/Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent))&&(t=!0),E(this,"isSyncFontLoadingSupported",t)}_queueLoadingCallback(t){const{loadingRequests:e}=this,i={done:!1,complete:function(){for(x(!i.done,"completeRequest() cannot be called twice."),i.done=!0;e.length>0&&e[0].done;){const t=e.shift();setTimeout(t.callback,0)}},callback:t};return e.push(i),i}get _loadTestFont(){return E(this,"_loadTestFont",atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA=="))}_prepareFontLoadEvent(t,e){function i(t,e){return t.charCodeAt(e)<<24|t.charCodeAt(e+1)<<16|t.charCodeAt(e+2)<<8|255&t.charCodeAt(e+3)}function s(t,e,i,s){return t.substring(0,e)+s+t.substring(e+i)}let n,a;const r=this._document.createElement("canvas");r.width=1,r.height=1;const o=r.getContext("2d");let l=0;const h=`lt${Date.now()}${this.loadTestFontId++}`;let d=this._loadTestFont;d=s(d,976,h.length,h);const c=1482184792;let u=i(d,16);for(n=0,a=h.length-3;n>24&255,p>>16&255,p>>8&255,255&p)));const g=`@font-face {font-family:"${h}";src:url(data:font/opentype;base64,${btoa(d)});}`;this.insertRule(g);const m=this._document.createElement("div");m.style.visibility="hidden",m.style.width=m.style.height="10px",m.style.position="absolute",m.style.top=m.style.left="0px";for(const e of[t.loadedName,h]){const t=this._document.createElement("span");t.textContent="Hi",t.style.fontFamily=e,m.append(t)}this._document.body.append(m),function t(e,i){if(++l>30)return w("Load test font never loaded."),void i();o.font="30px "+e,o.fillText(".",0,20),o.getImageData(0,0,1,1).data[3]>0?i():setTimeout(t.bind(null,e,i))}(h,(()=>{m.remove(),e.complete()}))}}class zt{constructor(t,{disableFontFace:e=!1,inspectFont:i=null}){this.compiledGlyphs=Object.create(null);for(const e in t)this[e]=t[e];this.disableFontFace=!0===e,this._inspectFont=i}createNativeFontFace(){if(!this.data||this.disableFontFace)return null;let t;if(this.cssFontInfo){const e={weight:this.cssFontInfo.fontWeight};this.cssFontInfo.italicAngle&&(e.style=`oblique ${this.cssFontInfo.italicAngle}deg`),t=new FontFace(this.cssFontInfo.fontFamily,this.data,e)}else t=new FontFace(this.loadedName,this.data,{});return this._inspectFont?.(this),t}createFontFaceRule(){if(!this.data||this.disableFontFace)return null;const t=L(this.data),e=`url(data:${this.mimetype};base64,${btoa(t)});`;let i;if(this.cssFontInfo){let t=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(t+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`),i=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${t}src:${e}}`}else i=`@font-face {font-family:"${this.loadedName}";src:${e}}`;return this._inspectFont?.(this,e),i}getPathGenerator(t,e){if(void 0!==this.compiledGlyphs[e])return this.compiledGlyphs[e];let i;try{i=t.get(this.loadedName+"_path_"+e)}catch(t){w(`getPathGenerator - ignoring character: "${t}".`)}if(!Array.isArray(i)||0===i.length)return this.compiledGlyphs[e]=function(t,e){};const s=[];for(let t=0,e=i.length;tt.bezierCurveTo(e,n,a,r,o,l))),t+=6}break;case 1:{const[e,n]=i.slice(t,t+2);s.push((t=>t.moveTo(e,n))),t+=2}break;case 2:{const[e,n]=i.slice(t,t+2);s.push((t=>t.lineTo(e,n))),t+=2}break;case 3:{const[e,n,a,r]=i.slice(t,t+4);s.push((t=>t.quadraticCurveTo(e,n,a,r))),t+=4}break;case 4:s.push((t=>t.restore()));break;case 5:s.push((t=>t.save()));break;case 6:x(2===s.length,"Scale command is only valid at the third position.");break;case 7:{const[e,n,a,r,o,l]=i.slice(t,t+6);s.push((t=>t.transform(e,n,a,r,o,l))),t+=6}break;case 8:{const[e,n]=i.slice(t,t+2);s.push((t=>t.translate(e,n))),t+=2}}return this.compiledGlyphs[e]=function(t,e){s[0](t),s[1](t),t.scale(e,-e);for(let e=2,i=s.length;e{const t=await import("fs"),e=await import("http"),i=await import("https"),s=await import("url");return new Map(Object.entries({fs:t,http:e,https:i,url:s,canvas:void 0,path2d:void 0}))})().then((t=>{jt=t,Ht.resolve()}),(t=>{w(`loadPackages: ${t}`),jt=new Map,Ht.resolve()}))}class Ut{static get promise(){return Ht.promise}static get(t){return jt?.get(t)}}const $t=function(t){return Ut.get("fs").promises.readFile(t).then((t=>new Uint8Array(t)))},Wt="Fill",Gt="Stroke",Vt="Shading";function qt(t,e){if(!e)return;const i=e[2]-e[0],s=e[3]-e[1],n=new Path2D;n.rect(e[0],e[1],i,s),t.clip(n)}class Xt{getPattern(){_("Abstract method `getPattern` called.")}}class Kt extends Xt{constructor(t){super(),this._type=t[1],this._bbox=t[2],this._colorStops=t[3],this._p0=t[4],this._p1=t[5],this._r0=t[6],this._r1=t[7],this.matrix=null}_createGradient(t){let e;"axial"===this._type?e=t.createLinearGradient(this._p0[0],this._p0[1],this._p1[0],this._p1[1]):"radial"===this._type&&(e=t.createRadialGradient(this._p0[0],this._p0[1],this._r0,this._p1[0],this._p1[1],this._r1));for(const t of this._colorStops)e.addColorStop(t[0],t[1]);return e}getPattern(t,e,i,s){let n;if(s===Gt||s===Wt){const a=e.current.getClippedPathBoundingBox(s,mt(t))||[0,0,0,0],r=Math.ceil(a[2]-a[0])||1,o=Math.ceil(a[3]-a[1])||1,l=e.cachedCanvases.getCanvas("pattern",r,o),h=l.context;h.clearRect(0,0,h.canvas.width,h.canvas.height),h.beginPath(),h.rect(0,0,h.canvas.width,h.canvas.height),h.translate(-a[0],-a[1]),i=z.transform(i,[1,0,0,1,a[0],a[1]]),h.transform(...e.baseTransform),this.matrix&&h.transform(...this.matrix),qt(h,this._bbox),h.fillStyle=this._createGradient(h),h.fill(),n=t.createPattern(l.canvas,"no-repeat");const d=new DOMMatrix(i);n.setTransform(d)}else qt(t,this._bbox),n=this._createGradient(t);return n}}function Yt(t,e,i,s,n,a,r,o){const l=e.coords,h=e.colors,d=t.data,c=4*t.width;let u;l[i+1]>l[s+1]&&(u=i,i=s,s=u,u=a,a=r,r=u),l[s+1]>l[n+1]&&(u=s,s=n,n=u,u=r,r=o,o=u),l[i+1]>l[s+1]&&(u=i,i=s,s=u,u=a,a=r,r=u);const p=(l[i]+e.offsetX)*e.scaleX,g=(l[i+1]+e.offsetY)*e.scaleY,m=(l[s]+e.offsetX)*e.scaleX,f=(l[s+1]+e.offsetY)*e.scaleY,b=(l[n]+e.offsetX)*e.scaleX,v=(l[n+1]+e.offsetY)*e.scaleY;if(g>=v)return;const A=h[a],y=h[a+1],w=h[a+2],_=h[r],x=h[r+1],C=h[r+2],E=h[o],S=h[o+1],T=h[o+2],M=Math.round(g),k=Math.round(v);let I,P,R,D,L,F,N,O;for(let t=M;t<=k;t++){if(tv?1:f===v?0:(f-t)/(f-v),I=m-(m-b)*e,P=_-(_-E)*e,R=x-(x-S)*e,D=C-(C-T)*e}let e;e=tv?1:(g-t)/(g-v),L=p-(p-b)*e,F=A-(A-E)*e,N=y-(y-S)*e,O=w-(w-T)*e;const i=Math.round(Math.min(I,L)),s=Math.round(Math.max(I,L));let n=c*t+4*i;for(let t=i;t<=s;t++)e=(I-t)/(I-L),e<0?e=0:e>1&&(e=1),d[n++]=P-(P-F)*e|0,d[n++]=R-(R-N)*e|0,d[n++]=D-(D-O)*e|0,d[n++]=255}}function Qt(t,e,i){const s=e.coords,n=e.colors;let a,r;switch(e.type){case"lattice":const o=e.verticesPerRow,l=Math.floor(s.length/o)-1,h=o-1;for(a=0;a=Math.ceil(p*b)?A=o:_=!0,E>=Math.ceil(g*v)?w=l:x=!0;const S=this.getSizeAndScale(A,this.ctx.canvas.width,b),T=this.getSizeAndScale(w,this.ctx.canvas.height,v),M=t.cachedCanvases.getCanvas("pattern",S.size,T.size),k=M.context,I=r.createCanvasGraphics(k);if(I.groupLevel=t.groupLevel,this.setFillAndStrokeStyleToContext(I,s,a),k.translate(-S.scale*h,-T.scale*d),I.transform(S.scale,0,0,T.scale,0,0),k.save(),this.clipBbox(I,h,d,c,u),I.baseTransform=mt(I.ctx),I.executeOperatorList(i),I.endDrawing(),k.restore(),_||x){const e=M.canvas;_&&(A=o),x&&(w=l);const i=this.getSizeAndScale(A,this.ctx.canvas.width,b),s=this.getSizeAndScale(w,this.ctx.canvas.height,v),n=i.size,a=s.size,r=t.cachedCanvases.getCanvas("pattern-workaround",n,a),c=r.context,u=_?Math.floor(p/o):0,m=x?Math.floor(g/l):0;for(let t=0;t<=u;t++)for(let i=0;i<=m;i++)c.drawImage(e,n*t,a*i,n,a,0,0,n,a);return{canvas:r.canvas,scaleX:i.scale,scaleY:s.scale,offsetX:h,offsetY:d}}return{canvas:M.canvas,scaleX:S.scale,scaleY:T.scale,offsetX:h,offsetY:d}}getSizeAndScale(t,e,i){const s=Math.max(te.MAX_PATTERN_SIZE,e);let n=Math.ceil(t*i);return n>=s?n=s:i=n/t,{scale:i,size:n}}clipBbox(t,e,i,s,n){const a=s-e,r=n-i;t.ctx.rect(e,i,a,r),t.current.updateRectMinMax(mt(t.ctx),[e,i,s,n]),t.clip(),t.endPath()}setFillAndStrokeStyleToContext(t,e,i){const s=t.ctx,n=t.current;switch(e){case 1:const t=this.ctx;s.fillStyle=t.fillStyle,s.strokeStyle=t.strokeStyle,n.fillColor=t.fillStyle,n.strokeColor=t.strokeStyle;break;case 2:const a=z.makeHexColor(i[0],i[1],i[2]);s.fillStyle=a,s.strokeStyle=a,n.fillColor=a,n.strokeColor=a;break;default:throw new R(`Unsupported paint type: ${e}`)}}getPattern(t,e,i,s){let n=i;s!==Vt&&(n=z.transform(n,e.baseTransform),this.matrix&&(n=z.transform(n,this.matrix)));const a=this.createPatternCanvas(e);let r=new DOMMatrix(n);r=r.translate(a.offsetX,a.offsetY),r=r.scale(1/a.scaleX,1/a.scaleY);const o=t.createPattern(a.canvas,"repeat");return o.setTransform(r),o}}function ee({src:t,srcPos:e=0,dest:i,width:s,height:n,nonBlackColor:a=4294967295,inverseDecode:r=!1}){const o=O.isLittleEndian?4278190080:255,[l,h]=r?[a,o]:[o,a],d=s>>3,c=7&s,u=t.length;i=new Uint32Array(i.buffer);let p=0;for(let s=0;s>2),u=i.length,f=s+7>>3,b=4294967295,v=O.isLittleEndian?4278190080:255;for(p=0;pf?s:8*t-7,r=-8&a;let o=0,c=0;for(;n>=1}for(;l=a&&(m=n,f=s*m),l=0,g=f;g--;)c[l++]=d[h++],c[l++]=d[h++],c[l++]=d[h++],c[l++]=255;t.putImageData(o,0,p*ie)}}}function oe(t,e){if(e.bitmap)return void t.drawImage(e.bitmap,0,0);const i=e.height,s=e.width,n=i%ie,a=(i-n)/ie,r=0===n?a:a+1,o=t.createImageData(s,ie);let l=0;const h=e.data,d=o.data;for(let e=0;e10&&"function"==typeof i,h=l?Date.now()+15:0;let d=0;const c=this.commonObjs,u=this.objs;let p;for(;;){if(void 0!==s&&r===s.nextBreakPoint)return s.breakIt(r,i),r;if(p=a[r],p!==m.dependency)this[p].apply(this,n[r]);else for(const t of n[r]){const e=t.startsWith("g_")?c:u;if(!e.has(t))return e.get(t,i),r}if(r++,r===o)return r;if(l&&++d>10){if(Date.now()>h)return i(),r;d=0}}}#Le(){for(;this.stateStack.length||this.inSMaskMode;)this.restore();this.current.activeSMask=null,this.ctx.restore(),this.transparentCanvas&&(this.ctx=this.compositeCtx,this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.drawImage(this.transparentCanvas,0,0),this.ctx.restore(),this.transparentCanvas=null)}endDrawing(){this.#Le(),this.cachedCanvases.clear(),this.cachedPatterns.clear();for(const t of this._cachedBitmapsMap.values()){for(const e of t.values())"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement&&(e.width=e.height=0);t.clear()}this._cachedBitmapsMap.clear(),this.#Fe()}#Fe(){if(this.pageColors){const t=this.filterFactory.addHCMFilter(this.pageColors.foreground,this.pageColors.background);if("none"!==t){const e=this.ctx.filter;this.ctx.filter=t,this.ctx.drawImage(this.ctx.canvas,0,0),this.ctx.filter=e}}}_scaleImage(t,e){const i=t.width,s=t.height;let n,a,r=Math.max(Math.hypot(e[0],e[1]),1),o=Math.max(Math.hypot(e[2],e[3]),1),l=i,h=s,d="prescale1";for(;r>2&&l>1||o>2&&h>1;){let e=l,i=h;r>2&&l>1&&(e=l>=16384?Math.floor(l/2)-1||1:Math.ceil(l/2),r/=l/e),o>2&&h>1&&(i=h>=16384?Math.floor(h/2)-1||1:Math.ceil(h)/2,o/=h/i),n=this.cachedCanvases.getCanvas(d,e,i),a=n.context,a.clearRect(0,0,e,i),a.drawImage(t,0,0,l,h,0,0,e,i),t=n.canvas,l=e,h=i,d="prescale1"===d?"prescale2":"prescale1"}return{img:t,paintWidth:l,paintHeight:h}}_createMaskCanvas(t){const e=this.ctx,{width:i,height:s}=t,n=this.current.fillColor,a=this.current.patternFill,r=mt(e);let o,l,h,d;if((t.bitmap||t.data)&&t.count>1){const e=t.bitmap||t.data.buffer;l=JSON.stringify(a?r:[r.slice(0,4),n]),o=this._cachedBitmapsMap.get(e),o||(o=new Map,this._cachedBitmapsMap.set(e,o));const i=o.get(l);if(i&&!a)return{canvas:i,offsetX:Math.round(Math.min(r[0],r[2])+r[4]),offsetY:Math.round(Math.min(r[1],r[3])+r[5])};h=i}h||(d=this.cachedCanvases.getCanvas("maskCanvas",i,s),oe(d.context,t));let c=z.transform(r,[1/i,0,0,-1/s,0,0]);c=z.transform(c,[1,0,0,1,0,-s]);const[u,p,g,m]=z.getAxialAlignedBoundingBox([0,0,i,s],c),f=Math.round(g-u)||1,b=Math.round(m-p)||1,v=this.cachedCanvases.getCanvas("fillCanvas",f,b),A=v.context,y=u,w=p;A.translate(-y,-w),A.transform(...c),h||(h=this._scaleImage(d.canvas,ft(A)),h=h.img,o&&a&&o.set(l,h)),A.imageSmoothingEnabled=de(mt(A),t.interpolate),ne(A,h,0,0,h.width,h.height,0,0,i,s),A.globalCompositeOperation="source-in";const _=z.transform(ft(A),[1,0,0,1,-y,-w]);return A.fillStyle=a?n.getPattern(e,this,_,Wt):n,A.fillRect(0,0,i,s),o&&!a&&(this.cachedCanvases.delete("fillCanvas"),o.set(l,v.canvas)),{canvas:v.canvas,offsetX:Math.round(y),offsetY:Math.round(w)}}setLineWidth(t){t!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=t,this.ctx.lineWidth=t}setLineCap(t){this.ctx.lineCap=ce[t]}setLineJoin(t){this.ctx.lineJoin=ue[t]}setMiterLimit(t){this.ctx.miterLimit=t}setDash(t,e){const i=this.ctx;void 0!==i.setLineDash&&(i.setLineDash(t),i.lineDashOffset=e)}setRenderingIntent(t){}setFlatness(t){}setGState(t){for(const[e,i]of t)switch(e){case"LW":this.setLineWidth(i);break;case"LC":this.setLineCap(i);break;case"LJ":this.setLineJoin(i);break;case"ML":this.setMiterLimit(i);break;case"D":this.setDash(i[0],i[1]);break;case"RI":this.setRenderingIntent(i);break;case"FL":this.setFlatness(i);break;case"Font":this.setFont(i[0],i[1]);break;case"CA":this.current.strokeAlpha=i;break;case"ca":this.current.fillAlpha=i,this.ctx.globalAlpha=i;break;case"BM":this.ctx.globalCompositeOperation=i;break;case"SMask":this.current.activeSMask=i?this.tempSMask:null,this.tempSMask=null,this.checkSMaskState();break;case"TR":this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(i)}}get inSMaskMode(){return!!this.suspendedCtx}checkSMaskState(){const t=this.inSMaskMode;this.current.activeSMask&&!t?this.beginSMaskMode():!this.current.activeSMask&&t&&this.endSMaskMode()}beginSMaskMode(){if(this.inSMaskMode)throw new Error("beginSMaskMode called while already in smask mode");const t=this.ctx.canvas.width,e=this.ctx.canvas.height,i="smaskGroupAt"+this.groupLevel,s=this.cachedCanvases.getCanvas(i,t,e);this.suspendedCtx=this.ctx,this.ctx=s.context;const n=this.ctx;n.setTransform(...mt(this.suspendedCtx)),le(this.suspendedCtx,n),function(t,e){if(t._removeMirroring)throw new Error("Context is already forwarding operations.");t.__originalSave=t.save,t.__originalRestore=t.restore,t.__originalRotate=t.rotate,t.__originalScale=t.scale,t.__originalTranslate=t.translate,t.__originalTransform=t.transform,t.__originalSetTransform=t.setTransform,t.__originalResetTransform=t.resetTransform,t.__originalClip=t.clip,t.__originalMoveTo=t.moveTo,t.__originalLineTo=t.lineTo,t.__originalBezierCurveTo=t.bezierCurveTo,t.__originalRect=t.rect,t.__originalClosePath=t.closePath,t.__originalBeginPath=t.beginPath,t._removeMirroring=()=>{t.save=t.__originalSave,t.restore=t.__originalRestore,t.rotate=t.__originalRotate,t.scale=t.__originalScale,t.translate=t.__originalTranslate,t.transform=t.__originalTransform,t.setTransform=t.__originalSetTransform,t.resetTransform=t.__originalResetTransform,t.clip=t.__originalClip,t.moveTo=t.__originalMoveTo,t.lineTo=t.__originalLineTo,t.bezierCurveTo=t.__originalBezierCurveTo,t.rect=t.__originalRect,t.closePath=t.__originalClosePath,t.beginPath=t.__originalBeginPath,delete t._removeMirroring},t.save=function(){e.save(),this.__originalSave()},t.restore=function(){e.restore(),this.__originalRestore()},t.translate=function(t,i){e.translate(t,i),this.__originalTranslate(t,i)},t.scale=function(t,i){e.scale(t,i),this.__originalScale(t,i)},t.transform=function(t,i,s,n,a,r){e.transform(t,i,s,n,a,r),this.__originalTransform(t,i,s,n,a,r)},t.setTransform=function(t,i,s,n,a,r){e.setTransform(t,i,s,n,a,r),this.__originalSetTransform(t,i,s,n,a,r)},t.resetTransform=function(){e.resetTransform(),this.__originalResetTransform()},t.rotate=function(t){e.rotate(t),this.__originalRotate(t)},t.clip=function(t){e.clip(t),this.__originalClip(t)},t.moveTo=function(t,i){e.moveTo(t,i),this.__originalMoveTo(t,i)},t.lineTo=function(t,i){e.lineTo(t,i),this.__originalLineTo(t,i)},t.bezierCurveTo=function(t,i,s,n,a,r){e.bezierCurveTo(t,i,s,n,a,r),this.__originalBezierCurveTo(t,i,s,n,a,r)},t.rect=function(t,i,s,n){e.rect(t,i,s,n),this.__originalRect(t,i,s,n)},t.closePath=function(){e.closePath(),this.__originalClosePath()},t.beginPath=function(){e.beginPath(),this.__originalBeginPath()}}(n,this.suspendedCtx),this.setGState([["BM","source-over"],["ca",1],["CA",1]])}endSMaskMode(){if(!this.inSMaskMode)throw new Error("endSMaskMode called while not in smask mode");this.ctx._removeMirroring(),le(this.ctx,this.suspendedCtx),this.ctx=this.suspendedCtx,this.suspendedCtx=null}compose(t){if(!this.current.activeSMask)return;t?(t[0]=Math.floor(t[0]),t[1]=Math.floor(t[1]),t[2]=Math.ceil(t[2]),t[3]=Math.ceil(t[3])):t=[0,0,this.ctx.canvas.width,this.ctx.canvas.height];const e=this.current.activeSMask,i=this.suspendedCtx;this.composeSMask(i,e,this.ctx,t),this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height),this.ctx.restore()}composeSMask(t,e,i,s){const n=s[0],a=s[1],r=s[2]-n,o=s[3]-a;0!==r&&0!==o&&(this.genericComposeSMask(e.context,i,r,o,e.subtype,e.backdrop,e.transferMap,n,a,e.offsetX,e.offsetY),t.save(),t.globalAlpha=1,t.globalCompositeOperation="source-over",t.setTransform(1,0,0,1,0,0),t.drawImage(i.canvas,0,0),t.restore())}genericComposeSMask(t,e,i,s,n,a,r,o,l,h,d){let c=t.canvas,u=o-h,p=l-d;if(a)if(u<0||p<0||u+i>c.width||p+s>c.height){const t=this.cachedCanvases.getCanvas("maskExtension",i,s),e=t.context;e.drawImage(c,-u,-p),a.some((t=>0!==t))&&(e.globalCompositeOperation="destination-atop",e.fillStyle=z.makeHexColor(...a),e.fillRect(0,0,i,s),e.globalCompositeOperation="source-over"),c=t.canvas,u=p=0}else if(a.some((t=>0!==t))){t.save(),t.globalAlpha=1,t.setTransform(1,0,0,1,0,0);const e=new Path2D;e.rect(u,p,i,s),t.clip(e),t.globalCompositeOperation="destination-atop",t.fillStyle=z.makeHexColor(...a),t.fillRect(u,p,i,s),t.restore()}e.save(),e.globalAlpha=1,e.setTransform(1,0,0,1,0,0),"Alpha"===n&&r?e.filter=this.filterFactory.addAlphaFilter(r):"Luminosity"===n&&(e.filter=this.filterFactory.addLuminosityFilter(r));const g=new Path2D;g.rect(o,l,i,s),e.clip(g),e.globalCompositeOperation="destination-in",e.drawImage(c,u,p,i,s,o,l,i,s),e.restore()}save(){this.inSMaskMode?(le(this.ctx,this.suspendedCtx),this.suspendedCtx.save()):this.ctx.save();const t=this.current;this.stateStack.push(t),this.current=t.clone()}restore(){0===this.stateStack.length&&this.inSMaskMode&&this.endSMaskMode(),0!==this.stateStack.length&&(this.current=this.stateStack.pop(),this.inSMaskMode?(this.suspendedCtx.restore(),le(this.suspendedCtx,this.ctx)):this.ctx.restore(),this.checkSMaskState(),this.pendingClip=null,this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null)}transform(t,e,i,s,n,a){this.ctx.transform(t,e,i,s,n,a),this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null}constructPath(t,e,i){const s=this.ctx,n=this.current;let a,r,o=n.x,l=n.y;const h=mt(s),d=0===h[0]&&0===h[3]||0===h[1]&&0===h[2],c=d?i.slice(0):null;for(let i=0,u=0,p=t.length;i100&&(h=100),this.current.fontSizeScale=e/h,this.ctx.font=`${l} ${o} ${h}px ${a}`}setTextRenderingMode(t){this.current.textRenderingMode=t}setTextRise(t){this.current.textRise=t}moveText(t,e){this.current.x=this.current.lineX+=t,this.current.y=this.current.lineY+=e}setLeadingMoveText(t,e){this.setLeading(-e),this.moveText(t,e)}setTextMatrix(t,e,i,s,n,a){this.current.textMatrix=[t,e,i,s,n,a],this.current.textMatrixScale=Math.hypot(t,e),this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0}nextLine(){this.moveText(0,this.current.leading)}paintChar(t,e,i,s){const n=this.ctx,a=this.current,r=a.font,o=a.textRenderingMode,l=a.fontSize/a.fontSizeScale,h=3&o,d=!!(4&o),c=a.patternFill&&!r.missingFile;let u;(r.disableFontFace||d||c)&&(u=r.getPathGenerator(this.commonObjs,t)),r.disableFontFace||c?(n.save(),n.translate(e,i),n.beginPath(),u(n,l),s&&n.setTransform(...s),0!==h&&2!==h||n.fill(),1!==h&&2!==h||n.stroke(),n.restore()):(0!==h&&2!==h||n.fillText(t,e,i),1!==h&&2!==h||n.strokeText(t,e,i)),d&&(this.pendingTextPaths||=[]).push({transform:mt(n),x:e,y:i,fontSize:l,addToPath:u})}get isFontSubpixelAAEnabled(){const{context:t}=this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled",10,10);t.scale(1.5,1),t.fillText("I",0,10);const e=t.getImageData(0,0,10,10).data;let i=!1;for(let t=3;t0&&e[t]<255){i=!0;break}return E(this,"isFontSubpixelAAEnabled",i)}showText(t){const e=this.current,i=e.font;if(i.isType3Font)return this.showType3Text(t);const s=e.fontSize;if(0===s)return;const n=this.ctx,a=e.fontSizeScale,r=e.charSpacing,o=e.wordSpacing,l=e.fontDirection,h=e.textHScale*l,d=t.length,c=i.vertical,u=c?1:-1,p=i.defaultVMetrics,g=s*e.fontMatrix[0],m=0===e.textRenderingMode&&!i.disableFontFace&&!e.patternFill;let f;if(n.save(),n.transform(...e.textMatrix),n.translate(e.x,e.y+e.textRise),l>0?n.scale(h,-1):n.scale(h,1),e.patternFill){n.save();const t=e.fillColor.getPattern(n,this,ft(n),Wt);f=mt(n),n.restore(),n.fillStyle=t}let b=e.lineWidth;const v=e.textMatrixScale;if(0===v||0===b){const t=3&e.textRenderingMode;1!==t&&2!==t||(b=this.getSinglePixelWidth())}else b/=v;if(1!==a&&(n.scale(a,a),b/=a),n.lineWidth=b,i.isInvalidPDFjsFont){const i=[];let s=0;for(const e of t)i.push(e.unicode),s+=e.width;return n.fillText(i.join(""),0,0),e.x+=s*g*h,n.restore(),void this.compose()}let A,y=0;for(A=0;A0){const t=1e3*n.measureText(b).width/s*a;if(xnew me(t,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack})};e=new te(t,i,this.ctx,n,s)}else e=this._getPattern(t[1],t[2]);return e}setStrokeColorN(){this.current.strokeColor=this.getColorN_Pattern(arguments)}setFillColorN(){this.current.fillColor=this.getColorN_Pattern(arguments),this.current.patternFill=!0}setStrokeRGBColor(t,e,i){this.ctx.strokeStyle=this.current.strokeColor=z.makeHexColor(t,e,i)}setStrokeTransparent(){this.ctx.strokeStyle=this.current.strokeColor="transparent"}setFillRGBColor(t,e,i){this.ctx.fillStyle=this.current.fillColor=z.makeHexColor(t,e,i),this.current.patternFill=!1}setFillTransparent(){this.ctx.fillStyle=this.current.fillColor="transparent",this.current.patternFill=!1}_getPattern(t,e=null){let i;return this.cachedPatterns.has(t)?i=this.cachedPatterns.get(t):(i=function(t){switch(t[0]){case"RadialAxial":return new Kt(t);case"Mesh":return new Jt(t);case"Dummy":return new Zt}throw new Error(`Unknown IR type: ${t[0]}`)}(this.getObject(t)),this.cachedPatterns.set(t,i)),e&&(i.matrix=e),i}shadingFill(t){if(!this.contentVisible)return;const e=this.ctx;this.save();const i=this._getPattern(t);e.fillStyle=i.getPattern(e,this,ft(e),Vt);const s=ft(e);if(s){const{width:t,height:i}=e.canvas,[n,a,r,o]=z.getAxialAlignedBoundingBox([0,0,t,i],s);this.ctx.fillRect(n,a,r-n,o-a)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.compose(this.current.getClippedPathBoundingBox()),this.restore()}beginInlineImage(){_("Should not call beginInlineImage")}beginImageData(){_("Should not call beginImageData")}paintFormXObjectBegin(t,e){if(this.contentVisible&&(this.save(),this.baseTransformStack.push(this.baseTransform),t&&this.transform(...t),this.baseTransform=mt(this.ctx),e)){const t=e[2]-e[0],i=e[3]-e[1];this.ctx.rect(e[0],e[1],t,i),this.current.updateRectMinMax(mt(this.ctx),e),this.clip(),this.endPath()}}paintFormXObjectEnd(){this.contentVisible&&(this.restore(),this.baseTransform=this.baseTransformStack.pop())}beginGroup(t){if(!this.contentVisible)return;this.save(),this.inSMaskMode&&(this.endSMaskMode(),this.current.activeSMask=null);const e=this.ctx;t.isolated||y("TODO: Support non-isolated groups."),t.knockout&&w("Knockout groups not supported.");const i=mt(e);if(t.matrix&&e.transform(...t.matrix),!t.bbox)throw new Error("Bounding box is required.");let s=z.getAxialAlignedBoundingBox(t.bbox,mt(e));const n=[0,0,e.canvas.width,e.canvas.height];s=z.intersect(s,n)||[0,0,0,0];const a=Math.floor(s[0]),r=Math.floor(s[1]),o=Math.max(Math.ceil(s[2])-a,1),l=Math.max(Math.ceil(s[3])-r,1);this.current.startNewPathAndClipBox([0,0,o,l]);let h="groupAt"+this.groupLevel;t.smask&&(h+="_smask_"+this.smaskCounter++%2);const d=this.cachedCanvases.getCanvas(h,o,l),c=d.context;c.translate(-a,-r),c.transform(...i),t.smask?this.smaskStack.push({canvas:d.canvas,context:c,offsetX:a,offsetY:r,subtype:t.smask.subtype,backdrop:t.smask.backdrop,transferMap:t.smask.transferMap||null,startTransformInverse:null}):(e.setTransform(1,0,0,1,0,0),e.translate(a,r),e.save()),le(e,c),this.ctx=c,this.setGState([["BM","source-over"],["ca",1],["CA",1]]),this.groupStack.push(e),this.groupLevel++}endGroup(t){if(!this.contentVisible)return;this.groupLevel--;const e=this.ctx,i=this.groupStack.pop();if(this.ctx=i,this.ctx.imageSmoothingEnabled=!1,t.smask)this.tempSMask=this.smaskStack.pop(),this.restore();else{this.ctx.restore();const t=mt(this.ctx);this.restore(),this.ctx.save(),this.ctx.setTransform(...t);const i=z.getAxialAlignedBoundingBox([0,0,e.canvas.width,e.canvas.height],t);this.ctx.drawImage(e.canvas,0,0),this.ctx.restore(),this.compose(i)}}beginAnnotation(t,e,i,s,n){if(this.#Le(),he(this.ctx),this.ctx.save(),this.save(),this.baseTransform&&this.ctx.setTransform(...this.baseTransform),e){const s=e[2]-e[0],a=e[3]-e[1];if(n&&this.annotationCanvasMap){(i=i.slice())[4]-=e[0],i[5]-=e[1],(e=e.slice())[0]=e[1]=0,e[2]=s,e[3]=a;const[n,r]=z.singularValueDecompose2dScale(mt(this.ctx)),{viewportScale:o}=this,l=Math.ceil(s*this.outputScaleX*o),h=Math.ceil(a*this.outputScaleY*o);this.annotationCanvas=this.canvasFactory.create(l,h);const{canvas:d,context:c}=this.annotationCanvas;this.annotationCanvasMap.set(t,d),this.annotationCanvas.savedCtx=this.ctx,this.ctx=c,this.ctx.save(),this.ctx.setTransform(n,0,0,-r,0,a*r),he(this.ctx)}else he(this.ctx),this.endPath(),this.ctx.rect(e[0],e[1],s,a),this.ctx.clip(),this.ctx.beginPath()}this.current=new ae(this.ctx.canvas.width,this.ctx.canvas.height),this.transform(...i),this.transform(...s)}endAnnotation(){this.annotationCanvas&&(this.ctx.restore(),this.#Fe(),this.ctx=this.annotationCanvas.savedCtx,delete this.annotationCanvas.savedCtx,delete this.annotationCanvas)}paintImageMaskXObject(t){if(!this.contentVisible)return;const e=t.count;(t=this.getObject(t.data,t)).count=e;const i=this.ctx,s=this.processingType3;if(s&&(void 0===s.compiled&&(s.compiled=function(t){const{width:e,height:i}=t;if(e>1e3||i>1e3)return null;const s=new Uint8Array([0,2,4,0,1,0,5,4,8,10,0,8,0,2,1,0]),n=e+1;let a,r,o,l=new Uint8Array(n*(i+1));const h=e+7&-8;let d=new Uint8Array(h*i),c=0;for(const e of t.data){let t=128;for(;t>0;)d[c++]=e&t?0:255,t>>=1}let u=0;for(c=0,0!==d[c]&&(l[0]=1,++u),r=1;r>2)+(d[c+1]?4:0)+(d[c-h+1]?8:0),s[t]&&(l[o+r]=s[t],++u),c++;if(d[c-h]!==d[c]&&(l[o+r]=d[c]?2:4,++u),u>1e3)return null}for(c=h*(i-1),o=a*n,0!==d[c]&&(l[o]=8,++u),r=1;r1e3)return null;const p=new Int32Array([0,n,-1,0,-n,0,0,0,1]),g=new Path2D;for(a=0;u&&a<=i;a++){let t=a*n;const i=t+e;for(;t>4,l[t]&=r>>2|r<<2),g.lineTo(t%n,t/n|0),l[t]||--u}while(s!==t);--a}return d=null,l=null,function(t){t.save(),t.scale(1/e,-1/i),t.translate(0,-i),t.fill(g),t.beginPath(),t.restore()}}(t)),s.compiled))return void s.compiled(i);const n=this._createMaskCanvas(t),a=n.canvas;i.save(),i.setTransform(1,0,0,1,0,0),i.drawImage(a,n.offsetX,n.offsetY),i.restore(),this.compose()}paintImageMaskXObjectRepeat(t,e,i=0,s=0,n,a){if(!this.contentVisible)return;t=this.getObject(t.data,t);const r=this.ctx;r.save();const o=mt(r);r.transform(e,i,s,n,0,0);const l=this._createMaskCanvas(t);r.setTransform(1,0,0,1,l.offsetX-o[4],l.offsetY-o[5]);for(let t=0,h=a.length;te?h/e:1,r=l>e?l/e:1}}this._cachedScaleForStroking[0]=a,this._cachedScaleForStroking[1]=r}return this._cachedScaleForStroking}rescaleAndStroke(t){const{ctx:e}=this,{lineWidth:i}=this.current,[s,n]=this.getScaleForStroking();if(e.lineWidth=i||1,1===s&&1===n)return void e.stroke();const a=e.getLineDash();if(t&&e.save(),e.scale(s,n),a.length>0){const t=Math.max(s,n);e.setLineDash(a.map((e=>e/t))),e.lineDashOffset/=t}e.stroke(),t&&e.restore()}isContentVisible(){for(let t=this.markedContentStack.length-1;t>=0;t--)if(!this.markedContentStack[t].visible)return!1;return!0}}for(const t in m)void 0!==me.prototype[t]&&(me.prototype[m[t]]=me.prototype[t]);class fe{static#Ne=null;static#Oe="";static get workerPort(){return this.#Ne}static set workerPort(t){if(!("undefined"!=typeof Worker&&t instanceof Worker)&&null!==t)throw new Error("Invalid `workerPort` type.");this.#Ne=t}static get workerSrc(){return this.#Oe}static set workerSrc(t){if("string"!=typeof t)throw new Error("Invalid `workerSrc` type.");this.#Oe=t}}function be(t){switch(t instanceof Error||"object"==typeof t&&null!==t||_('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),t.name){case"AbortException":return new D(t.message);case"MissingPDFException":return new I(t.message);case"PasswordException":return new T(t.message,t.code);case"UnexpectedResponseException":return new P(t.message,t.status);case"UnknownErrorException":return new M(t.message,t.details);default:return new M(t.message,t.toString())}}class ve{constructor(t,e,i){this.sourceName=t,this.targetName=e,this.comObj=i,this.callbackId=1,this.streamId=1,this.streamSinks=Object.create(null),this.streamControllers=Object.create(null),this.callbackCapabilities=Object.create(null),this.actionHandler=Object.create(null),this._onComObjOnMessage=t=>{const e=t.data;if(e.targetName!==this.sourceName)return;if(e.stream)return void this.#Be(e);if(e.callback){const t=e.callbackId,i=this.callbackCapabilities[t];if(!i)throw new Error(`Cannot resolve callback ${t}`);if(delete this.callbackCapabilities[t],1===e.callback)i.resolve(e.data);else{if(2!==e.callback)throw new Error("Unexpected callback case");i.reject(be(e.reason))}return}const s=this.actionHandler[e.action];if(!s)throw new Error(`Unknown action from worker: ${e.action}`);if(e.callbackId){const t=this.sourceName,n=e.sourceName;new Promise((function(t){t(s(e.data))})).then((function(s){i.postMessage({sourceName:t,targetName:n,callback:1,callbackId:e.callbackId,data:s})}),(function(s){i.postMessage({sourceName:t,targetName:n,callback:2,callbackId:e.callbackId,reason:be(s)})}))}else e.streamId?this.#ze(e):s(e.data)},i.addEventListener("message",this._onComObjOnMessage)}on(t,e){const i=this.actionHandler;if(i[t])throw new Error(`There is already an actionName called "${t}"`);i[t]=e}send(t,e,i){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,data:e},i)}sendWithPromise(t,e,i){const s=this.callbackId++,n=Promise.withResolvers();this.callbackCapabilities[s]=n;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,callbackId:s,data:e},i)}catch(t){n.reject(t)}return n.promise}sendWithStream(t,e,i,s){const n=this.streamId++,a=this.sourceName,r=this.targetName,o=this.comObj;return new ReadableStream({start:i=>{const l=Promise.withResolvers();return this.streamControllers[n]={controller:i,startCall:l,pullCall:null,cancelCall:null,isClosed:!1},o.postMessage({sourceName:a,targetName:r,action:t,streamId:n,data:e,desiredSize:i.desiredSize},s),l.promise},pull:t=>{const e=Promise.withResolvers();return this.streamControllers[n].pullCall=e,o.postMessage({sourceName:a,targetName:r,stream:6,streamId:n,desiredSize:t.desiredSize}),e.promise},cancel:t=>{x(t instanceof Error,"cancel must have a valid reason");const e=Promise.withResolvers();return this.streamControllers[n].cancelCall=e,this.streamControllers[n].isClosed=!0,o.postMessage({sourceName:a,targetName:r,stream:1,streamId:n,reason:be(t)}),e.promise}},i)}#ze(t){const e=t.streamId,i=this.sourceName,s=t.sourceName,n=this.comObj,a=this,r=this.actionHandler[t.action],o={enqueue(t,a=1,r){if(this.isCancelled)return;const o=this.desiredSize;this.desiredSize-=a,o>0&&this.desiredSize<=0&&(this.sinkCapability=Promise.withResolvers(),this.ready=this.sinkCapability.promise),n.postMessage({sourceName:i,targetName:s,stream:4,streamId:e,chunk:t},r)},close(){this.isCancelled||(this.isCancelled=!0,n.postMessage({sourceName:i,targetName:s,stream:3,streamId:e}),delete a.streamSinks[e])},error(t){x(t instanceof Error,"error must have a valid reason"),this.isCancelled||(this.isCancelled=!0,n.postMessage({sourceName:i,targetName:s,stream:5,streamId:e,reason:be(t)}))},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:t.desiredSize,ready:null};o.sinkCapability.resolve(),o.ready=o.sinkCapability.promise,this.streamSinks[e]=o,new Promise((function(e){e(r(t.data,o))})).then((function(){n.postMessage({sourceName:i,targetName:s,stream:8,streamId:e,success:!0})}),(function(t){n.postMessage({sourceName:i,targetName:s,stream:8,streamId:e,reason:be(t)})}))}#Be(t){const e=t.streamId,i=this.sourceName,s=t.sourceName,n=this.comObj,a=this.streamControllers[e],r=this.streamSinks[e];switch(t.stream){case 8:t.success?a.startCall.resolve():a.startCall.reject(be(t.reason));break;case 7:t.success?a.pullCall.resolve():a.pullCall.reject(be(t.reason));break;case 6:if(!r){n.postMessage({sourceName:i,targetName:s,stream:7,streamId:e,success:!0});break}r.desiredSize<=0&&t.desiredSize>0&&r.sinkCapability.resolve(),r.desiredSize=t.desiredSize,new Promise((function(t){t(r.onPull?.())})).then((function(){n.postMessage({sourceName:i,targetName:s,stream:7,streamId:e,success:!0})}),(function(t){n.postMessage({sourceName:i,targetName:s,stream:7,streamId:e,reason:be(t)})}));break;case 4:if(x(a,"enqueue should have stream controller"),a.isClosed)break;a.controller.enqueue(t.chunk);break;case 3:if(x(a,"close should have stream controller"),a.isClosed)break;a.isClosed=!0,a.controller.close(),this.#He(a,e);break;case 5:x(a,"error should have stream controller"),a.controller.error(be(t.reason)),this.#He(a,e);break;case 2:t.success?a.cancelCall.resolve():a.cancelCall.reject(be(t.reason)),this.#He(a,e);break;case 1:if(!r)break;new Promise((function(e){e(r.onCancel?.(be(t.reason)))})).then((function(){n.postMessage({sourceName:i,targetName:s,stream:2,streamId:e,success:!0})}),(function(t){n.postMessage({sourceName:i,targetName:s,stream:2,streamId:e,reason:be(t)})})),r.sinkCapability.reject(be(t.reason)),r.isCancelled=!0,delete this.streamSinks[e];break;default:throw new Error("Unexpected stream case")}}async#He(t,e){await Promise.allSettled([t.startCall?.promise,t.pullCall?.promise,t.cancelCall?.promise]),delete this.streamControllers[e]}destroy(){this.comObj.removeEventListener("message",this._onComObjOnMessage)}}class Ae{#je;#Ue;constructor({parsedData:t,rawData:e}){this.#je=t,this.#Ue=e}getRaw(){return this.#Ue}get(t){return this.#je.get(t)??null}getAll(){return N(this.#je)}has(t){return this.#je.has(t)}}const ye=Symbol("INTERNAL");class we{#$e=!1;#We=!1;#Ge=!1;#Ve=!0;constructor(t,{name:e,intent:i,usage:s}){this.#$e=!!(2&t),this.#We=!!(4&t),this.name=e,this.intent=i,this.usage=s}get visible(){if(this.#Ge)return this.#Ve;if(!this.#Ve)return!1;const{print:t,view:e}=this.usage;return this.#$e?"OFF"!==e?.viewState:!this.#We||"OFF"!==t?.printState}_setVisible(t,e,i=!1){t!==ye&&_("Internal method `_setVisible` called."),this.#Ge=i,this.#Ve=e}}class _e{#qe=null;#Xe=new Map;#Ke=null;#Ye=null;constructor(t,e=2){if(this.renderingIntent=e,this.name=null,this.creator=null,null!==t){this.name=t.name,this.creator=t.creator,this.#Ye=t.order;for(const i of t.groups)this.#Xe.set(i.id,new we(e,i));if("OFF"===t.baseState)for(const t of this.#Xe.values())t._setVisible(ye,!1);for(const e of t.on)this.#Xe.get(e)._setVisible(ye,!0);for(const e of t.off)this.#Xe.get(e)._setVisible(ye,!1);this.#Ke=this.getHash()}}#Qe(t){const e=t.length;if(e<2)return!0;const i=t[0];for(let s=1;s0?N(this.#Xe):null}getGroup(t){return this.#Xe.get(t)||null}getHash(){if(null!==this.#qe)return this.#qe;const t=new Lt;for(const[e,i]of this.#Xe)t.update(`${e}:${i.visible}`);return this.#qe=t.hexdigest()}}class xe{constructor(t,{disableRange:e=!1,disableStream:i=!1}){x(t,'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');const{length:s,initialData:n,progressiveDone:a,contentDispositionFilename:r}=t;if(this._queuedChunks=[],this._progressiveDone=a,this._contentDispositionFilename=r,n?.length>0){const t=n instanceof Uint8Array&&n.byteLength===n.buffer.byteLength?n.buffer:new Uint8Array(n).buffer;this._queuedChunks.push(t)}this._pdfDataRangeTransport=t,this._isStreamingSupported=!i,this._isRangeSupported=!e,this._contentLength=s,this._fullRequestReader=null,this._rangeReaders=[],t.addRangeListener(((t,e)=>{this._onReceiveData({begin:t,chunk:e})})),t.addProgressListener(((t,e)=>{this._onProgress({loaded:t,total:e})})),t.addProgressiveReadListener((t=>{this._onReceiveData({chunk:t})})),t.addProgressiveDoneListener((()=>{this._onProgressiveDone()})),t.transportReady()}_onReceiveData({begin:t,chunk:e}){const i=e instanceof Uint8Array&&e.byteLength===e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer;void 0===t?this._fullRequestReader?this._fullRequestReader._enqueue(i):this._queuedChunks.push(i):x(this._rangeReaders.some((function(e){return e._begin===t&&(e._enqueue(i),!0)})),"_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.")}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}_onProgress(t){void 0===t.total?this._rangeReaders[0]?.onProgress?.({loaded:t.loaded}):this._fullRequestReader?.onProgress?.({loaded:t.loaded,total:t.total})}_onProgressiveDone(){this._fullRequestReader?.progressiveDone(),this._progressiveDone=!0}_removeRangeReader(t){const e=this._rangeReaders.indexOf(t);e>=0&&this._rangeReaders.splice(e,1)}getFullReader(){x(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");const t=this._queuedChunks;return this._queuedChunks=null,new Ce(this,t,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const i=new Ee(this,t,e);return this._pdfDataRangeTransport.requestDataRange(t,e),this._rangeReaders.push(i),i}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeReaders.slice(0))e.cancel(t);this._pdfDataRangeTransport.abort()}}class Ce{constructor(t,e,i=!1,s=null){this._stream=t,this._done=i||!1,this._filename=nt(s)?s:null,this._queuedChunks=e||[],this._loaded=0;for(const t of this._queuedChunks)this._loaded+=t.byteLength;this._requests=[],this._headersReady=Promise.resolve(),t._fullRequestReader=this,this.onProgress=null}_enqueue(t){this._done||(this._requests.length>0?this._requests.shift().resolve({value:t,done:!1}):this._queuedChunks.push(t),this._loaded+=t.byteLength)}get headersReady(){return this._headersReady}get filename(){return this._filename}get isRangeSupported(){return this._stream._isRangeSupported}get isStreamingSupported(){return this._stream._isStreamingSupported}get contentLength(){return this._stream._contentLength}async read(){if(this._queuedChunks.length>0)return{value:this._queuedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}progressiveDone(){this._done||(this._done=!0)}}class Ee{constructor(t,e,i){this._stream=t,this._begin=e,this._end=i,this._queuedChunk=null,this._requests=[],this._done=!1,this.onProgress=null}_enqueue(t){if(!this._done){if(0===this._requests.length)this._queuedChunk=t;else{this._requests.shift().resolve({value:t,done:!1});for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}this._done=!0,this._stream._removeRangeReader(this)}}get isStreamingSupported(){return!1}async read(){if(this._queuedChunk){const t=this._queuedChunk;return this._queuedChunk=null,{value:t,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0,this._stream._removeRangeReader(this)}}function Se(t,e){const i=new Headers;if(!t||!e||"object"!=typeof e)return i;for(const t in e){const s=e[t];void 0!==s&&i.append(t,s)}return i}function Te({responseHeaders:t,isHttp:e,rangeChunkSize:i,disableRange:s}){const n={allowRangeRequests:!1,suggestedLength:void 0},a=parseInt(t.get("Content-Length"),10);return Number.isInteger(a)?(n.suggestedLength=a,a<=2*i||s||!e||"bytes"!==t.get("Accept-Ranges")||"identity"!==(t.get("Content-Encoding")||"identity")||(n.allowRangeRequests=!0),n):n}function Me(t){const e=t.get("Content-Disposition");if(e){let t=function(t){let e=!0,i=s("filename\\*","i").exec(t);if(i){i=i[1];let t=r(i);return t=unescape(t),t=o(t),t=l(t),a(t)}if(i=function(t){const e=[];let i;const n=s("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;null!==(i=n.exec(t));){let[,t,s,n]=i;if(t=parseInt(t,10),t in e){if(0===t)break}else e[t]=[s,n]}const a=[];for(let t=0;t{if(!Ie(e.status))throw ke(e.status,s);this._reader=e.body.getReader(),this._headersCapability.resolve();const i=e.headers,{allowRangeRequests:n,suggestedLength:a}=Te({responseHeaders:i,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=n,this._contentLength=a||this._contentLength,this._filename=Me(i),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new D("Streaming is disabled."))})).catch(this._headersCapability.reject),this.onProgress=null}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._headersCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:(this._loaded+=t.byteLength,this.onProgress?.({loaded:this._loaded,total:this._contentLength}),{value:Re(t),done:!1})}cancel(t){this._reader?.cancel(t),this._abortController.abort()}}class Fe{constructor(t,e,i){this._stream=t,this._reader=null,this._loaded=0;const s=t.source;this._withCredentials=s.withCredentials||!1,this._readCapability=Promise.withResolvers(),this._isStreamingSupported=!s.disableStream,this._abortController=new AbortController;const n=new Headers(t.headers);n.append("Range",`bytes=${e}-${i-1}`);const a=s.url;fetch(a,Pe(n,this._withCredentials,this._abortController)).then((t=>{if(!Ie(t.status))throw ke(t.status,a);this._readCapability.resolve(),this._reader=t.body.getReader()})).catch(this._readCapability.reject),this.onProgress=null}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._readCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:(this._loaded+=t.byteLength,this.onProgress?.({loaded:this._loaded}),{value:Re(t),done:!1})}cancel(t){this._reader?.cancel(t),this._abortController.abort()}}class Ne{constructor({url:t,httpHeaders:e,withCredentials:i}){this.url=t,this.isHttp=/^https?:/i.test(t),this.headers=Se(this.isHttp,e),this.withCredentials=i||!1,this.currXhrId=0,this.pendingRequests=Object.create(null)}requestRange(t,e,i){const s={begin:t,end:e};for(const t in i)s[t]=i[t];return this.request(s)}requestFull(t){return this.request(t)}request(t){const e=new XMLHttpRequest,i=this.currXhrId++,s=this.pendingRequests[i]={xhr:e};e.open("GET",this.url),e.withCredentials=this.withCredentials;for(const[t,i]of this.headers)e.setRequestHeader(t,i);return this.isHttp&&"begin"in t&&"end"in t?(e.setRequestHeader("Range",`bytes=${t.begin}-${t.end-1}`),s.expectedStatus=206):s.expectedStatus=200,e.responseType="arraybuffer",t.onError&&(e.onerror=function(i){t.onError(e.status)}),e.onreadystatechange=this.onStateChange.bind(this,i),e.onprogress=this.onProgress.bind(this,i),s.onHeadersReceived=t.onHeadersReceived,s.onDone=t.onDone,s.onError=t.onError,s.onProgress=t.onProgress,e.send(null),i}onProgress(t,e){const i=this.pendingRequests[t];i&&i.onProgress?.(e)}onStateChange(t,e){const i=this.pendingRequests[t];if(!i)return;const s=i.xhr;if(s.readyState>=2&&i.onHeadersReceived&&(i.onHeadersReceived(),delete i.onHeadersReceived),4!==s.readyState)return;if(!(t in this.pendingRequests))return;if(delete this.pendingRequests[t],0===s.status&&this.isHttp)return void i.onError?.(s.status);const n=s.status||200;if((200!==n||206!==i.expectedStatus)&&n!==i.expectedStatus)return void i.onError?.(s.status);const a=function(t){const e=t.response;return"string"!=typeof e?e:F(e).buffer}(s);if(206===n){const t=s.getResponseHeader("Content-Range"),e=/bytes (\d+)-(\d+)\/(\d+)/.exec(t);i.onDone({begin:parseInt(e[1],10),chunk:a})}else a?i.onDone({begin:0,chunk:a}):i.onError?.(s.status)}getRequestXhr(t){return this.pendingRequests[t].xhr}isPendingRequest(t){return t in this.pendingRequests}abortRequest(t){const e=this.pendingRequests[t].xhr;delete this.pendingRequests[t],e.abort()}}class Oe{constructor(t){this._source=t,this._manager=new Ne(t),this._rangeChunkSize=t.rangeChunkSize,this._fullRequestReader=null,this._rangeRequestReaders=[]}_onRangeRequestReaderClosed(t){const e=this._rangeRequestReaders.indexOf(t);e>=0&&this._rangeRequestReaders.splice(e,1)}getFullReader(){return x(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once."),this._fullRequestReader=new Be(this._manager,this._source),this._fullRequestReader}getRangeReader(t,e){const i=new ze(this._manager,t,e);return i.onClosed=this._onRangeRequestReaderClosed.bind(this),this._rangeRequestReaders.push(i),i}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class Be{constructor(t,e){this._manager=t;const i={onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)};this._url=e.url,this._fullRequestId=t.requestFull(i),this._headersCapability=Promise.withResolvers(),this._disableRange=e.disableRange||!1,this._contentLength=e.length,this._rangeChunkSize=e.rangeChunkSize,this._rangeChunkSize||this._disableRange||(this._disableRange=!0),this._isStreamingSupported=!1,this._isRangeSupported=!1,this._cachedChunks=[],this._requests=[],this._done=!1,this._storedError=void 0,this._filename=null,this.onProgress=null}_onHeadersReceived(){const t=this._fullRequestId,e=this._manager.getRequestXhr(t),i=new Headers(e.getAllResponseHeaders().trim().split(/[\r\n]+/).map((t=>{const[e,...i]=t.split(": ");return[e,i.join(": ")]}))),{allowRangeRequests:s,suggestedLength:n}=Te({responseHeaders:i,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});s&&(this._isRangeSupported=!0),this._contentLength=n||this._contentLength,this._filename=Me(i),this._isRangeSupported&&this._manager.abortRequest(t),this._headersCapability.resolve()}_onDone(t){if(t&&(this._requests.length>0?this._requests.shift().resolve({value:t.chunk,done:!1}):this._cachedChunks.push(t.chunk)),this._done=!0,!(this._cachedChunks.length>0)){for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}}_onError(t){this._storedError=ke(t,this._url),this._headersCapability.reject(this._storedError);for(const t of this._requests)t.reject(this._storedError);this._requests.length=0,this._cachedChunks.length=0}_onProgress(t){this.onProgress?.({loaded:t.loaded,total:t.lengthComputable?t.total:this._contentLength})}get filename(){return this._filename}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}get contentLength(){return this._contentLength}get headersReady(){return this._headersCapability.promise}async read(){if(this._storedError)throw this._storedError;if(this._cachedChunks.length>0)return{value:this._cachedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0,this._headersCapability.reject(t);for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._fullRequestId)&&this._manager.abortRequest(this._fullRequestId),this._fullRequestReader=null}}class ze{constructor(t,e,i){this._manager=t;const s={onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)};this._url=t.url,this._requestId=t.requestRange(e,i,s),this._requests=[],this._queuedChunk=null,this._done=!1,this._storedError=void 0,this.onProgress=null,this.onClosed=null}_close(){this.onClosed?.(this)}_onDone(t){const e=t.chunk;this._requests.length>0?this._requests.shift().resolve({value:e,done:!1}):this._queuedChunk=e,this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0,this._close()}_onError(t){this._storedError=ke(t,this._url);for(const t of this._requests)t.reject(this._storedError);this._requests.length=0,this._queuedChunk=null}_onProgress(t){this.isStreamingSupported||this.onProgress?.({loaded:t.loaded})}get isStreamingSupported(){return!1}async read(){if(this._storedError)throw this._storedError;if(null!==this._queuedChunk){const t=this._queuedChunk;return this._queuedChunk=null,{value:t,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._requestId)&&this._manager.abortRequest(this._requestId),this._close()}}const He=/^[a-z][a-z0-9\-+.]+:/i;function je(t,e,i){return"http:"===t.protocol?Ut.get("http").request(t,{headers:e},i):Ut.get("https").request(t,{headers:e},i)}class Ue{constructor(t){this.source=t,this.url=function(t){if(He.test(t))return new URL(t);const e=Ut.get("url");return new URL(e.pathToFileURL(t))}(t.url),this.isHttp="http:"===this.url.protocol||"https:"===this.url.protocol,this.isFsUrl="file:"===this.url.protocol,this.headers=Se(this.isHttp,t.httpHeaders),this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return x(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once."),this._fullRequestReader=this.isFsUrl?new qe(this):new Ge(this),this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const i=this.isFsUrl?new Xe(this,t,e):new Ve(this,t,e);return this._rangeRequestReaders.push(i),i}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class $e{constructor(t){this._url=t.url,this._done=!1,this._storedError=null,this.onProgress=null;const e=t.source;this._contentLength=e.length,this._loaded=0,this._filename=null,this._disableRange=e.disableRange||!1,this._rangeChunkSize=e.rangeChunkSize,this._rangeChunkSize||this._disableRange||(this._disableRange=!0),this._isStreamingSupported=!e.disableStream,this._isRangeSupported=!e.disableRange,this._readableStream=null,this._readCapability=Promise.withResolvers(),this._headersCapability=Promise.withResolvers()}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const t=this._readableStream.read();return null===t?(this._readCapability=Promise.withResolvers(),this.read()):(this._loaded+=t.length,this.onProgress?.({loaded:this._loaded,total:this._contentLength}),{value:new Uint8Array(t).buffer,done:!1})}cancel(t){this._readableStream?this._readableStream.destroy(t):this._error(t)}_error(t){this._storedError=t,this._readCapability.resolve()}_setReadableStream(t){this._readableStream=t,t.on("readable",(()=>{this._readCapability.resolve()})),t.on("end",(()=>{t.destroy(),this._done=!0,this._readCapability.resolve()})),t.on("error",(t=>{this._error(t)})),!this._isStreamingSupported&&this._isRangeSupported&&this._error(new D("streaming is disabled")),this._storedError&&this._readableStream.destroy(this._storedError)}}class We{constructor(t){this._url=t.url,this._done=!1,this._storedError=null,this.onProgress=null,this._loaded=0,this._readableStream=null,this._readCapability=Promise.withResolvers();const e=t.source;this._isStreamingSupported=!e.disableStream}get isStreamingSupported(){return this._isStreamingSupported}async read(){if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const t=this._readableStream.read();return null===t?(this._readCapability=Promise.withResolvers(),this.read()):(this._loaded+=t.length,this.onProgress?.({loaded:this._loaded}),{value:new Uint8Array(t).buffer,done:!1})}cancel(t){this._readableStream?this._readableStream.destroy(t):this._error(t)}_error(t){this._storedError=t,this._readCapability.resolve()}_setReadableStream(t){this._readableStream=t,t.on("readable",(()=>{this._readCapability.resolve()})),t.on("end",(()=>{t.destroy(),this._done=!0,this._readCapability.resolve()})),t.on("error",(t=>{this._error(t)})),this._storedError&&this._readableStream.destroy(this._storedError)}}class Ge extends $e{constructor(t){super(t);const e=Object.fromEntries(t.headers);this._request=je(this._url,e,(e=>{if(404===e.statusCode){const t=new I(`Missing PDF "${this._url}".`);return this._storedError=t,void this._headersCapability.reject(t)}this._headersCapability.resolve(),this._setReadableStream(e);const i=new Headers(this._readableStream.headers),{allowRangeRequests:s,suggestedLength:n}=Te({responseHeaders:i,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=s,this._contentLength=n||this._contentLength,this._filename=Me(i)})),this._request.on("error",(t=>{this._storedError=t,this._headersCapability.reject(t)})),this._request.end()}}class Ve extends We{constructor(t,e,i){super(t);const s=Object.fromEntries(t.headers);s.Range=`bytes=${e}-${i-1}`,this._request=je(this._url,s,(t=>{if(404!==t.statusCode)this._setReadableStream(t);else{const t=new I(`Missing PDF "${this._url}".`);this._storedError=t}})),this._request.on("error",(t=>{this._storedError=t})),this._request.end()}}class qe extends $e{constructor(t){super(t);const e=Ut.get("fs");e.promises.lstat(this._url).then((t=>{this._contentLength=t.size,this._setReadableStream(e.createReadStream(this._url)),this._headersCapability.resolve()}),(t=>{"ENOENT"===t.code&&(t=new I(`Missing PDF "${this._url}".`)),this._storedError=t,this._headersCapability.reject(t)}))}}class Xe extends We{constructor(t,e,i){super(t);const s=Ut.get("fs");this._setReadableStream(s.createReadStream(this._url,{start:e,end:i-1}))}}const Ke=30;class Ye{#Je=Promise.withResolvers();#ut=null;#Ze=!1;#ti=!!globalThis.FontInspector?.enabled;#ei=null;#ii=null;#si=0;#ni=0;#ai=null;#ri=null;#oi=0;#li=0;#hi=Object.create(null);#di=[];#ci=null;#ui=[];#pi=new WeakMap;#gi=null;static#mi=new Map;static#fi=new Map;static#bi=new WeakMap;static#vi=null;static#Ai=new Set;constructor({textContentSource:t,container:e,viewport:i}){if(t instanceof ReadableStream)this.#ci=t;else{if("object"!=typeof t)throw new Error('No "textContentSource" parameter specified.');this.#ci=new ReadableStream({start(e){e.enqueue(t),e.close()}})}this.#ut=this.#ri=e,this.#li=i.scale*(globalThis.devicePixelRatio||1),this.#oi=i.rotation,this.#ii={div:null,properties:null,ctx:null};const{pageWidth:s,pageHeight:n,pageX:a,pageY:r}=i.rawDims;this.#gi=[1,0,0,-1,-a,r+n],this.#ni=s,this.#si=n,Ye.#yi(),bt(e,i),this.#Je.promise.finally((()=>{Ye.#Ai.delete(this),this.#ii=null,this.#hi=null})).catch((()=>{}))}static get fontFamilyMap(){const{isWindows:t,isFirefox:e}=O.platform;return E(this,"fontFamilyMap",new Map([["sans-serif",(t&&e?"Calibri, ":"")+"sans-serif"],["monospace",(t&&e?"Lucida Console, ":"")+"monospace"]]))}render(){const t=()=>{this.#ai.read().then((({value:e,done:i})=>{i?this.#Je.resolve():(this.#ei??=e.lang,Object.assign(this.#hi,e.styles),this.#wi(e.items),t())}),this.#Je.reject)};return this.#ai=this.#ci.getReader(),Ye.#Ai.add(this),t(),this.#Je.promise}update({viewport:t,onBefore:e=null}){const i=t.scale*(globalThis.devicePixelRatio||1),s=t.rotation;if(s!==this.#oi&&(e?.(),this.#oi=s,bt(this.#ri,{rotation:s})),i!==this.#li){e?.(),this.#li=i;const t={div:null,properties:null,ctx:Ye.#_i(this.#ei)};for(const e of this.#ui)t.properties=this.#pi.get(e),t.div=e,this.#xi(t)}}cancel(){const t=new D("TextLayer task cancelled.");this.#ai?.cancel(t).catch((()=>{})),this.#ai=null,this.#Je.reject(t)}get textDivs(){return this.#ui}get textContentItemsStr(){return this.#di}#wi(t){if(this.#Ze)return;this.#ii.ctx??=Ye.#_i(this.#ei);const e=this.#ui,i=this.#di;for(const s of t){if(e.length>1e5)return w("Ignoring additional textDivs for performance reasons."),void(this.#Ze=!0);if(void 0!==s.str)i.push(s.str),this.#Ci(s);else if("beginMarkedContentProps"===s.type||"beginMarkedContent"===s.type){const t=this.#ut;this.#ut=document.createElement("span"),this.#ut.classList.add("markedContent"),null!==s.id&&this.#ut.setAttribute("id",`${s.id}`),t.append(this.#ut)}else"endMarkedContent"===s.type&&(this.#ut=this.#ut.parentNode)}}#Ci(t){const e=document.createElement("span"),i={angle:0,canvasWidth:0,hasText:""!==t.str,hasEOL:t.hasEOL,fontSize:0};this.#ui.push(e);const s=z.transform(this.#gi,t.transform);let n=Math.atan2(s[1],s[0]);const a=this.#hi[t.fontName];a.vertical&&(n+=Math.PI/2);let r=this.#ti&&a.fontSubstitution||a.fontFamily;r=Ye.fontFamilyMap.get(r)||r;const o=Math.hypot(s[2],s[3]),l=o*Ye.#Ei(r,this.#ei);let h,d;0===n?(h=s[4],d=s[5]-l):(h=s[4]+l*Math.sin(n),d=s[5]-l*Math.cos(n));const c="calc(var(--scale-factor)*",u=e.style;this.#ut===this.#ri?(u.left=`${(100*h/this.#ni).toFixed(2)}%`,u.top=`${(100*d/this.#si).toFixed(2)}%`):(u.left=`${c}${h.toFixed(2)}px)`,u.top=`${c}${d.toFixed(2)}px)`),u.fontSize=`${c}${(Ye.#vi*o).toFixed(2)}px)`,u.fontFamily=r,i.fontSize=o,e.setAttribute("role","presentation"),e.textContent=t.str,e.dir=t.dir,this.#ti&&(e.dataset.fontName=a.fontSubstitutionLoadedName||t.fontName),0!==n&&(i.angle=n*(180/Math.PI));let p=!1;if(t.str.length>1)p=!0;else if(" "!==t.str&&t.transform[0]!==t.transform[3]){const e=Math.abs(t.transform[0]),i=Math.abs(t.transform[3]);e!==i&&Math.max(e,i)/Math.min(e,i)>1.5&&(p=!0)}if(p&&(i.canvasWidth=a.vertical?t.height:t.width),this.#pi.set(e,i),this.#ii.div=e,this.#ii.properties=i,this.#xi(this.#ii),i.hasText&&this.#ut.append(e),i.hasEOL){const t=document.createElement("br");t.setAttribute("role","presentation"),this.#ut.append(t)}}#xi(t){const{div:e,properties:i,ctx:s}=t,{style:n}=e;let a="";if(Ye.#vi>1&&(a=`scale(${1/Ye.#vi})`),0!==i.canvasWidth&&i.hasText){const{fontFamily:t}=n,{canvasWidth:r,fontSize:o}=i;Ye.#Si(s,o*this.#li,t);const{width:l}=s.measureText(e.textContent);l>0&&(a=`scaleX(${r*this.#li/l}) ${a}`)}0!==i.angle&&(a=`rotate(${i.angle}deg) ${a}`),a.length>0&&(n.transform=a)}static cleanup(){if(!(this.#Ai.size>0)){this.#mi.clear();for(const{canvas:t}of this.#fi.values())t.remove();this.#fi.clear()}}static#_i(t=null){let e=this.#fi.get(t||="");if(!e){const i=document.createElement("canvas");i.className="hiddenCanvasElement",i.lang=t,document.body.append(i),e=i.getContext("2d",{alpha:!1,willReadFrequently:!0}),this.#fi.set(t,e),this.#bi.set(e,{size:0,family:""})}return e}static#Si(t,e,i){const s=this.#bi.get(t);e===s.size&&i===s.family||(t.font=`${e}px ${i}`,s.size=e,s.family=i)}static#yi(){if(null!==this.#vi)return;const t=document.createElement("div");t.style.opacity=0,t.style.lineHeight=1,t.style.fontSize="1px",t.style.position="absolute",t.textContent="X",document.body.append(t),this.#vi=t.getBoundingClientRect().height,t.remove()}static#Ei(t,e){const i=this.#mi.get(t);if(i)return i;const s=this.#_i(e);s.canvas.width=s.canvas.height=Ke,this.#Si(s,Ke,t);const n=s.measureText("");let a=n.fontBoundingBoxAscent,r=Math.abs(n.fontBoundingBoxDescent);if(a){const e=a/(a+r);return this.#mi.set(t,e),s.canvas.width=s.canvas.height=0,e}s.strokeStyle="red",s.clearRect(0,0,Ke,Ke),s.strokeText("g",0,0);let o=s.getImageData(0,0,Ke,Ke).data;r=0;for(let t=o.length-1-3;t>=0;t-=4)if(o[t]>0){r=Math.ceil(t/4/Ke);break}s.clearRect(0,0,Ke,Ke),s.strokeText("A",0,Ke),o=s.getImageData(0,0,Ke,Ke).data,a=0;for(let t=0,e=o.length;t0){a=Ke-Math.floor(t/4/Ke);break}s.canvas.width=s.canvas.height=0;const l=a?a/(a+r):.8;return this.#mi.set(t,l),l}}class Qe{static textContent(t){const e=[],i={items:e,styles:Object.create(null)};return function t(i){if(!i)return;let s=null;const n=i.name;if("#text"===n)s=i.value;else{if(!Qe.shouldBuildText(n))return;i?.attributes?.textContent?s=i.attributes.textContent:i.value&&(s=i.value)}if(null!==s&&e.push({str:s}),i.children)for(const e of i.children)t(e)}(t),i}static shouldBuildText(t){return!("textarea"===t||"input"===t||"option"===t||"select"===t)}}const Je=n?class extends G{_createCanvas(t,e){return Ut.get("canvas").createCanvas(t,e)}}:class extends G{constructor({ownerDocument:t=globalThis.document,enableHWA:e=!1}){super({enableHWA:e}),this._document=t}_createCanvas(t,e){const i=this._document.createElement("canvas");return i.width=t,i.height=e,i}},Ze=n?class extends V{_fetchData(t,e){return $t(t).then((t=>({cMapData:t,compressionType:e})))}}:J,ti=n?class extends W{}:class extends W{#Ti;#Mi;#ki;#Ii;#Pi;#Ri;#A=0;constructor({docId:t,ownerDocument:e=globalThis.document}){super(),this.#Ii=t,this.#Pi=e}get#w(){return this.#Mi||=new Map}get#Di(){return this.#Ri||=new Map}get#Li(){if(!this.#ki){const t=this.#Pi.createElement("div"),{style:e}=t;e.visibility="hidden",e.contain="strict",e.width=e.height=0,e.position="absolute",e.top=e.left=0,e.zIndex=-1;const i=this.#Pi.createElementNS(K,"svg");i.setAttribute("width",0),i.setAttribute("height",0),this.#ki=this.#Pi.createElementNS(K,"defs"),t.append(i),i.append(this.#ki),this.#Pi.body.append(t)}return this.#ki}#Fi(t){if(1===t.length){const e=t[0],i=new Array(256);for(let t=0;t<256;t++)i[t]=e[t]/255;const s=i.join(",");return[s,s,s]}const[e,i,s]=t,n=new Array(256),a=new Array(256),r=new Array(256);for(let t=0;t<256;t++)n[t]=e[t]/255,a[t]=i[t]/255,r[t]=s[t]/255;return[n.join(","),a.join(","),r.join(",")]}#Ni(t){if(void 0===this.#Ti){this.#Ti="";const t=this.#Pi.URL;t!==this.#Pi.baseURI&&(st(t)?w('#createUrl: ignore "data:"-URL for performance reasons.'):this.#Ti=t.split("#",1)[0])}return`url(${this.#Ti}#${t})`}addFilter(t){if(!t)return"none";let e=this.#w.get(t);if(e)return e;const[i,s,n]=this.#Fi(t),a=1===t.length?i:`${i}${s}${n}`;if(e=this.#w.get(a),e)return this.#w.set(t,e),e;const r=`g_${this.#Ii}_transfer_map_${this.#A++}`,o=this.#Ni(r);this.#w.set(t,o),this.#w.set(a,o);const l=this.#Oi(r);return this.#Bi(i,s,n,l),o}addHCMFilter(t,e){const i=`${t}-${e}`,s="base";let n=this.#Di.get(s);if(n?.key===i)return n.url;if(n?(n.filter?.remove(),n.key=i,n.url="none",n.filter=null):(n={key:i,url:"none",filter:null},this.#Di.set(s,n)),!t||!e)return n.url;const a=this.#zi(t);t=z.makeHexColor(...a);const r=this.#zi(e);if(e=z.makeHexColor(...r),this.#Li.style.color="","#000000"===t&&"#ffffff"===e||t===e)return n.url;const o=new Array(256);for(let t=0;t<=255;t++){const e=t/255;o[t]=e<=.03928?e/12.92:((e+.055)/1.055)**2.4}const l=o.join(","),h=`g_${this.#Ii}_hcm_filter`,d=n.filter=this.#Oi(h);this.#Bi(l,l,l,d),this.#Hi(d);const c=(t,e)=>{const i=a[t]/255,s=r[t]/255,n=new Array(e+1);for(let t=0;t<=e;t++)n[t]=i+t/e*(s-i);return n.join(",")};return this.#Bi(c(0,5),c(1,5),c(2,5),d),n.url=this.#Ni(h),n.url}addAlphaFilter(t){let e=this.#w.get(t);if(e)return e;const[i]=this.#Fi([t]),s=`alpha_${i}`;if(e=this.#w.get(s),e)return this.#w.set(t,e),e;const n=`g_${this.#Ii}_alpha_map_${this.#A++}`,a=this.#Ni(n);this.#w.set(t,a),this.#w.set(s,a);const r=this.#Oi(n);return this.#ji(i,r),a}addLuminosityFilter(t){let e,i,s=this.#w.get(t||"luminosity");if(s)return s;if(t?([e]=this.#Fi([t]),i=`luminosity_${e}`):i="luminosity",s=this.#w.get(i),s)return this.#w.set(t,s),s;const n=`g_${this.#Ii}_luminosity_map_${this.#A++}`,a=this.#Ni(n);this.#w.set(t,a),this.#w.set(i,a);const r=this.#Oi(n);return this.#Ui(r),t&&this.#ji(e,r),a}addHighlightHCMFilter(t,e,i,s,n){const a=`${e}-${i}-${s}-${n}`;let r=this.#Di.get(t);if(r?.key===a)return r.url;if(r?(r.filter?.remove(),r.key=a,r.url="none",r.filter=null):(r={key:a,url:"none",filter:null},this.#Di.set(t,r)),!e||!i)return r.url;const[o,l]=[e,i].map(this.#zi.bind(this));let h=Math.round(.2126*o[0]+.7152*o[1]+.0722*o[2]),d=Math.round(.2126*l[0]+.7152*l[1]+.0722*l[2]),[c,u]=[s,n].map(this.#zi.bind(this));d{const s=new Array(256),n=(d-h)/i,a=t/255,r=(e-t)/(255*i);let o=0;for(let t=0;t<=i;t++){const e=Math.round(h+t*n),i=a+t*r;for(let t=o;t<=e;t++)s[t]=i;o=e+1}for(let t=o;t<256;t++)s[t]=s[o-1];return s.join(",")},g=`g_${this.#Ii}_hcm_${t}_filter`,m=r.filter=this.#Oi(g);return this.#Hi(m),this.#Bi(p(c[0],u[0],5),p(c[1],u[1],5),p(c[2],u[2],5),m),r.url=this.#Ni(g),r.url}destroy(t=!1){t&&0!==this.#Di.size||(this.#ki&&(this.#ki.parentNode.parentNode.remove(),this.#ki=null),this.#Mi&&(this.#Mi.clear(),this.#Mi=null),this.#A=0)}#Ui(t){const e=this.#Pi.createElementNS(K,"feColorMatrix");e.setAttribute("type","matrix"),e.setAttribute("values","0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0.59 0.11 0 0"),t.append(e)}#Hi(t){const e=this.#Pi.createElementNS(K,"feColorMatrix");e.setAttribute("type","matrix"),e.setAttribute("values","0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0"),t.append(e)}#Oi(t){const e=this.#Pi.createElementNS(K,"filter");return e.setAttribute("color-interpolation-filters","sRGB"),e.setAttribute("id",t),this.#Li.append(e),e}#$i(t,e,i){const s=this.#Pi.createElementNS(K,e);s.setAttribute("type","discrete"),s.setAttribute("tableValues",i),t.append(s)}#Bi(t,e,i,s){const n=this.#Pi.createElementNS(K,"feComponentTransfer");s.append(n),this.#$i(n,"feFuncR",t),this.#$i(n,"feFuncG",e),this.#$i(n,"feFuncB",i)}#ji(t,e){const i=this.#Pi.createElementNS(K,"feComponentTransfer");e.append(i),this.#$i(i,"feFuncA",t)}#zi(t){return this.#Li.style.color=t,gt(getComputedStyle(this.#Li).getPropertyValue("color"))}},ei=n?class extends q{_fetchData(t){return $t(t)}}:Z;function ii(t={}){"string"==typeof t||t instanceof URL?t={url:t}:(t instanceof ArrayBuffer||ArrayBuffer.isView(t))&&(t={data:t});const e=new ni,{docId:i}=e,s=t.url?function(t){if(t instanceof URL)return t.href;try{return new URL(t,window.location).href}catch{if(n&&"string"==typeof t)return t}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}(t.url):null,a=t.data?function(t){if(n&&"undefined"!=typeof Buffer&&t instanceof Buffer)throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");if(t instanceof Uint8Array&&t.byteLength===t.buffer.byteLength)return t;if("string"==typeof t)return F(t);if(t instanceof ArrayBuffer||ArrayBuffer.isView(t)||"object"==typeof t&&!isNaN(t?.length))return new Uint8Array(t);throw new Error("Invalid PDF binary data: either TypedArray, string, or array-like object is expected in the data property.")}(t.data):null,r=t.httpHeaders||null,o=!0===t.withCredentials,l=t.password??null,h=t.range instanceof ai?t.range:null,d=Number.isInteger(t.rangeChunkSize)&&t.rangeChunkSize>0?t.rangeChunkSize:65536;let c=t.worker instanceof hi?t.worker:null;const u=t.verbosity,p="string"!=typeof t.docBaseUrl||st(t.docBaseUrl)?null:t.docBaseUrl,g="string"==typeof t.cMapUrl?t.cMapUrl:null,m=!1!==t.cMapPacked,f=t.CMapReaderFactory||Ze,b="string"==typeof t.standardFontDataUrl?t.standardFontDataUrl:null,A=t.StandardFontDataFactory||ei,y=!0!==t.stopAtErrors,w=Number.isInteger(t.maxImageSize)&&t.maxImageSize>-1?t.maxImageSize:-1,_=!1!==t.isEvalSupported,x="boolean"==typeof t.isOffscreenCanvasSupported?t.isOffscreenCanvasSupported:!n,C=Number.isInteger(t.canvasMaxAreaInBytes)?t.canvasMaxAreaInBytes:-1,E="boolean"==typeof t.disableFontFace?t.disableFontFace:n,S=!0===t.fontExtraProperties,T=!0===t.enableXfa,M=t.ownerDocument||globalThis.document,k=!0===t.disableRange,I=!0===t.disableStream,P=!0===t.disableAutoFetch,R=!0===t.pdfBug,D=t.CanvasFactory||Je,L=t.FilterFactory||ti,N=!0===t.enableHWA,O=h?h.length:t.length??NaN,B="boolean"==typeof t.useSystemFonts?t.useSystemFonts:!n&&!E,z="boolean"==typeof t.useWorkerFetch?t.useWorkerFetch:f===J&&A===Z&&g&&b&<(g,document.baseURI)&<(b,document.baseURI);t.canvasFactory&&dt("`canvasFactory`-instance option, please use `CanvasFactory` instead."),t.filterFactory&&dt("`filterFactory`-instance option, please use `FilterFactory` instead."),v(u);const H={canvasFactory:new D({ownerDocument:M,enableHWA:N}),filterFactory:new L({docId:i,ownerDocument:M}),cMapReaderFactory:z?null:new f({baseUrl:g,isCompressed:m}),standardFontDataFactory:z?null:new A({baseUrl:b})};if(!c){const t={verbosity:u,port:fe.workerPort};c=t.port?hi.fromPort(t):new hi(t),e._worker=c}const j={docId:i,apiVersion:"4.7.76",data:a,password:l,disableAutoFetch:P,rangeChunkSize:d,length:O,docBaseUrl:p,enableXfa:T,evaluatorOptions:{maxImageSize:w,disableFontFace:E,ignoreErrors:y,isEvalSupported:_,isOffscreenCanvasSupported:x,canvasMaxAreaInBytes:C,fontExtraProperties:S,useSystemFonts:B,cMapUrl:z?g:null,standardFontDataUrl:z?b:null}},U={disableFontFace:E,fontExtraProperties:S,ownerDocument:M,pdfBug:R,styleElement:null,loadingParams:{disableAutoFetch:P,enableXfa:T}};return c.promise.then((function(){if(e.destroyed)throw new Error("Loading aborted");if(c.destroyed)throw new Error("Worker was destroyed");const t=c.messageHandler.sendWithPromise("GetDocRequest",j,a?[a.buffer]:null);let l;if(h)l=new xe(h,{disableRange:k,disableStream:I});else if(!a){if(!s)throw new Error("getDocument - no `url` parameter provided.");let t;t=n?"undefined"!=typeof fetch&&"undefined"!=typeof Response&&"body"in Response.prototype&<(s)?De:Ue:lt(s)?De:Oe,l=new t({url:s,length:O,httpHeaders:r,withCredentials:o,rangeChunkSize:d,disableRange:k,disableStream:I})}return t.then((t=>{if(e.destroyed)throw new Error("Loading aborted");if(c.destroyed)throw new Error("Worker was destroyed");const s=new ve(i,t,c.port),n=new di(s,e,l,U,H);e._transport=n,s.send("Ready",null)}))})).catch(e._capability.reject),e}function si(t){return"object"==typeof t&&Number.isInteger(t?.num)&&t.num>=0&&Number.isInteger(t?.gen)&&t.gen>=0}class ni{static#Ii=0;constructor(){this._capability=Promise.withResolvers(),this._transport=null,this._worker=null,this.docId="d"+ni.#Ii++,this.destroyed=!1,this.onPassword=null,this.onProgress=null}get promise(){return this._capability.promise}async destroy(){this.destroyed=!0;try{this._worker?.port&&(this._worker._pendingDestroy=!0),await(this._transport?.destroy())}catch(t){throw this._worker?.port&&delete this._worker._pendingDestroy,t}this._transport=null,this._worker&&(this._worker.destroy(),this._worker=null)}}class ai{constructor(t,e,i=!1,s=null){this.length=t,this.initialData=e,this.progressiveDone=i,this.contentDispositionFilename=s,this._rangeListeners=[],this._progressListeners=[],this._progressiveReadListeners=[],this._progressiveDoneListeners=[],this._readyCapability=Promise.withResolvers()}addRangeListener(t){this._rangeListeners.push(t)}addProgressListener(t){this._progressListeners.push(t)}addProgressiveReadListener(t){this._progressiveReadListeners.push(t)}addProgressiveDoneListener(t){this._progressiveDoneListeners.push(t)}onDataRange(t,e){for(const i of this._rangeListeners)i(t,e)}onDataProgress(t,e){this._readyCapability.promise.then((()=>{for(const i of this._progressListeners)i(t,e)}))}onDataProgressiveRead(t){this._readyCapability.promise.then((()=>{for(const e of this._progressiveReadListeners)e(t)}))}onDataProgressiveDone(){this._readyCapability.promise.then((()=>{for(const t of this._progressiveDoneListeners)t()}))}transportReady(){this._readyCapability.resolve()}requestDataRange(t,e){_("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class ri{constructor(t,e){this._pdfInfo=t,this._transport=e}get annotationStorage(){return this._transport.annotationStorage}get canvasFactory(){return this._transport.canvasFactory}get filterFactory(){return this._transport.filterFactory}get numPages(){return this._pdfInfo.numPages}get fingerprints(){return this._pdfInfo.fingerprints}get isPureXfa(){return E(this,"isPureXfa",!!this._transport._htmlForXfa)}get allXfaHtml(){return this._transport._htmlForXfa}getPage(t){return this._transport.getPage(t)}getPageIndex(t){return this._transport.getPageIndex(t)}getDestinations(){return this._transport.getDestinations()}getDestination(t){return this._transport.getDestination(t)}getPageLabels(){return this._transport.getPageLabels()}getPageLayout(){return this._transport.getPageLayout()}getPageMode(){return this._transport.getPageMode()}getViewerPreferences(){return this._transport.getViewerPreferences()}getOpenAction(){return this._transport.getOpenAction()}getAttachments(){return this._transport.getAttachments()}getJSActions(){return this._transport.getDocJSActions()}getOutline(){return this._transport.getOutline()}getOptionalContentConfig({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getOptionalContentConfig(e)}getPermissions(){return this._transport.getPermissions()}getMetadata(){return this._transport.getMetadata()}getMarkInfo(){return this._transport.getMarkInfo()}getData(){return this._transport.getData()}saveDocument(){return this._transport.saveDocument()}getDownloadInfo(){return this._transport.downloadInfoCapability.promise}cleanup(t=!1){return this._transport.startCleanup(t||this.isPureXfa)}destroy(){return this.loadingTask.destroy()}cachedPageNumber(t){return this._transport.cachedPageNumber(t)}get loadingParams(){return this._transport.loadingParams}get loadingTask(){return this._transport.loadingTask}getFieldObjects(){return this._transport.getFieldObjects()}hasJSActions(){return this._transport.hasJSActions()}getCalculationOrderIds(){return this._transport.getCalculationOrderIds()}}class oi{#Wi=null;#Gi=!1;constructor(t,e,i,s=!1){this._pageIndex=t,this._pageInfo=e,this._transport=i,this._stats=s?new ot:null,this._pdfBug=s,this.commonObjs=i.commonObjs,this.objs=new ui,this._maybeCleanupAfterRender=!1,this._intentStates=new Map,this.destroyed=!1}get pageNumber(){return this._pageIndex+1}get rotate(){return this._pageInfo.rotate}get ref(){return this._pageInfo.ref}get userUnit(){return this._pageInfo.userUnit}get view(){return this._pageInfo.view}getViewport({scale:t,rotation:e=this.rotate,offsetX:i=0,offsetY:s=0,dontFlip:n=!1}={}){return new et({viewBox:this.view,scale:t,rotation:e,offsetX:i,offsetY:s,dontFlip:n})}getAnnotations({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getAnnotations(this._pageIndex,e)}getJSActions(){return this._transport.getPageJSActions(this._pageIndex)}get filterFactory(){return this._transport.filterFactory}get isPureXfa(){return E(this,"isPureXfa",!!this._transport._htmlForXfa)}async getXfa(){return this._transport._htmlForXfa?.children[this._pageIndex]||null}render({canvasContext:t,viewport:e,intent:i="display",annotationMode:s=l.ENABLE,transform:n=null,background:a=null,optionalContentConfigPromise:r=null,annotationCanvasMap:o=null,pageColors:h=null,printAnnotationStorage:d=null,isEditing:c=!1}){this._stats?.time("Overall");const u=this._transport.getRenderingIntent(i,s,d,c),{renderingIntent:p,cacheKey:g}=u;this.#Gi=!1,this.#Vi(),r||=this._transport.getOptionalContentConfig(p);let m=this._intentStates.get(g);m||(m=Object.create(null),this._intentStates.set(g,m)),m.streamReaderCancelTimeout&&(clearTimeout(m.streamReaderCancelTimeout),m.streamReaderCancelTimeout=null);const f=!!(4&p);m.displayReadyCapability||(m.displayReadyCapability=Promise.withResolvers(),m.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(u));const b=t=>{m.renderTasks.delete(v),(this._maybeCleanupAfterRender||f)&&(this.#Gi=!0),this.#qi(!f),t?(v.capability.reject(t),this._abortOperatorList({intentState:m,reason:t instanceof Error?t:new Error(t)})):v.capability.resolve(),this._stats&&(this._stats.timeEnd("Rendering"),this._stats.timeEnd("Overall"),globalThis.Stats?.enabled&&globalThis.Stats.add(this.pageNumber,this._stats))},v=new gi({callback:b,params:{canvasContext:t,viewport:e,transform:n,background:a},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:o,operatorList:m.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!f,pdfBug:this._pdfBug,pageColors:h});(m.renderTasks||=new Set).add(v);const A=v.task;return Promise.all([m.displayReadyCapability.promise,r]).then((([t,e])=>{if(this.destroyed)b();else{if(this._stats?.time("Rendering"),!(e.renderingIntent&p))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");v.initializeGraphics({transparency:t,optionalContentConfig:e}),v.operatorListChanged()}})).catch(b),A}getOperatorList({intent:t="display",annotationMode:e=l.ENABLE,printAnnotationStorage:i=null,isEditing:s=!1}={}){const n=this._transport.getRenderingIntent(t,e,i,s,!0);let a,r=this._intentStates.get(n.cacheKey);return r||(r=Object.create(null),this._intentStates.set(n.cacheKey,r)),r.opListReadCapability||(a=Object.create(null),a.operatorListChanged=function(){r.operatorList.lastChunk&&(r.opListReadCapability.resolve(r.operatorList),r.renderTasks.delete(a))},r.opListReadCapability=Promise.withResolvers(),(r.renderTasks||=new Set).add(a),r.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(n)),r.opListReadCapability.promise}streamTextContent({includeMarkedContent:t=!1,disableNormalization:e=!1}={}){return this._transport.messageHandler.sendWithStream("GetTextContent",{pageIndex:this._pageIndex,includeMarkedContent:!0===t,disableNormalization:!0===e},{highWaterMark:100,size:t=>t.items.length})}getTextContent(t={}){if(this._transport._htmlForXfa)return this.getXfa().then((t=>Qe.textContent(t)));const e=this.streamTextContent(t);return new Promise((function(t,i){const s=e.getReader(),n={items:[],styles:Object.create(null),lang:null};!function e(){s.read().then((function({value:i,done:s}){s?t(n):(n.lang??=i.lang,Object.assign(n.styles,i.styles),n.items.push(...i.items),e())}),i)}()}))}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;const t=[];for(const e of this._intentStates.values())if(this._abortOperatorList({intentState:e,reason:new Error("Page was destroyed."),force:!0}),!e.opListReadCapability)for(const i of e.renderTasks)t.push(i.completed),i.cancel();return this.objs.clear(),this.#Gi=!1,this.#Vi(),Promise.all(t)}cleanup(t=!1){this.#Gi=!0;const e=this.#qi(!1);return t&&e&&(this._stats&&=new ot),e}#qi(t=!1){if(this.#Vi(),!this.#Gi||this.destroyed)return!1;if(t)return this.#Wi=setTimeout((()=>{this.#Wi=null,this.#qi(!1)}),5e3),!1;for(const{renderTasks:t,operatorList:e}of this._intentStates.values())if(t.size>0||!e.lastChunk)return!1;return this._intentStates.clear(),this.objs.clear(),this.#Gi=!1,!0}#Vi(){this.#Wi&&(clearTimeout(this.#Wi),this.#Wi=null)}_startRenderPage(t,e){const i=this._intentStates.get(e);i&&(this._stats?.timeEnd("Page Request"),i.displayReadyCapability?.resolve(t))}_renderPageChunk(t,e){for(let i=0,s=t.length;i{r.read().then((({value:t,done:e})=>{e?o.streamReader=null:this._transport.destroyed||(this._renderPageChunk(t,o),l())}),(t=>{if(o.streamReader=null,!this._transport.destroyed){if(o.operatorList){o.operatorList.lastChunk=!0;for(const t of o.renderTasks)t.operatorListChanged();this.#qi(!0)}if(o.displayReadyCapability)o.displayReadyCapability.reject(t);else{if(!o.opListReadCapability)throw t;o.opListReadCapability.reject(t)}}}))};l()}_abortOperatorList({intentState:t,reason:e,force:i=!1}){if(t.streamReader){if(t.streamReaderCancelTimeout&&(clearTimeout(t.streamReaderCancelTimeout),t.streamReaderCancelTimeout=null),!i){if(t.renderTasks.size>0)return;if(e instanceof it){let i=100;return e.extraDelay>0&&e.extraDelay<1e3&&(i+=e.extraDelay),void(t.streamReaderCancelTimeout=setTimeout((()=>{t.streamReaderCancelTimeout=null,this._abortOperatorList({intentState:t,reason:e,force:!0})}),i))}}if(t.streamReader.cancel(new D(e.message)).catch((()=>{})),t.streamReader=null,!this._transport.destroyed){for(const[e,i]of this._intentStates)if(i===t){this._intentStates.delete(e);break}this.cleanup()}}}get stats(){return this._stats}}class li{#Xi=new Set;#Ki=Promise.resolve();postMessage(t,e){const i={data:structuredClone(t,e?{transfer:e}:null)};this.#Ki.then((()=>{for(const t of this.#Xi)t.call(this,i)}))}addEventListener(t,e){this.#Xi.add(e)}removeEventListener(t,e){this.#Xi.delete(e)}terminate(){this.#Xi.clear()}}class hi{static#Yi=0;static#Qi=!1;static#Ji;static{n&&(this.#Qi=!0,fe.workerSrc||="./pdf.worker.mjs"),this._isSameOrigin=(t,e)=>{let i;try{if(i=new URL(t),!i.origin||"null"===i.origin)return!1}catch{return!1}const s=new URL(e,i);return i.origin===s.origin},this._createCDNWrapper=t=>{const e=`await import("${t}");`;return URL.createObjectURL(new Blob([e],{type:"text/javascript"}))}}constructor({name:t=null,port:e=null,verbosity:i=A()}={}){if(this.name=t,this.destroyed=!1,this.verbosity=i,this._readyCapability=Promise.withResolvers(),this._port=null,this._webWorker=null,this._messageHandler=null,e){if(hi.#Ji?.has(e))throw new Error("Cannot use more than one PDFWorker per port.");return(hi.#Ji||=new WeakMap).set(e,this),void this._initializeFromPort(e)}this._initialize()}get promise(){return n?Promise.all([Ut.promise,this._readyCapability.promise]):this._readyCapability.promise}#Zi(){this._readyCapability.resolve(),this._messageHandler.send("configure",{verbosity:this.verbosity})}get port(){return this._port}get messageHandler(){return this._messageHandler}_initializeFromPort(t){this._port=t,this._messageHandler=new ve("main","worker",t),this._messageHandler.on("ready",(function(){})),this.#Zi()}_initialize(){if(hi.#Qi||hi.#ts)return void this._setupFakeWorker();let{workerSrc:t}=hi;try{hi._isSameOrigin(window.location.href,t)||(t=hi._createCDNWrapper(new URL(t,window.location).href));const e=new Worker(t,{type:"module"}),i=new ve("main","worker",e),s=()=>{n.abort(),i.destroy(),e.terminate(),this.destroyed?this._readyCapability.reject(new Error("Worker was destroyed")):this._setupFakeWorker()},n=new AbortController;e.addEventListener("error",(()=>{this._webWorker||s()}),{signal:n.signal}),i.on("test",(t=>{n.abort(),!this.destroyed&&t?(this._messageHandler=i,this._port=e,this._webWorker=e,this.#Zi()):s()})),i.on("ready",(t=>{if(n.abort(),this.destroyed)s();else try{a()}catch{this._setupFakeWorker()}}));const a=()=>{const t=new Uint8Array;i.send("test",t,[t.buffer])};return void a()}catch{y("The worker has been disabled.")}this._setupFakeWorker()}_setupFakeWorker(){hi.#Qi||(w("Setting up fake worker."),hi.#Qi=!0),hi._setupFakeWorkerGlobal.then((t=>{if(this.destroyed)return void this._readyCapability.reject(new Error("Worker was destroyed"));const e=new li;this._port=e;const i="fake"+hi.#Yi++,s=new ve(i+"_worker",i,e);t.setup(s,e),this._messageHandler=new ve(i,i+"_worker",e),this.#Zi()})).catch((t=>{this._readyCapability.reject(new Error(`Setting up fake worker failed: "${t.message}".`))}))}destroy(){this.destroyed=!0,this._webWorker&&(this._webWorker.terminate(),this._webWorker=null),hi.#Ji?.delete(this._port),this._port=null,this._messageHandler&&(this._messageHandler.destroy(),this._messageHandler=null)}static fromPort(t){if(!t?.port)throw new Error("PDFWorker.fromPort - invalid method signature.");const e=this.#Ji?.get(t.port);if(e){if(e._pendingDestroy)throw new Error("PDFWorker.fromPort - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return e}return new hi(t)}static get workerSrc(){if(fe.workerSrc)return fe.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get#ts(){try{return globalThis.pdfjsWorker?.WorkerMessageHandler||null}catch{return null}}static get _setupFakeWorkerGlobal(){return E(this,"_setupFakeWorkerGlobal",(async()=>this.#ts?this.#ts:(await import(this.workerSrc)).WorkerMessageHandler)())}}class di{#es=new Map;#is=new Map;#ss=new Map;#ns=new Map;#as=null;constructor(t,e,i,s,n){this.messageHandler=t,this.loadingTask=e,this.commonObjs=new ui,this.fontLoader=new Bt({ownerDocument:s.ownerDocument,styleElement:s.styleElement}),this.loadingParams=s.loadingParams,this._params=s,this.canvasFactory=n.canvasFactory,this.filterFactory=n.filterFactory,this.cMapReaderFactory=n.cMapReaderFactory,this.standardFontDataFactory=n.standardFontDataFactory,this.destroyed=!1,this.destroyCapability=null,this._networkStream=i,this._fullReader=null,this._lastProgress=null,this.downloadInfoCapability=Promise.withResolvers(),this.setupMessageHandler()}#rs(t,e=null){const i=this.#es.get(t);if(i)return i;const s=this.messageHandler.sendWithPromise(t,e);return this.#es.set(t,s),s}get annotationStorage(){return E(this,"annotationStorage",new Nt)}getRenderingIntent(t,e=l.ENABLE,i=null,s=!1,n=!1){let a=2,r=Ft;switch(t){case"any":a=1;break;case"display":break;case"print":a=4;break;default:w(`getRenderingIntent - invalid intent: ${t}`)}const o=4&a&&i instanceof Ot?i:this.annotationStorage;switch(e){case l.DISABLE:a+=64;break;case l.ENABLE:break;case l.ENABLE_FORMS:a+=16;break;case l.ENABLE_STORAGE:a+=32,r=o.serializable;break;default:w(`getRenderingIntent - invalid annotationMode: ${e}`)}s&&(a+=128),n&&(a+=256);const{ids:h,hash:d}=o.modifiedIds;return{renderingIntent:a,cacheKey:[a,r.hash,d].join("_"),annotationStorageSerializable:r,modifiedIds:h}}destroy(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=Promise.withResolvers(),this.#as?.reject(new Error("Worker was destroyed during onPassword callback"));const t=[];for(const e of this.#is.values())t.push(e._destroy());this.#is.clear(),this.#ss.clear(),this.#ns.clear(),this.hasOwnProperty("annotationStorage")&&this.annotationStorage.resetModified();const e=this.messageHandler.sendWithPromise("Terminate",null);return t.push(e),Promise.all(t).then((()=>{this.commonObjs.clear(),this.fontLoader.clear(),this.#es.clear(),this.filterFactory.destroy(),Ye.cleanup(),this._networkStream?.cancelAllRequests(new D("Worker was terminated.")),this.messageHandler&&(this.messageHandler.destroy(),this.messageHandler=null),this.destroyCapability.resolve()}),this.destroyCapability.reject),this.destroyCapability.promise}setupMessageHandler(){const{messageHandler:t,loadingTask:e}=this;t.on("GetReader",((t,e)=>{x(this._networkStream,"GetReader - no `IPDFStream` instance available."),this._fullReader=this._networkStream.getFullReader(),this._fullReader.onProgress=t=>{this._lastProgress={loaded:t.loaded,total:t.total}},e.onPull=()=>{this._fullReader.read().then((function({value:t,done:i}){i?e.close():(x(t instanceof ArrayBuffer,"GetReader - expected an ArrayBuffer."),e.enqueue(new Uint8Array(t),1,[t]))})).catch((t=>{e.error(t)}))},e.onCancel=t=>{this._fullReader.cancel(t),e.ready.catch((t=>{if(!this.destroyed)throw t}))}})),t.on("ReaderHeadersReady",(t=>{const i=Promise.withResolvers(),s=this._fullReader;return s.headersReady.then((()=>{s.isStreamingSupported&&s.isRangeSupported||(this._lastProgress&&e.onProgress?.(this._lastProgress),s.onProgress=t=>{e.onProgress?.({loaded:t.loaded,total:t.total})}),i.resolve({isStreamingSupported:s.isStreamingSupported,isRangeSupported:s.isRangeSupported,contentLength:s.contentLength})}),i.reject),i.promise})),t.on("GetRangeReader",((t,e)=>{x(this._networkStream,"GetRangeReader - no `IPDFStream` instance available.");const i=this._networkStream.getRangeReader(t.begin,t.end);i?(e.onPull=()=>{i.read().then((function({value:t,done:i}){i?e.close():(x(t instanceof ArrayBuffer,"GetRangeReader - expected an ArrayBuffer."),e.enqueue(new Uint8Array(t),1,[t]))})).catch((t=>{e.error(t)}))},e.onCancel=t=>{i.cancel(t),e.ready.catch((t=>{if(!this.destroyed)throw t}))}):e.close()})),t.on("GetDoc",(({pdfInfo:t})=>{this._numPages=t.numPages,this._htmlForXfa=t.htmlForXfa,delete t.htmlForXfa,e._capability.resolve(new ri(t,this))})),t.on("DocException",(function(t){let i;switch(t.name){case"PasswordException":i=new T(t.message,t.code);break;case"InvalidPDFException":i=new k(t.message);break;case"MissingPDFException":i=new I(t.message);break;case"UnexpectedResponseException":i=new P(t.message,t.status);break;case"UnknownErrorException":i=new M(t.message,t.details);break;default:_("DocException - expected a valid Error.")}e._capability.reject(i)})),t.on("PasswordRequest",(t=>{if(this.#as=Promise.withResolvers(),e.onPassword){const i=t=>{t instanceof Error?this.#as.reject(t):this.#as.resolve({password:t})};try{e.onPassword(i,t.code)}catch(t){this.#as.reject(t)}}else this.#as.reject(new T(t.message,t.code));return this.#as.promise})),t.on("DataLoaded",(t=>{e.onProgress?.({loaded:t.length,total:t.length}),this.downloadInfoCapability.resolve(t)})),t.on("StartRenderPage",(t=>{this.destroyed||this.#is.get(t.pageIndex)._startRenderPage(t.transparency,t.cacheKey)})),t.on("commonobj",(([e,i,s])=>{if(this.destroyed)return null;if(this.commonObjs.has(e))return null;switch(i){case"Font":const{disableFontFace:n,fontExtraProperties:a,pdfBug:r}=this._params;if("error"in s){const t=s.error;w(`Error during font loading: ${t}`),this.commonObjs.resolve(e,t);break}const o=r&&globalThis.FontInspector?.enabled?(t,e)=>globalThis.FontInspector.fontAdded(t,e):null,l=new zt(s,{disableFontFace:n,inspectFont:o});this.fontLoader.bind(l).catch((()=>t.sendWithPromise("FontFallback",{id:e}))).finally((()=>{!a&&l.data&&(l.data=null),this.commonObjs.resolve(e,l)}));break;case"CopyLocalImage":const{imageRef:h}=s;x(h,"The imageRef must be defined.");for(const t of this.#is.values())for(const[,i]of t.objs)if(i?.ref===h)return i.dataLen?(this.commonObjs.resolve(e,structuredClone(i)),i.dataLen):null;break;case"FontPath":case"Image":case"Pattern":this.commonObjs.resolve(e,s);break;default:throw new Error(`Got unknown common object type ${i}`)}return null})),t.on("obj",(([t,e,i,s])=>{if(this.destroyed)return;const n=this.#is.get(e);if(!n.objs.has(t))if(0!==n._intentStates.size)switch(i){case"Image":n.objs.resolve(t,s),s?.dataLen>1e7&&(n._maybeCleanupAfterRender=!0);break;case"Pattern":n.objs.resolve(t,s);break;default:throw new Error(`Got unknown object type ${i}`)}else s?.bitmap?.close()})),t.on("DocProgress",(t=>{this.destroyed||e.onProgress?.({loaded:t.loaded,total:t.total})})),t.on("FetchBuiltInCMap",(t=>this.destroyed?Promise.reject(new Error("Worker was destroyed.")):this.cMapReaderFactory?this.cMapReaderFactory.fetch(t):Promise.reject(new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter.")))),t.on("FetchStandardFontData",(t=>this.destroyed?Promise.reject(new Error("Worker was destroyed.")):this.standardFontDataFactory?this.standardFontDataFactory.fetch(t):Promise.reject(new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter."))))}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){this.annotationStorage.size<=0&&w("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");const{map:t,transfer:e}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:t,filename:this._fullReader?.filename??null},e).finally((()=>{this.annotationStorage.resetModified()}))}getPage(t){if(!Number.isInteger(t)||t<=0||t>this._numPages)return Promise.reject(new Error("Invalid page request."));const e=t-1,i=this.#ss.get(e);if(i)return i;const s=this.messageHandler.sendWithPromise("GetPage",{pageIndex:e}).then((i=>{if(this.destroyed)throw new Error("Transport destroyed");i.refStr&&this.#ns.set(i.refStr,t);const s=new oi(e,i,this,this._params.pdfBug);return this.#is.set(e,s),s}));return this.#ss.set(e,s),s}getPageIndex(t){return si(t)?this.messageHandler.sendWithPromise("GetPageIndex",{num:t.num,gen:t.gen}):Promise.reject(new Error("Invalid pageIndex request."))}getAnnotations(t,e){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:t,intent:e})}getFieldObjects(){return this.#rs("GetFieldObjects")}hasJSActions(){return this.#rs("HasJSActions")}getCalculationOrderIds(){return this.messageHandler.sendWithPromise("GetCalculationOrderIds",null)}getDestinations(){return this.messageHandler.sendWithPromise("GetDestinations",null)}getDestination(t){return"string"!=typeof t?Promise.reject(new Error("Invalid destination request.")):this.messageHandler.sendWithPromise("GetDestination",{id:t})}getPageLabels(){return this.messageHandler.sendWithPromise("GetPageLabels",null)}getPageLayout(){return this.messageHandler.sendWithPromise("GetPageLayout",null)}getPageMode(){return this.messageHandler.sendWithPromise("GetPageMode",null)}getViewerPreferences(){return this.messageHandler.sendWithPromise("GetViewerPreferences",null)}getOpenAction(){return this.messageHandler.sendWithPromise("GetOpenAction",null)}getAttachments(){return this.messageHandler.sendWithPromise("GetAttachments",null)}getDocJSActions(){return this.#rs("GetDocJSActions")}getPageJSActions(t){return this.messageHandler.sendWithPromise("GetPageJSActions",{pageIndex:t})}getStructTree(t){return this.messageHandler.sendWithPromise("GetStructTree",{pageIndex:t})}getOutline(){return this.messageHandler.sendWithPromise("GetOutline",null)}getOptionalContentConfig(t){return this.#rs("GetOptionalContentConfig").then((e=>new _e(e,t)))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const t="GetMetadata",e=this.#es.get(t);if(e)return e;const i=this.messageHandler.sendWithPromise(t,null).then((t=>({info:t[0],metadata:t[1]?new Ae(t[1]):null,contentDispositionFilename:this._fullReader?.filename??null,contentLength:this._fullReader?.contentLength??null})));return this.#es.set(t,i),i}getMarkInfo(){return this.messageHandler.sendWithPromise("GetMarkInfo",null)}async startCleanup(t=!1){if(!this.destroyed){await this.messageHandler.sendWithPromise("Cleanup",null);for(const t of this.#is.values())if(!t.cleanup())throw new Error(`startCleanup: Page ${t.pageNumber} is currently rendering.`);this.commonObjs.clear(),t||this.fontLoader.clear(),this.#es.clear(),this.filterFactory.destroy(!0),Ye.cleanup()}}cachedPageNumber(t){if(!si(t))return null;const e=0===t.gen?`${t.num}R`:`${t.num}R${t.gen}`;return this.#ns.get(e)??null}}const ci=Symbol("INITIAL_DATA");class ui{#os=Object.create(null);#ls(t){return this.#os[t]||={...Promise.withResolvers(),data:ci}}get(t,e=null){if(e){const i=this.#ls(t);return i.promise.then((()=>e(i.data))),null}const i=this.#os[t];if(!i||i.data===ci)throw new Error(`Requesting object that isn't resolved yet ${t}.`);return i.data}has(t){const e=this.#os[t];return!!e&&e.data!==ci}resolve(t,e=null){const i=this.#ls(t);i.data=e,i.resolve()}clear(){for(const t in this.#os){const{data:e}=this.#os[t];e?.bitmap?.close()}this.#os=Object.create(null)}*[Symbol.iterator](){for(const t in this.#os){const{data:e}=this.#os[t];e!==ci&&(yield[t,e])}}}class pi{#hs=null;constructor(t){this.#hs=t,this.onContinue=null}get promise(){return this.#hs.capability.promise}cancel(t=0){this.#hs.cancel(null,t)}get separateAnnots(){const{separateAnnots:t}=this.#hs.operatorList;if(!t)return!1;const{annotationCanvasMap:e}=this.#hs;return t.form||t.canvas&&e?.size>0}}class gi{#ds=null;static#cs=new WeakSet;constructor({callback:t,params:e,objs:i,commonObjs:s,annotationCanvasMap:n,operatorList:a,pageIndex:r,canvasFactory:o,filterFactory:l,useRequestAnimationFrame:h=!1,pdfBug:d=!1,pageColors:c=null}){this.callback=t,this.params=e,this.objs=i,this.commonObjs=s,this.annotationCanvasMap=n,this.operatorListIdx=null,this.operatorList=a,this._pageIndex=r,this.canvasFactory=o,this.filterFactory=l,this._pdfBug=d,this.pageColors=c,this.running=!1,this.graphicsReadyCallback=null,this.graphicsReady=!1,this._useRequestAnimationFrame=!0===h&&"undefined"!=typeof window,this.cancelled=!1,this.capability=Promise.withResolvers(),this.task=new pi(this),this._cancelBound=this.cancel.bind(this),this._continueBound=this._continue.bind(this),this._scheduleNextBound=this._scheduleNext.bind(this),this._nextBound=this._next.bind(this),this._canvas=e.canvasContext.canvas}get completed(){return this.capability.promise.catch((function(){}))}initializeGraphics({transparency:t=!1,optionalContentConfig:e}){if(this.cancelled)return;if(this._canvas){if(gi.#cs.has(this._canvas))throw new Error("Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.");gi.#cs.add(this._canvas)}this._pdfBug&&globalThis.StepperManager?.enabled&&(this.stepper=globalThis.StepperManager.create(this._pageIndex),this.stepper.init(this.operatorList),this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint());const{canvasContext:i,viewport:s,transform:n,background:a}=this.params;this.gfx=new me(i,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:e},this.annotationCanvasMap,this.pageColors),this.gfx.beginDrawing({transform:n,viewport:s,transparency:t,background:a}),this.operatorListIdx=0,this.graphicsReady=!0,this.graphicsReadyCallback?.()}cancel(t=null,e=0){this.running=!1,this.cancelled=!0,this.gfx?.endDrawing(),this.#ds&&(window.cancelAnimationFrame(this.#ds),this.#ds=null),gi.#cs.delete(this._canvas),this.callback(t||new it(`Rendering cancelled, page ${this._pageIndex+1}`,e))}operatorListChanged(){this.graphicsReady?(this.stepper?.updateOperatorList(this.operatorList),this.running||this._continue()):this.graphicsReadyCallback||=this._continueBound}_continue(){this.running=!0,this.cancelled||(this.task.onContinue?this.task.onContinue(this._scheduleNextBound):this._scheduleNext())}_scheduleNext(){this._useRequestAnimationFrame?this.#ds=window.requestAnimationFrame((()=>{this.#ds=null,this._nextBound().catch(this._cancelBound)})):Promise.resolve().then(this._nextBound).catch(this._cancelBound)}async _next(){this.cancelled||(this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper),this.operatorListIdx===this.operatorList.argsArray.length&&(this.running=!1,this.operatorList.lastChunk&&(this.gfx.endDrawing(),gi.#cs.delete(this._canvas),this.callback())))}}const mi="4.7.76",fi="8b73b828b";function bi(t){return Math.floor(255*Math.max(0,Math.min(1,t))).toString(16).padStart(2,"0")}function vi(t){return Math.max(0,Math.min(255,255*t))}class Ai{static CMYK_G([t,e,i,s]){return["G",1-Math.min(1,.3*t+.59*i+.11*e+s)]}static G_CMYK([t]){return["CMYK",0,0,0,1-t]}static G_RGB([t]){return["RGB",t,t,t]}static G_rgb([t]){return[t=vi(t),t,t]}static G_HTML([t]){const e=bi(t);return`#${e}${e}${e}`}static RGB_G([t,e,i]){return["G",.3*t+.59*e+.11*i]}static RGB_rgb(t){return t.map(vi)}static RGB_HTML(t){return`#${t.map(bi).join("")}`}static T_HTML(){return"#00000000"}static T_rgb(){return[null]}static CMYK_RGB([t,e,i,s]){return["RGB",1-Math.min(1,t+s),1-Math.min(1,i+s),1-Math.min(1,e+s)]}static CMYK_rgb([t,e,i,s]){return[vi(1-Math.min(1,t+s)),vi(1-Math.min(1,i+s)),vi(1-Math.min(1,e+s))]}static CMYK_HTML(t){const e=this.CMYK_RGB(t).slice(1);return this.RGB_HTML(e)}static RGB_CMYK([t,e,i]){const s=1-t,n=1-e,a=1-i;return["CMYK",s,n,a,Math.min(s,n,a)]}}class yi{static setupStorage(t,e,i,s,n){const a=s.getValue(e,{value:null});switch(i.name){case"textarea":if(null!==a.value&&(t.textContent=a.value),"print"===n)break;t.addEventListener("input",(t=>{s.setValue(e,{value:t.target.value})}));break;case"input":if("radio"===i.attributes.type||"checkbox"===i.attributes.type){if(a.value===i.attributes.xfaOn?t.setAttribute("checked",!0):a.value===i.attributes.xfaOff&&t.removeAttribute("checked"),"print"===n)break;t.addEventListener("change",(t=>{s.setValue(e,{value:t.target.checked?t.target.getAttribute("xfaOn"):t.target.getAttribute("xfaOff")})}))}else{if(null!==a.value&&t.setAttribute("value",a.value),"print"===n)break;t.addEventListener("input",(t=>{s.setValue(e,{value:t.target.value})}))}break;case"select":if(null!==a.value){t.setAttribute("value",a.value);for(const t of i.children)t.attributes.value===a.value?t.attributes.selected=!0:t.attributes.hasOwnProperty("selected")&&delete t.attributes.selected}t.addEventListener("input",(t=>{const i=t.target.options,n=-1===i.selectedIndex?"":i[i.selectedIndex].value;s.setValue(e,{value:n})}))}}static setAttributes({html:t,element:e,storage:i=null,intent:s,linkService:n}){const{attributes:a}=e,r=t instanceof HTMLAnchorElement;"radio"===a.type&&(a.name=`${a.name}-${s}`);for(const[e,i]of Object.entries(a))if(null!=i)switch(e){case"class":i.length&&t.setAttribute(e,i.join(" "));break;case"dataId":break;case"id":t.setAttribute("data-element-id",i);break;case"style":Object.assign(t.style,i);break;case"textContent":t.textContent=i;break;default:(!r||"href"!==e&&"newWindow"!==e)&&t.setAttribute(e,i)}r&&n.addLinkAttributes(t,a.href,a.newWindow),i&&a.dataId&&this.setupStorage(t,a.dataId,e,i)}static render(t){const e=t.annotationStorage,i=t.linkService,s=t.xfaHtml,n=t.intent||"display",a=document.createElement(s.name);s.attributes&&this.setAttributes({html:a,element:s,intent:n,linkService:i});const r="richText"!==n,o=t.div;if(o.append(a),t.viewport){const e=`matrix(${t.viewport.transform.join(",")})`;o.style.transform=e}r&&o.setAttribute("class","xfaLayer xfaFont");const l=[];if(0===s.children.length){if(s.value){const t=document.createTextNode(s.value);a.append(t),r&&Qe.shouldBuildText(s.name)&&l.push(t)}return{textDivs:l}}const h=[[s,-1,a]];for(;h.length>0;){const[t,s,a]=h.at(-1);if(s+1===t.children.length){h.pop();continue}const o=t.children[++h.at(-1)[1]];if(null===o)continue;const{name:d}=o;if("#text"===d){const t=document.createTextNode(o.value);l.push(t),a.append(t);continue}const c=o?.attributes?.xmlns?document.createElementNS(o.attributes.xmlns,d):document.createElement(d);if(a.append(c),o.attributes&&this.setAttributes({html:c,element:o,storage:e,intent:n,linkService:i}),o.children?.length>0)h.push([o,-1,c]);else if(o.value){const t=document.createTextNode(o.value);r&&Qe.shouldBuildText(d)&&l.push(t),c.append(t)}}for(const t of o.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))t.setAttribute("readOnly",!0);return{textDivs:l}}static update(t){const e=`matrix(${t.viewport.transform.join(",")})`;t.div.style.transform=e,t.div.hidden=!1}}const wi=1e3,_i=new WeakSet;function xi(t){return{width:t[2]-t[0],height:t[3]-t[1]}}class Ci{static create(t){switch(t.data.annotationType){case 2:return new Si(t);case 1:return new Ti(t);case 20:switch(t.data.fieldType){case"Tx":return new ki(t);case"Btn":return t.data.radioButton?new Ri(t):t.data.checkBox?new Pi(t):new Di(t);case"Ch":return new Li(t);case"Sig":return new Ii(t)}return new Mi(t);case 16:return new Fi(t);case 3:return new Oi(t);case 4:return new Bi(t);case 5:return new zi(t);case 6:return new Hi(t);case 8:return new ji(t);case 14:return new $i(t);case 15:return new Wi(t);case 7:return new Ui(t);case 9:return new Gi(t);case 10:return new Vi(t);case 11:return new qi(t);case 12:return new Xi(t);case 13:return new Ki(t);case 17:return new Yi(t);default:return new Ei(t)}}}class Ei{#us=null;#ps=!1;#gs=null;constructor(t,{isRenderable:e=!1,ignoreBorder:i=!1,createQuadrilaterals:s=!1}={}){this.isRenderable=e,this.data=t.data,this.layer=t.layer,this.linkService=t.linkService,this.downloadManager=t.downloadManager,this.imageResourcesPath=t.imageResourcesPath,this.renderForms=t.renderForms,this.svgFactory=t.svgFactory,this.annotationStorage=t.annotationStorage,this.enableScripting=t.enableScripting,this.hasJSActions=t.hasJSActions,this._fieldObjects=t.fieldObjects,this.parent=t.parent,e&&(this.container=this._createContainer(i)),s&&this._createQuadrilaterals()}static _hasPopupData({titleObj:t,contentsObj:e,richText:i}){return!!(t?.str||e?.str||i?.str)}get _isEditable(){return this.data.isEditable}get hasPopupData(){return Ei._hasPopupData(this.data)}updateEdited(t){if(!this.container)return;this.#us||={rect:this.data.rect.slice(0)};const{rect:e}=t;e&&this.#ms(e),this.#gs?.popup.updateEdited(t)}resetEdited(){this.#us&&(this.#ms(this.#us.rect),this.#gs?.popup.resetEdited(),this.#us=null)}#ms(t){const{container:{style:e},data:{rect:i,rotation:s},parent:{viewport:{rawDims:{pageWidth:n,pageHeight:a,pageX:r,pageY:o}}}}=this;i?.splice(0,4,...t);const{width:l,height:h}=xi(t);e.left=100*(t[0]-r)/n+"%",e.top=100*(a-t[3]+o)/a+"%",0===s?(e.width=100*l/n+"%",e.height=100*h/a+"%"):this.setRotation(s)}_createContainer(t){const{data:e,parent:{page:i,viewport:s}}=this,n=document.createElement("section");n.setAttribute("data-annotation-id",e.id),this instanceof Mi||(n.tabIndex=wi);const{style:a}=n;if(a.zIndex=this.parent.zIndex++,e.popupRef&&n.setAttribute("aria-haspopup","dialog"),e.alternativeText&&(n.title=e.alternativeText),e.noRotate&&n.classList.add("norotate"),!e.rect||this instanceof Fi){const{rotation:t}=e;return e.hasOwnCanvas||0===t||this.setRotation(t,n),n}const{width:r,height:o}=xi(e.rect);if(!t&&e.borderStyle.width>0){a.borderWidth=`${e.borderStyle.width}px`;const t=e.borderStyle.horizontalCornerRadius,i=e.borderStyle.verticalCornerRadius;if(t>0||i>0){const e=`calc(${t}px * var(--scale-factor)) / calc(${i}px * var(--scale-factor))`;a.borderRadius=e}else if(this instanceof Ri){const t=`calc(${r}px * var(--scale-factor)) / calc(${o}px * var(--scale-factor))`;a.borderRadius=t}switch(e.borderStyle.style){case 1:a.borderStyle="solid";break;case 2:a.borderStyle="dashed";break;case 3:w("Unimplemented border style: beveled");break;case 4:w("Unimplemented border style: inset");break;case 5:a.borderBottomStyle="solid"}const s=e.borderColor||null;s?(this.#ps=!0,a.borderColor=z.makeHexColor(0|s[0],0|s[1],0|s[2])):a.borderWidth=0}const l=z.normalizeRect([e.rect[0],i.view[3]-e.rect[1]+i.view[1],e.rect[2],i.view[3]-e.rect[3]+i.view[1]]),{pageWidth:h,pageHeight:d,pageX:c,pageY:u}=s.rawDims;a.left=100*(l[0]-c)/h+"%",a.top=100*(l[1]-u)/d+"%";const{rotation:p}=e;return e.hasOwnCanvas||0===p?(a.width=100*r/h+"%",a.height=100*o/d+"%"):this.setRotation(p,n),n}setRotation(t,e=this.container){if(!this.data.rect)return;const{pageWidth:i,pageHeight:s}=this.parent.viewport.rawDims,{width:n,height:a}=xi(this.data.rect);let r,o;t%180==0?(r=100*n/i,o=100*a/s):(r=100*a/i,o=100*n/s),e.style.width=`${r}%`,e.style.height=`${o}%`,e.setAttribute("data-main-rotation",(360-t)%360)}get _commonActions(){const t=(t,e,i)=>{const s=i.detail[t],n=s[0],a=s.slice(1);i.target.style[e]=Ai[`${n}_HTML`](a),this.annotationStorage.setValue(this.data.id,{[e]:Ai[`${n}_rgb`](a)})};return E(this,"_commonActions",{display:t=>{const{display:e}=t.detail,i=e%2==1;this.container.style.visibility=i?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noView:i,noPrint:1===e||2===e})},print:t=>{this.annotationStorage.setValue(this.data.id,{noPrint:!t.detail.print})},hidden:t=>{const{hidden:e}=t.detail;this.container.style.visibility=e?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noPrint:e,noView:e})},focus:t=>{setTimeout((()=>t.target.focus({preventScroll:!1})),0)},userName:t=>{t.target.title=t.detail.userName},readonly:t=>{t.target.disabled=t.detail.readonly},required:t=>{this._setRequired(t.target,t.detail.required)},bgColor:e=>{t("bgColor","backgroundColor",e)},fillColor:e=>{t("fillColor","backgroundColor",e)},fgColor:e=>{t("fgColor","color",e)},textColor:e=>{t("textColor","color",e)},borderColor:e=>{t("borderColor","borderColor",e)},strokeColor:e=>{t("strokeColor","borderColor",e)},rotation:t=>{const e=t.detail.rotation;this.setRotation(e),this.annotationStorage.setValue(this.data.id,{rotation:e})}})}_dispatchEventFromSandbox(t,e){const i=this._commonActions;for(const s of Object.keys(e.detail))(t[s]||i[s])?.(e)}_setDefaultPropertiesFromJS(t){if(!this.enableScripting)return;const e=this.annotationStorage.getRawValue(this.data.id);if(!e)return;const i=this._commonActions;for(const[s,n]of Object.entries(e)){const a=i[s];a&&(a({detail:{[s]:n},target:t}),delete e[s])}}_createQuadrilaterals(){if(!this.container)return;const{quadPoints:t}=this.data;if(!t)return;const[e,i,s,n]=this.data.rect.map((t=>Math.fround(t)));if(8===t.length){const[a,r,o,l]=t.subarray(2,6);if(s===a&&n===r&&e===o&&i===l)return}const{style:a}=this.container;let r;if(this.#ps){const{borderColor:t,borderWidth:e}=a;a.borderWidth=0,r=["url('data:image/svg+xml;utf8,",'',``],this.container.classList.add("hasBorder")}const o=s-e,l=n-i,{svgFactory:h}=this,d=h.createElement("svg");d.classList.add("quadrilateralsContainer"),d.setAttribute("width",0),d.setAttribute("height",0);const c=h.createElement("defs");d.append(c);const u=h.createElement("clipPath"),p=`clippath_${this.data.id}`;u.setAttribute("id",p),u.setAttribute("clipPathUnits","objectBoundingBox"),c.append(u);for(let i=2,s=t.length;i`)}this.#ps&&(r.push("')"),a.backgroundImage=r.join("")),this.container.append(d),this.container.style.clipPath=`url(#${p})`}_createPopup(){const{container:t,data:e}=this;t.setAttribute("aria-haspopup","dialog");const i=this.#gs=new Fi({data:{color:e.color,titleObj:e.titleObj,modificationDate:e.modificationDate,contentsObj:e.contentsObj,richText:e.richText,parentRect:e.rect,borderStyle:0,id:`popup_${e.id}`,rotation:e.rotation},parent:this.parent,elements:[this]});this.parent.div.append(i.render())}render(){_("Abstract method `AnnotationElement.render` called")}_getElementsByName(t,e=null){const i=[];if(this._fieldObjects){const s=this._fieldObjects[t];if(s)for(const{page:t,id:n,exportValues:a}of s){if(-1===t)continue;if(n===e)continue;const s="string"==typeof a?a:null,r=document.querySelector(`[data-element-id="${n}"]`);!r||_i.has(r)?i.push({id:n,exportValue:s,domElement:r}):w(`_getElementsByName - element not allowed: ${n}`)}return i}for(const s of document.getElementsByName(t)){const{exportValue:t}=s,n=s.getAttribute("data-element-id");n!==e&&_i.has(s)&&i.push({id:n,exportValue:t,domElement:s})}return i}show(){this.container&&(this.container.hidden=!1),this.popup?.maybeShow()}hide(){this.container&&(this.container.hidden=!0),this.popup?.forceHide()}getElementsToTriggerPopup(){return this.container}addHighlightArea(){const t=this.getElementsToTriggerPopup();if(Array.isArray(t))for(const e of t)e.classList.add("highlightArea");else t.classList.add("highlightArea")}_editOnDoubleClick(){if(!this._isEditable)return;const{annotationEditorType:t,data:{id:e}}=this;this.container.addEventListener("dblclick",(()=>{this.linkService.eventBus?.dispatch("switchannotationeditormode",{source:this,mode:t,editId:e})}))}}class Si extends Ei{constructor(t,e=null){super(t,{isRenderable:!0,ignoreBorder:!!e?.ignoreBorder,createQuadrilaterals:!0}),this.isTooltipOnly=t.data.isTooltipOnly}render(){const{data:t,linkService:e}=this,i=document.createElement("a");i.setAttribute("data-element-id",t.id);let s=!1;return t.url?(e.addLinkAttributes(i,t.url,t.newWindow),s=!0):t.action?(this._bindNamedAction(i,t.action),s=!0):t.attachment?(this.#fs(i,t.attachment,t.attachmentDest),s=!0):t.setOCGState?(this.#bs(i,t.setOCGState),s=!0):t.dest?(this._bindLink(i,t.dest),s=!0):(t.actions&&(t.actions.Action||t.actions["Mouse Up"]||t.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions&&(this._bindJSAction(i,t),s=!0),t.resetForm?(this._bindResetFormAction(i,t.resetForm),s=!0):this.isTooltipOnly&&!s&&(this._bindLink(i,""),s=!0)),this.container.classList.add("linkAnnotation"),s&&this.container.append(i),this.container}#vs(){this.container.setAttribute("data-internal-link","")}_bindLink(t,e){t.href=this.linkService.getDestinationHash(e),t.onclick=()=>(e&&this.linkService.goToDestination(e),!1),(e||""===e)&&this.#vs()}_bindNamedAction(t,e){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeNamedAction(e),!1),this.#vs()}#fs(t,e,i=null){t.href=this.linkService.getAnchorUrl(""),e.description&&(t.title=e.description),t.onclick=()=>(this.downloadManager?.openOrDownloadData(e.content,e.filename,i),!1),this.#vs()}#bs(t,e){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeSetOCGState(e),!1),this.#vs()}_bindJSAction(t,e){t.href=this.linkService.getAnchorUrl("");const i=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(const s of Object.keys(e.actions)){const n=i.get(s);n&&(t[n]=()=>(this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e.id,name:s}}),!1))}t.onclick||(t.onclick=()=>!1),this.#vs()}_bindResetFormAction(t,e){const i=t.onclick;if(i||(t.href=this.linkService.getAnchorUrl("")),this.#vs(),!this._fieldObjects)return w('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.'),void(i||(t.onclick=()=>!1));t.onclick=()=>{i?.();const{fields:t,refs:s,include:n}=e,a=[];if(0!==t.length||0!==s.length){const e=new Set(s);for(const i of t){const t=this._fieldObjects[i]||[];for(const{id:i}of t)e.add(i)}for(const t of Object.values(this._fieldObjects))for(const i of t)e.has(i.id)===n&&a.push(i)}else for(const t of Object.values(this._fieldObjects))a.push(...t);const r=this.annotationStorage,o=[];for(const t of a){const{id:e}=t;switch(o.push(e),t.type){case"text":{const i=t.defaultValue||"";r.setValue(e,{value:i});break}case"checkbox":case"radiobutton":{const i=t.defaultValue===t.exportValues;r.setValue(e,{value:i});break}case"combobox":case"listbox":{const i=t.defaultValue||"";r.setValue(e,{value:i});break}default:continue}const i=document.querySelector(`[data-element-id="${e}"]`);i&&(_i.has(i)?i.dispatchEvent(new Event("resetform")):w(`_bindResetFormAction - element not allowed: ${e}`))}return this.enableScripting&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:o,name:"ResetForm"}}),!1}}}class Ti extends Ei{constructor(t){super(t,{isRenderable:!0})}render(){this.container.classList.add("textAnnotation");const t=document.createElement("img");return t.src=this.imageResourcesPath+"annotation-"+this.data.name.toLowerCase()+".svg",t.setAttribute("data-l10n-id","pdfjs-text-annotation-type"),t.setAttribute("data-l10n-args",JSON.stringify({type:this.data.name})),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.append(t),this.container}}class Mi extends Ei{render(){return this.container}showElementAndHideCanvas(t){this.data.hasOwnCanvas&&("CANVAS"===t.previousSibling?.nodeName&&(t.previousSibling.hidden=!0),t.hidden=!1)}_getKeyModifier(t){return O.platform.isMac?t.metaKey:t.ctrlKey}_setEventListener(t,e,i,s,n){i.includes("mouse")?t.addEventListener(i,(t=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:s,value:n(t),shift:t.shiftKey,modifier:this._getKeyModifier(t)}})})):t.addEventListener(i,(t=>{if("blur"===i){if(!e.focused||!t.relatedTarget)return;e.focused=!1}else if("focus"===i){if(e.focused)return;e.focused=!0}n&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:s,value:n(t)}})}))}_setEventListeners(t,e,i,s){for(const[n,a]of i)("Action"===a||this.data.actions?.[a])&&("Focus"!==a&&"Blur"!==a||(e||={focused:!1}),this._setEventListener(t,e,n,a,s),"Focus"!==a||this.data.actions?.Blur?"Blur"!==a||this.data.actions?.Focus||this._setEventListener(t,e,"focus","Focus",null):this._setEventListener(t,e,"blur","Blur",null))}_setBackgroundColor(t){const e=this.data.backgroundColor||null;t.style.backgroundColor=null===e?"transparent":z.makeHexColor(e[0],e[1],e[2])}_setTextStyle(t){const{fontColor:e}=this.data.defaultAppearanceData,i=this.data.defaultAppearanceData.fontSize||9,s=t.style;let n;const a=t=>Math.round(10*t)/10;if(this.data.multiLine){const t=Math.abs(this.data.rect[3]-this.data.rect[1]-2),e=t/(Math.round(t/(o*i))||1);n=Math.min(i,a(e/o))}else{const t=Math.abs(this.data.rect[3]-this.data.rect[1]-2);n=Math.min(i,a(t/o))}s.fontSize=`calc(${n}px * var(--scale-factor))`,s.color=z.makeHexColor(e[0],e[1],e[2]),null!==this.data.textAlignment&&(s.textAlign=["left","center","right"][this.data.textAlignment])}_setRequired(t,e){e?t.setAttribute("required",!0):t.removeAttribute("required"),t.setAttribute("aria-required",e)}}class ki extends Mi{constructor(t){super(t,{isRenderable:t.renderForms||t.data.hasOwnCanvas||!t.data.hasAppearance&&!!t.data.fieldValue})}setPropertyOnSiblings(t,e,i,s){const n=this.annotationStorage;for(const a of this._getElementsByName(t.name,t.id))a.domElement&&(a.domElement[e]=i),n.setValue(a.id,{[s]:i})}render(){const t=this.annotationStorage,e=this.data.id;this.container.classList.add("textWidgetAnnotation");let i=null;if(this.renderForms){const s=t.getValue(e,{value:this.data.fieldValue});let n=s.value||"";const a=t.getValue(e,{charLimit:this.data.maxLen}).charLimit;a&&n.length>a&&(n=n.slice(0,a));let r=s.formattedValue||this.data.textContent?.join("\n")||null;r&&this.data.comb&&(r=r.replaceAll(/\s+/g,""));const o={userValue:n,formattedValue:r,lastCommittedValue:null,commitKey:1,focused:!1};this.data.multiLine?(i=document.createElement("textarea"),i.textContent=r??n,this.data.doNotScroll&&(i.style.overflowY="hidden")):(i=document.createElement("input"),i.type="text",i.setAttribute("value",r??n),this.data.doNotScroll&&(i.style.overflowX="hidden")),this.data.hasOwnCanvas&&(i.hidden=!0),_i.add(i),i.setAttribute("data-element-id",e),i.disabled=this.data.readOnly,i.name=this.data.fieldName,i.tabIndex=wi,this._setRequired(i,this.data.required),a&&(i.maxLength=a),i.addEventListener("input",(s=>{t.setValue(e,{value:s.target.value}),this.setPropertyOnSiblings(i,"value",s.target.value,"value"),o.formattedValue=null})),i.addEventListener("resetform",(t=>{const e=this.data.defaultFieldValue??"";i.value=o.userValue=e,o.formattedValue=null}));let l=t=>{const{formattedValue:e}=o;null!=e&&(t.target.value=e),t.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){i.addEventListener("focus",(t=>{if(o.focused)return;const{target:e}=t;o.userValue&&(e.value=o.userValue),o.lastCommittedValue=e.value,o.commitKey=1,this.data.actions?.Focus||(o.focused=!0)})),i.addEventListener("updatefromsandbox",(i=>{this.showElementAndHideCanvas(i.target);const s={value(i){o.userValue=i.detail.value??"",t.setValue(e,{value:o.userValue.toString()}),i.target.value=o.userValue},formattedValue(i){const{formattedValue:s}=i.detail;o.formattedValue=s,null!=s&&i.target!==document.activeElement&&(i.target.value=s),t.setValue(e,{formattedValue:s})},selRange(t){t.target.setSelectionRange(...t.detail.selRange)},charLimit:i=>{const{charLimit:s}=i.detail,{target:n}=i;if(0===s)return void n.removeAttribute("maxLength");n.setAttribute("maxLength",s);let a=o.userValue;!a||a.length<=s||(a=a.slice(0,s),n.value=o.userValue=a,t.setValue(e,{value:a}),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:a,willCommit:!0,commitKey:1,selStart:n.selectionStart,selEnd:n.selectionEnd}}))}};this._dispatchEventFromSandbox(s,i)})),i.addEventListener("keydown",(t=>{o.commitKey=1;let i=-1;if("Escape"===t.key?i=0:"Enter"!==t.key||this.data.multiLine?"Tab"===t.key&&(o.commitKey=3):i=2,-1===i)return;const{value:s}=t.target;o.lastCommittedValue!==s&&(o.lastCommittedValue=s,o.userValue=s,this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:s,willCommit:!0,commitKey:i,selStart:t.target.selectionStart,selEnd:t.target.selectionEnd}}))}));const s=l;l=null,i.addEventListener("blur",(t=>{if(!o.focused||!t.relatedTarget)return;this.data.actions?.Blur||(o.focused=!1);const{value:i}=t.target;o.userValue=i,o.lastCommittedValue!==i&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:i,willCommit:!0,commitKey:o.commitKey,selStart:t.target.selectionStart,selEnd:t.target.selectionEnd}}),s(t)})),this.data.actions?.Keystroke&&i.addEventListener("beforeinput",(t=>{o.lastCommittedValue=null;const{data:i,target:s}=t,{value:n,selectionStart:a,selectionEnd:r}=s;let l=a,h=r;switch(t.inputType){case"deleteWordBackward":{const t=n.substring(0,a).match(/\w*[^\w]*$/);t&&(l-=t[0].length);break}case"deleteWordForward":{const t=n.substring(a).match(/^[^\w]*\w*/);t&&(h+=t[0].length);break}case"deleteContentBackward":a===r&&(l-=1);break;case"deleteContentForward":a===r&&(h+=1)}t.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:n,change:i||"",willCommit:!1,selStart:l,selEnd:h}})})),this._setEventListeners(i,o,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(t=>t.target.value))}if(l&&i.addEventListener("blur",l),this.data.comb){const t=(this.data.rect[2]-this.data.rect[0])/a;i.classList.add("comb"),i.style.letterSpacing=`calc(${t}px * var(--scale-factor) - 1ch)`}}else i=document.createElement("div"),i.textContent=this.data.fieldValue,i.style.verticalAlign="middle",i.style.display="table-cell",this.data.hasOwnCanvas&&(i.hidden=!0);return this._setTextStyle(i),this._setBackgroundColor(i),this._setDefaultPropertiesFromJS(i),this.container.append(i),this.container}}class Ii extends Mi{constructor(t){super(t,{isRenderable:!!t.data.hasOwnCanvas})}}class Pi extends Mi{constructor(t){super(t,{isRenderable:t.renderForms})}render(){const t=this.annotationStorage,e=this.data,i=e.id;let s=t.getValue(i,{value:e.exportValue===e.fieldValue}).value;"string"==typeof s&&(s="Off"!==s,t.setValue(i,{value:s})),this.container.classList.add("buttonWidgetAnnotation","checkBox");const n=document.createElement("input");return _i.add(n),n.setAttribute("data-element-id",i),n.disabled=e.readOnly,this._setRequired(n,this.data.required),n.type="checkbox",n.name=e.fieldName,s&&n.setAttribute("checked",!0),n.setAttribute("exportValue",e.exportValue),n.tabIndex=wi,n.addEventListener("change",(s=>{const{name:n,checked:a}=s.target;for(const s of this._getElementsByName(n,i)){const i=a&&s.exportValue===e.exportValue;s.domElement&&(s.domElement.checked=i),t.setValue(s.id,{value:i})}t.setValue(i,{value:a})})),n.addEventListener("resetform",(t=>{const i=e.defaultFieldValue||"Off";t.target.checked=i===e.exportValue})),this.enableScripting&&this.hasJSActions&&(n.addEventListener("updatefromsandbox",(e=>{const s={value(e){e.target.checked="Off"!==e.detail.value,t.setValue(i,{value:e.target.checked})}};this._dispatchEventFromSandbox(s,e)})),this._setEventListeners(n,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(t=>t.target.checked))),this._setBackgroundColor(n),this._setDefaultPropertiesFromJS(n),this.container.append(n),this.container}}class Ri extends Mi{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("buttonWidgetAnnotation","radioButton");const t=this.annotationStorage,e=this.data,i=e.id;let s=t.getValue(i,{value:e.fieldValue===e.buttonValue}).value;if("string"==typeof s&&(s=s!==e.buttonValue,t.setValue(i,{value:s})),s)for(const s of this._getElementsByName(e.fieldName,i))t.setValue(s.id,{value:!1});const n=document.createElement("input");if(_i.add(n),n.setAttribute("data-element-id",i),n.disabled=e.readOnly,this._setRequired(n,this.data.required),n.type="radio",n.name=e.fieldName,s&&n.setAttribute("checked",!0),n.tabIndex=wi,n.addEventListener("change",(e=>{const{name:s,checked:n}=e.target;for(const e of this._getElementsByName(s,i))t.setValue(e.id,{value:!1});t.setValue(i,{value:n})})),n.addEventListener("resetform",(t=>{const i=e.defaultFieldValue;t.target.checked=null!=i&&i===e.buttonValue})),this.enableScripting&&this.hasJSActions){const s=e.buttonValue;n.addEventListener("updatefromsandbox",(e=>{const n={value:e=>{const n=s===e.detail.value;for(const s of this._getElementsByName(e.target.name)){const e=n&&s.id===i;s.domElement&&(s.domElement.checked=e),t.setValue(s.id,{value:e})}}};this._dispatchEventFromSandbox(n,e)})),this._setEventListeners(n,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(t=>t.target.checked))}return this._setBackgroundColor(n),this._setDefaultPropertiesFromJS(n),this.container.append(n),this.container}}class Di extends Si{constructor(t){super(t,{ignoreBorder:t.data.hasAppearance})}render(){const t=super.render();t.classList.add("buttonWidgetAnnotation","pushButton");const e=t.lastChild;return this.enableScripting&&this.hasJSActions&&e&&(this._setDefaultPropertiesFromJS(e),e.addEventListener("updatefromsandbox",(t=>{this._dispatchEventFromSandbox({},t)}))),t}}class Li extends Mi{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("choiceWidgetAnnotation");const t=this.annotationStorage,e=this.data.id,i=t.getValue(e,{value:this.data.fieldValue}),s=document.createElement("select");_i.add(s),s.setAttribute("data-element-id",e),s.disabled=this.data.readOnly,this._setRequired(s,this.data.required),s.name=this.data.fieldName,s.tabIndex=wi;let n=this.data.combo&&this.data.options.length>0;this.data.combo||(s.size=this.data.options.length,this.data.multiSelect&&(s.multiple=!0)),s.addEventListener("resetform",(t=>{const e=this.data.defaultFieldValue;for(const t of s.options)t.selected=t.value===e}));for(const t of this.data.options){const e=document.createElement("option");e.textContent=t.displayValue,e.value=t.exportValue,i.value.includes(t.exportValue)&&(e.setAttribute("selected",!0),n=!1),s.append(e)}let a=null;if(n){const t=document.createElement("option");t.value=" ",t.setAttribute("hidden",!0),t.setAttribute("selected",!0),s.prepend(t),a=()=>{t.remove(),s.removeEventListener("input",a),a=null},s.addEventListener("input",a)}const r=t=>{const e=t?"value":"textContent",{options:i,multiple:n}=s;return n?Array.prototype.filter.call(i,(t=>t.selected)).map((t=>t[e])):-1===i.selectedIndex?null:i[i.selectedIndex][e]};let o=r(!1);const l=t=>{const e=t.target.options;return Array.prototype.map.call(e,(t=>({displayValue:t.textContent,exportValue:t.value})))};return this.enableScripting&&this.hasJSActions?(s.addEventListener("updatefromsandbox",(i=>{const n={value(i){a?.();const n=i.detail.value,l=new Set(Array.isArray(n)?n:[n]);for(const t of s.options)t.selected=l.has(t.value);t.setValue(e,{value:r(!0)}),o=r(!1)},multipleSelection(t){s.multiple=!0},remove(i){const n=s.options,a=i.detail.remove;n[a].selected=!1,s.remove(a),n.length>0&&-1===Array.prototype.findIndex.call(n,(t=>t.selected))&&(n[0].selected=!0),t.setValue(e,{value:r(!0),items:l(i)}),o=r(!1)},clear(i){for(;0!==s.length;)s.remove(0);t.setValue(e,{value:null,items:[]}),o=r(!1)},insert(i){const{index:n,displayValue:a,exportValue:h}=i.detail.insert,d=s.children[n],c=document.createElement("option");c.textContent=a,c.value=h,d?d.before(c):s.append(c),t.setValue(e,{value:r(!0),items:l(i)}),o=r(!1)},items(i){const{items:n}=i.detail;for(;0!==s.length;)s.remove(0);for(const t of n){const{displayValue:e,exportValue:i}=t,n=document.createElement("option");n.textContent=e,n.value=i,s.append(n)}s.options.length>0&&(s.options[0].selected=!0),t.setValue(e,{value:r(!0),items:l(i)}),o=r(!1)},indices(i){const s=new Set(i.detail.indices);for(const t of i.target.options)t.selected=s.has(t.index);t.setValue(e,{value:r(!0)}),o=r(!1)},editable(t){t.target.disabled=!t.detail.editable}};this._dispatchEventFromSandbox(n,i)})),s.addEventListener("input",(i=>{const s=r(!0),n=r(!1);t.setValue(e,{value:s}),i.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:o,change:n,changeEx:s,willCommit:!1,commitKey:1,keyDown:!1}})})),this._setEventListeners(s,null,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"],["input","Action"],["input","Validate"]],(t=>t.target.value))):s.addEventListener("input",(function(i){t.setValue(e,{value:r(!0)})})),this.data.combo&&this._setTextStyle(s),this._setBackgroundColor(s),this._setDefaultPropertiesFromJS(s),this.container.append(s),this.container}}class Fi extends Ei{constructor(t){const{data:e,elements:i}=t;super(t,{isRenderable:Ei._hasPopupData(e)}),this.elements=i,this.popup=null}render(){this.container.classList.add("popupAnnotation");const t=this.popup=new Ni({container:this.container,color:this.data.color,titleObj:this.data.titleObj,modificationDate:this.data.modificationDate,contentsObj:this.data.contentsObj,richText:this.data.richText,rect:this.data.rect,parentRect:this.data.parentRect||null,parent:this.parent,elements:this.elements,open:this.data.open}),e=[];for(const i of this.elements)i.popup=t,e.push(i.data.id),i.addHighlightArea();return this.container.setAttribute("aria-controls",e.map((t=>`${$}${t}`)).join(",")),this.container}}class Ni{#As=this.#ys.bind(this);#ws=this.#_s.bind(this);#xs=this.#Cs.bind(this);#Es=this.#Ss.bind(this);#Ts=null;#ut=null;#Ms=null;#ks=null;#Is=null;#Ps=null;#Rs=null;#Ds=!1;#Ls=null;#S=null;#Fs=null;#Ns=null;#Os=null;#us=null;#Bs=!1;constructor({container:t,color:e,elements:i,titleObj:s,modificationDate:n,contentsObj:a,richText:r,parent:o,rect:l,parentRect:h,open:d}){this.#ut=t,this.#Os=s,this.#Ms=a,this.#Ns=r,this.#Ps=o,this.#Ts=e,this.#Fs=l,this.#Rs=h,this.#Is=i,this.#ks=ut.toDateObject(n),this.trigger=i.flatMap((t=>t.getElementsToTriggerPopup()));for(const t of this.trigger)t.addEventListener("click",this.#Es),t.addEventListener("mouseenter",this.#xs),t.addEventListener("mouseleave",this.#ws),t.classList.add("popupTriggerArea");for(const t of i)t.container?.addEventListener("keydown",this.#As);this.#ut.hidden=!0,d&&this.#Ss()}render(){if(this.#Ls)return;const t=this.#Ls=document.createElement("div");if(t.className="popup",this.#Ts){const e=t.style.outlineColor=z.makeHexColor(...this.#Ts);if(CSS.supports("background-color","color-mix(in srgb, red 30%, white)"))t.style.backgroundColor=`color-mix(in srgb, ${e} 30%, white)`;else{const e=.7;t.style.backgroundColor=z.makeHexColor(...this.#Ts.map((t=>Math.floor(e*(255-t)+t))))}}const e=document.createElement("span");e.className="header";const i=document.createElement("h1");if(e.append(i),({dir:i.dir,str:i.textContent}=this.#Os),t.append(e),this.#ks){const t=document.createElement("span");t.classList.add("popupDate"),t.setAttribute("data-l10n-id","pdfjs-annotation-date-time-string"),t.setAttribute("data-l10n-args",JSON.stringify({dateObj:this.#ks.valueOf()})),e.append(t)}const s=this.#zs;if(s)yi.render({xfaHtml:s,intent:"richText",div:t}),t.lastChild.classList.add("richText","popupContent");else{const e=this._formatContents(this.#Ms);t.append(e)}this.#ut.append(t)}get#zs(){const t=this.#Ns,e=this.#Ms;return!t?.str||e?.str&&e.str!==t.str?null:this.#Ns.html||null}get#Hs(){return this.#zs?.attributes?.style?.fontSize||0}get#js(){return this.#zs?.attributes?.style?.color||null}#Us(t){const e=[],i={str:t,html:{name:"div",attributes:{dir:"auto"},children:[{name:"p",children:e}]}},s={style:{color:this.#js,fontSize:this.#Hs?`calc(${this.#Hs}px * var(--scale-factor))`:""}};for(const i of t.split("\n"))e.push({name:"span",value:i,attributes:s});return i}_formatContents({str:t,dir:e}){const i=document.createElement("p");i.classList.add("popupContent"),i.dir=e;const s=t.split(/(?:\r\n?|\n)/);for(let t=0,e=s.length;t{"Enter"===t.key&&(s?t.metaKey:t.ctrlKey)&&this.#Ys()})),!e.popupRef&&this.hasPopupData?this._createPopup():i.classList.add("popupTriggerArea"),t.append(i),t}getElementsToTriggerPopup(){return this.#Ks}addHighlightArea(){this.container.classList.add("highlightArea")}#Ys(){this.downloadManager?.openOrDownloadData(this.content,this.filename)}}class Qi{#Qs=null;#Js=null;#Zs=new Map;#tn=null;constructor({div:t,accessibilityManager:e,annotationCanvasMap:i,annotationEditorUIManager:s,page:n,viewport:a,structTreeLayer:r}){this.div=t,this.#Qs=e,this.#Js=i,this.#tn=r||null,this.page=n,this.viewport=a,this.zIndex=0,this._annotationEditorUIManager=s}hasEditableAnnotations(){return this.#Zs.size>0}async#en(t,e){const i=t.firstChild||t,s=i.id=`${$}${e}`,n=await(this.#tn?.getAriaAttributes(s));if(n)for(const[t,e]of n)i.setAttribute(t,e);this.div.append(t),this.#Qs?.moveElementInDOM(this.div,t,i,!1)}async render(t){const{annotations:e}=t,i=this.div;bt(i,this.viewport);const s=new Map,n={data:null,layer:i,linkService:t.linkService,downloadManager:t.downloadManager,imageResourcesPath:t.imageResourcesPath||"",renderForms:!1!==t.renderForms,svgFactory:new tt,annotationStorage:t.annotationStorage||new Nt,enableScripting:!0===t.enableScripting,hasJSActions:t.hasJSActions,fieldObjects:t.fieldObjects,parent:this,elements:null};for(const t of e){if(t.noHTML)continue;const e=16===t.annotationType;if(e){const e=s.get(t.id);if(!e)continue;n.elements=e}else{const{width:e,height:i}=xi(t.rect);if(e<=0||i<=0)continue}n.data=t;const i=Ci.create(n);if(!i.isRenderable)continue;if(!e&&t.popupRef){const e=s.get(t.popupRef);e?e.push(i):s.set(t.popupRef,[i])}const a=i.render();t.hidden&&(a.style.visibility="hidden"),await this.#en(a,t.id),i._isEditable&&(this.#Zs.set(i.data.id,i),this._annotationEditorUIManager?.renderAnnotationElement(i))}this.#in()}update({viewport:t}){const e=this.div;this.viewport=t,bt(e,{rotation:t.rotation}),this.#in(),e.hidden=!1}#in(){if(!this.#Js)return;const t=this.div;for(const[e,i]of this.#Js){const s=t.querySelector(`[data-annotation-id="${e}"]`);if(!s)continue;i.className="annotationContent";const{firstChild:n}=s;n?"CANVAS"===n.nodeName?n.replaceWith(i):n.classList.contains("annotationContent")?n.after(i):n.before(i):s.append(i)}this.#Js.clear()}getEditableAnnotations(){return Array.from(this.#Zs.values())}getEditableAnnotation(t){return this.#Zs.get(t)}}const Ji=/\r\n?|\n/g;class Zi extends kt{#Ts;#sn="";#nn=`${this.id}-editor`;#an=null;#Hs;static _freeTextDefaultContent="";static _internalPadding=0;static _defaultColor=null;static _defaultFontSize=10;static get _keyboardManager(){const t=Zi.prototype,e=t=>t.isEmpty(),i=Tt.TRANSLATE_SMALL,s=Tt.TRANSLATE_BIG;return E(this,"_keyboardManager",new Et([[["ctrl+s","mac+meta+s","ctrl+p","mac+meta+p"],t.commitOrRemove,{bubbles:!0}],[["ctrl+Enter","mac+meta+Enter","Escape","mac+Escape"],t.commitOrRemove],[["ArrowLeft","mac+ArrowLeft"],t._translateEmpty,{args:[-i,0],checker:e}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t._translateEmpty,{args:[-s,0],checker:e}],[["ArrowRight","mac+ArrowRight"],t._translateEmpty,{args:[i,0],checker:e}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t._translateEmpty,{args:[s,0],checker:e}],[["ArrowUp","mac+ArrowUp"],t._translateEmpty,{args:[0,-i],checker:e}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t._translateEmpty,{args:[0,-s],checker:e}],[["ArrowDown","mac+ArrowDown"],t._translateEmpty,{args:[0,i],checker:e}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t._translateEmpty,{args:[0,s],checker:e}]]))}static _type="freetext";static _editorType=h.FREETEXT;constructor(t){super({...t,name:"freeTextEditor"}),this.#Ts=t.color||Zi._defaultColor||kt._defaultLineColor,this.#Hs=t.fontSize||Zi._defaultFontSize}static initialize(t,e){kt.initialize(t,e,{strings:["pdfjs-free-text-default-content"]});const i=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(i.getPropertyValue("--freetext-padding"))}static updateDefaultParams(t,e){switch(t){case d.FREETEXT_SIZE:Zi._defaultFontSize=e;break;case d.FREETEXT_COLOR:Zi._defaultColor=e}}updateParams(t,e){switch(t){case d.FREETEXT_SIZE:this.#rn(e);break;case d.FREETEXT_COLOR:this.#on(e)}}static get defaultPropertiesToUpdate(){return[[d.FREETEXT_SIZE,Zi._defaultFontSize],[d.FREETEXT_COLOR,Zi._defaultColor||kt._defaultLineColor]]}get propertiesToUpdate(){return[[d.FREETEXT_SIZE,this.#Hs],[d.FREETEXT_COLOR,this.#Ts]]}#rn(t){const e=t=>{this.editorDiv.style.fontSize=`calc(${t}px * var(--scale-factor))`,this.translate(0,-(t-this.#Hs)*this.parentScale),this.#Hs=t,this.#ln()},i=this.#Hs;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:d.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})}#on(t){const e=t=>{this.#Ts=this.editorDiv.style.color=t},i=this.#Ts;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:d.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})}_translateEmpty(t,e){this._uiManager.translateSelectedEditors(t,e,!0)}getInitialTranslation(){const t=this.parentScale;return[-Zi._internalPadding*t,-(Zi._internalPadding+this.#Hs)*t]}rebuild(){this.parent&&(super.rebuild(),null!==this.div&&(this.isAttachedToDOM||this.parent.add(this)))}enableEditMode(){if(this.isInEditMode())return;this.parent.setEditingState(!1),this.parent.updateToolbar(h.FREETEXT),super.enableEditMode(),this.overlayDiv.classList.remove("enabled"),this.editorDiv.contentEditable=!0,this._isDraggable=!1,this.div.removeAttribute("aria-activedescendant"),this.#an=new AbortController;const t=this._uiManager.combinedSignal(this.#an);this.editorDiv.addEventListener("keydown",this.editorDivKeydown.bind(this),{signal:t}),this.editorDiv.addEventListener("focus",this.editorDivFocus.bind(this),{signal:t}),this.editorDiv.addEventListener("blur",this.editorDivBlur.bind(this),{signal:t}),this.editorDiv.addEventListener("input",this.editorDivInput.bind(this),{signal:t}),this.editorDiv.addEventListener("paste",this.editorDivPaste.bind(this),{signal:t})}disableEditMode(){this.isInEditMode()&&(this.parent.setEditingState(!0),super.disableEditMode(),this.overlayDiv.classList.add("enabled"),this.editorDiv.contentEditable=!1,this.div.setAttribute("aria-activedescendant",this.#nn),this._isDraggable=!0,this.#an?.abort(),this.#an=null,this.div.focus({preventScroll:!0}),this.isEditing=!1,this.parent.div.classList.add("freetextEditing"))}focusin(t){this._focusEventsAllowed&&(super.focusin(t),t.target!==this.editorDiv&&this.editorDiv.focus())}onceAdded(){this.width||(this.enableEditMode(),this.editorDiv.focus(),this._initialOptions?.isCentered&&this.center(),this._initialOptions=null)}isEmpty(){return!this.editorDiv||""===this.editorDiv.innerText.trim()}remove(){this.isEditing=!1,this.parent&&(this.parent.setEditingState(!0),this.parent.div.classList.add("freetextEditing")),super.remove()}#hn(){const t=[];this.editorDiv.normalize();let e=null;for(const i of this.editorDiv.childNodes)e?.nodeType===Node.TEXT_NODE&&"BR"===i.nodeName||(t.push(Zi.#dn(i)),e=i);return t.join("\n")}#ln(){const[t,e]=this.parentDimensions;let i;if(this.isAttachedToDOM)i=this.div.getBoundingClientRect();else{const{currentLayer:t,div:e}=this,s=e.style.display,n=e.classList.contains("hidden");e.classList.remove("hidden"),e.style.display="hidden",t.div.append(this.div),i=e.getBoundingClientRect(),e.remove(),e.style.display=s,e.classList.toggle("hidden",n)}this.rotation%180==this.parentRotation%180?(this.width=i.width/t,this.height=i.height/e):(this.width=i.height/t,this.height=i.width/e),this.fixAndSetPosition()}commit(){if(!this.isInEditMode())return;super.commit(),this.disableEditMode();const t=this.#sn,e=this.#sn=this.#hn().trimEnd();if(t===e)return;const i=t=>{this.#sn=t,t?(this.#cn(),this._uiManager.rebuild(this),this.#ln()):this.remove()};this.addCommands({cmd:()=>{i(e)},undo:()=>{i(t)},mustExec:!1}),this.#ln()}shouldGetKeyboardEvents(){return this.isInEditMode()}enterInEditMode(){this.enableEditMode(),this.editorDiv.focus()}dblclick(t){this.enterInEditMode()}keydown(t){t.target===this.div&&"Enter"===t.key&&(this.enterInEditMode(),t.preventDefault())}editorDivKeydown(t){Zi._keyboardManager.exec(this,t)}editorDivFocus(t){this.isEditing=!0}editorDivBlur(t){this.isEditing=!1}editorDivInput(t){this.parent.div.classList.toggle("freetextEditing",this.isEmpty())}disableEditing(){this.editorDiv.setAttribute("role","comment"),this.editorDiv.removeAttribute("aria-multiline")}enableEditing(){this.editorDiv.setAttribute("role","textbox"),this.editorDiv.setAttribute("aria-multiline",!0)}render(){if(this.div)return this.div;let t,e;this.width&&(t=this.x,e=this.y),super.render(),this.editorDiv=document.createElement("div"),this.editorDiv.className="internal",this.editorDiv.setAttribute("id",this.#nn),this.editorDiv.setAttribute("data-l10n-id","pdfjs-free-text"),this.enableEditing(),kt._l10nPromise.get("pdfjs-free-text-default-content").then((t=>this.editorDiv?.setAttribute("default-content",t))),this.editorDiv.contentEditable=!0;const{style:i}=this.editorDiv;if(i.fontSize=`calc(${this.#Hs}px * var(--scale-factor))`,i.color=this.#Ts,this.div.append(this.editorDiv),this.overlayDiv=document.createElement("div"),this.overlayDiv.classList.add("overlay","enabled"),this.div.append(this.overlayDiv),wt(this,this.div,["dblclick","keydown"]),this.width){const[i,s]=this.parentDimensions;if(this.annotationElementId){const{position:n}=this._initialData;let[a,r]=this.getInitialTranslation();[a,r]=this.pageTranslationToScreen(a,r);const[o,l]=this.pageDimensions,[h,d]=this.pageTranslation;let c,u;switch(this.rotation){case 0:c=t+(n[0]-h)/o,u=e+this.height-(n[1]-d)/l;break;case 90:c=t+(n[0]-h)/o,u=e-(n[1]-d)/l,[a,r]=[r,-a];break;case 180:c=t-this.width+(n[0]-h)/o,u=e-(n[1]-d)/l,[a,r]=[-a,-r];break;case 270:c=t+(n[0]-h-this.height*l)/o,u=e+(n[1]-d-this.width*o)/l,[a,r]=[-r,a]}this.setAt(c*i,u*s,a,r)}else this.setAt(t*i,e*s,this.width*i,this.height*s);this.#cn(),this._isDraggable=!0,this.editorDiv.contentEditable=!1}else this._isDraggable=!1,this.editorDiv.contentEditable=!0;return this.div}static#dn(t){return(t.nodeType===Node.TEXT_NODE?t.nodeValue:t.innerText).replaceAll(Ji,"")}editorDivPaste(t){const e=t.clipboardData||window.clipboardData,{types:i}=e;if(1===i.length&&"text/plain"===i[0])return;t.preventDefault();const s=Zi.#un(e.getData("text")||"").replaceAll(Ji,"\n");if(!s)return;const n=window.getSelection();if(!n.rangeCount)return;this.editorDiv.normalize(),n.deleteFromDocument();const a=n.getRangeAt(0);if(!s.includes("\n"))return a.insertNode(document.createTextNode(s)),this.editorDiv.normalize(),void n.collapseToStart();const{startContainer:r,startOffset:o}=a,l=[],h=[];if(r.nodeType===Node.TEXT_NODE){const t=r.parentElement;if(h.push(r.nodeValue.slice(o).replaceAll(Ji,"")),t!==this.editorDiv){let e=l;for(const i of this.editorDiv.childNodes)i!==t?e.push(Zi.#dn(i)):e=h}l.push(r.nodeValue.slice(0,o).replaceAll(Ji,""))}else if(r===this.editorDiv){let t=l,e=0;for(const i of this.editorDiv.childNodes)e++===o&&(t=h),t.push(Zi.#dn(i))}this.#sn=`${l.join("\n")}${s}${h.join("\n")}`,this.#cn();const d=new Range;let c=l.reduce(((t,e)=>t+e.length),0);for(const{firstChild:t}of this.editorDiv.childNodes)if(t.nodeType===Node.TEXT_NODE){const e=t.nodeValue.length;if(c<=e){d.setStart(t,c),d.setEnd(t,c);break}c-=e}n.removeAllRanges(),n.addRange(d)}#cn(){if(this.editorDiv.replaceChildren(),this.#sn)for(const t of this.#sn.split("\n")){const e=document.createElement("div");e.append(t?document.createTextNode(t):document.createElement("br")),this.editorDiv.append(e)}}#pn(){return this.#sn.replaceAll(" "," ")}static#un(t){return t.replaceAll(" "," ")}get contentDiv(){return this.editorDiv}static async deserialize(t,e,i){let s=null;if(t instanceof Oi){const{data:{defaultAppearanceData:{fontSize:e,fontColor:i},rect:n,rotation:a,id:r,popupRef:o},textContent:l,textPosition:d,parent:{page:{pageNumber:c}}}=t;if(!l||0===l.length)return null;s=t={annotationType:h.FREETEXT,color:Array.from(i),fontSize:e,value:l.join("\n"),position:d,pageIndex:c-1,rect:n.slice(0),rotation:a,id:r,deleted:!1,popupRef:o}}const n=await super.deserialize(t,e,i);return n.#Hs=t.fontSize,n.#Ts=z.makeHexColor(...t.color),n.#sn=Zi.#un(t.value),n.annotationElementId=t.id||null,n._initialData=s,n}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const e=Zi._internalPadding*this.parentScale,i=this.getRect(e,e),s=kt._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:this.#Ts),n={annotationType:h.FREETEXT,color:s,fontSize:this.#Hs,value:this.#pn(),pageIndex:this.pageIndex,rect:i,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return t?n:this.annotationElementId&&!this.#gn(n)?null:(n.id=this.annotationElementId,n)}#gn(t){const{value:e,fontSize:i,color:s,pageIndex:n}=this._initialData;return this._hasBeenMoved||t.value!==e||t.fontSize!==i||t.color.some(((t,e)=>t!==s[e]))||t.pageIndex!==n}renderAnnotationElement(t){const e=super.renderAnnotationElement(t);if(this.deleted)return e;const{style:i}=e;i.fontSize=`calc(${this.#Hs}px * var(--scale-factor))`,i.color=this.#Ts,e.replaceChildren();for(const t of this.#sn.split("\n")){const i=document.createElement("div");i.append(t?document.createTextNode(t):document.createElement("br")),e.append(i)}const s=Zi._internalPadding*this.parentScale;return t.updateEdited({rect:this.getRect(s,s),popupContent:this.#sn}),e}resetAnnotationElement(t){super.resetAnnotationElement(t),t.resetEdited()}}class ts{#mn;#fn=[];#bn=[];constructor(t,e=0,i=0,s=!0){let n=1/0,a=-1/0,r=1/0,o=-1/0;const l=10**-4;for(const{x:i,y:s,width:h,height:d}of t){const t=Math.floor((i-e)/l)*l,c=Math.ceil((i+h+e)/l)*l,u=Math.floor((s-e)/l)*l,p=Math.ceil((s+d+e)/l)*l,g=[t,u,p,!0],m=[c,u,p,!1];this.#fn.push(g,m),n=Math.min(n,t),a=Math.max(a,c),r=Math.min(r,u),o=Math.max(o,p)}const h=a-n+2*i,d=o-r+2*i,c=n-i,u=r-i,p=this.#fn.at(s?-1:-2),g=[p[0],p[2]];for(const t of this.#fn){const[e,i,s]=t;t[0]=(e-c)/h,t[1]=(i-u)/d,t[2]=(s-u)/d}this.#mn={x:c,y:u,width:h,height:d,lastPoint:g}}getOutlines(){this.#fn.sort(((t,e)=>t[0]-e[0]||t[1]-e[1]||t[2]-e[2]));const t=[];for(const e of this.#fn)e[3]?(t.push(...this.#vn(e)),this.#An(e)):(this.#yn(e),t.push(...this.#vn(e)));return this.#wn(t)}#wn(t){const e=[],i=new Set;for(const i of t){const[t,s,n]=i;e.push([t,s,i],[t,n,i])}e.sort(((t,e)=>t[1]-e[1]||t[0]-e[0]));for(let t=0,s=e.length;t0;){const t=i.values().next().value;let[e,a,r,o,l]=t;i.delete(t);let h=e,d=a;for(n=[e,r],s.push(n);;){let t;if(i.has(o))t=o;else{if(!i.has(l))break;t=l}i.delete(t),[e,a,r,o,l]=t,h!==e&&(n.push(h,d,e,d===a?a:r),h=e),d=d===a?r:a}n.push(h,d)}return new is(s,this.#mn)}#_n(t){const e=this.#bn;let i=0,s=e.length-1;for(;i<=s;){const n=i+s>>1,a=e[n][0];if(a===t)return n;a=0;s--){const[i,n]=this.#bn[s];if(i!==t)break;if(i===t&&n===e)return void this.#bn.splice(s,1)}}#vn(t){const[e,i,s]=t,n=[[e,i,s]],a=this.#_n(s);for(let t=0;t=i)if(o>s)n[t][1]=s;else{if(1===a)return[];n.splice(t,1),t--,a--}else n[t][2]=i,o>s&&n.push([e,s,o])}}return n}}class es{toSVGPath(){throw new Error("Abstract method `toSVGPath` must be implemented.")}get box(){throw new Error("Abstract getter `box` must be implemented.")}serialize(t,e){throw new Error("Abstract method `serialize` must be implemented.")}get free(){return this instanceof ns}}class is extends es{#mn;#xn;constructor(t,e){super(),this.#xn=t,this.#mn=e}toSVGPath(){const t=[];for(const e of this.#xn){let[i,s]=e;t.push(`M${i} ${s}`);for(let n=2;n=6;t-=6)isNaN(e[t])?u.push(`L${e[t+4]} ${e[t+5]}`):u.push(`C${e[t]} ${e[t+1]} ${e[t+2]} ${e[t+3]} ${e[t+4]} ${e[t+5]}`);return u.push(`L${e[4]} ${e[5]} Z`),u.join(" ")}getOutlines(){const t=this.#Tn,e=this.#Cn,i=this.#Mn,s=i.subarray(4,6),n=i.subarray(16,18),[a,r,o,l]=this.#mn,h=new Float64Array((this.#Fn?.length??0)+2);for(let t=0,e=h.length-2;t=6;t-=6)for(let i=0;i<6;i+=2)isNaN(e[t+i])?(g[m]=g[m+1]=NaN,m+=2):(g[m]=e[t+i],g[m+1]=e[t+i+1],m+=2);return g.set([NaN,NaN,NaN,NaN,e[4],e[5]],m),new ns(g,h,this.#mn,this.#Dn,this.#En,this.#Sn)}}class ns extends es{#mn;#Hn=null;#En;#Sn;#Fn;#Dn;#jn;constructor(t,e,i,s,n,a){super(),this.#jn=t,this.#Fn=e,this.#mn=i,this.#Dn=s,this.#En=n,this.#Sn=a,this.#Un(a);const{x:r,y:o,width:l,height:h}=this.#Hn;for(let e=0,i=t.length;e-1?(this.#ga=!0,this.#ya(t),this.#wa()):this.#oa&&(this.#aa=t.anchorNode,this.#ra=t.anchorOffset,this.#da=t.focusNode,this.#ca=t.focusOffset,this.#_a(),this.#wa(),this.rotate(this.rotation))}get telemetryInitialData(){return{action:"added",type:this.#ga?"free_highlight":"highlight",color:this._uiManager.highlightColorNames.get(this.color),thickness:this.#Ln,methodOfCreation:this.#Aa}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.highlightColorNames.get(this.color)}}static computeTelemetryFinalData(t){return{numberOfColors:t.get("color").size}}#_a(){const t=new ts(this.#oa,.001);this.#pa=t.getOutlines(),({x:this.x,y:this.y,width:this.width,height:this.height}=this.#pa.box);const e=new ts(this.#oa,.0025,.001,"ltr"===this._uiManager.direction);this.#ha=e.getOutlines();const{lastPoint:i}=this.#ha.box;this.#ma=[(i[0]-this.x)/this.width,(i[1]-this.y)/this.height]}#ya({highlightOutlines:t,highlightId:e,clipPathId:i}){if(this.#pa=t,this.#ha=t.getNewOutline(this.#Ln/2+1.5,.0025),e>=0)this.#A=e,this.#la=i,this.parent.drawLayer.finalizeLine(e,t),this.#ba=this.parent.drawLayer.highlightOutline(this.#ha);else if(this.parent){const e=this.parent.viewport.rotation;this.parent.drawLayer.updateLine(this.#A,t),this.parent.drawLayer.updateBox(this.#A,rs.#xa(this.#pa.box,(e-this.rotation+360)%360)),this.parent.drawLayer.updateLine(this.#ba,this.#ha),this.parent.drawLayer.updateBox(this.#ba,rs.#xa(this.#ha.box,e))}const{x:s,y:n,width:a,height:r}=t.box;switch(this.rotation){case 0:this.x=s,this.y=n,this.width=a,this.height=r;break;case 90:{const[t,e]=this.parentDimensions;this.x=n,this.y=1-s,this.width=a*e/t,this.height=r*t/e;break}case 180:this.x=1-s,this.y=1-n,this.width=a,this.height=r;break;case 270:{const[t,e]=this.parentDimensions;this.x=1-n,this.y=s,this.width=a*e/t,this.height=r*t/e;break}}const{lastPoint:o}=this.#ha.box;this.#ma=[(o[0]-s)/a,(o[1]-n)/r]}static initialize(t,e){kt.initialize(t,e),rs._defaultColor||=e.highlightColors?.values().next().value||"#fff066"}static updateDefaultParams(t,e){switch(t){case d.HIGHLIGHT_DEFAULT_COLOR:rs._defaultColor=e;break;case d.HIGHLIGHT_THICKNESS:rs._defaultThickness=e}}translateInPage(t,e){}get toolbarPosition(){return this.#ma}updateParams(t,e){switch(t){case d.HIGHLIGHT_COLOR:this.#on(e);break;case d.HIGHLIGHT_THICKNESS:this.#Ca(e)}}static get defaultPropertiesToUpdate(){return[[d.HIGHLIGHT_DEFAULT_COLOR,rs._defaultColor],[d.HIGHLIGHT_THICKNESS,rs._defaultThickness]]}get propertiesToUpdate(){return[[d.HIGHLIGHT_COLOR,this.color||rs._defaultColor],[d.HIGHLIGHT_THICKNESS,this.#Ln||rs._defaultThickness],[d.HIGHLIGHT_FREE,this.#ga]]}#on(t){const e=(t,e)=>{this.color=t,this.parent?.drawLayer.changeColor(this.#A,t),this.#n?.updateColor(t),this.#fa=e,this.parent?.drawLayer.changeOpacity(this.#A,e)},i=this.color,s=this.#fa;this.addCommands({cmd:e.bind(this,t,rs._defaultOpacity),undo:e.bind(this,i,s),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:d.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"color_changed",color:this._uiManager.highlightColorNames.get(t)},!0)}#Ca(t){const e=this.#Ln,i=t=>{this.#Ln=t,this.#Ea(t)};this.addCommands({cmd:i.bind(this,t),undo:i.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:d.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"thickness_changed",thickness:t},!0)}async addEditToolbar(){const t=await super.addEditToolbar();return t?(this._uiManager.highlightColors&&(this.#n=new as({editor:this}),t.addColorPicker(this.#n)),t):null}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(this.#Sa())}getBaseTranslation(){return[0,0]}getRect(t,e){return super.getRect(t,e,this.#Sa())}onceAdded(){this.annotationElementId||this.parent.addUndoableEditor(this),this.div.focus()}remove(){this.#Ta(),this._reportTelemetry({action:"deleted"}),super.remove()}rebuild(){this.parent&&(super.rebuild(),null!==this.div&&(this.#wa(),this.isAttachedToDOM||this.parent.add(this)))}setParent(t){let e=!1;this.parent&&!t?this.#Ta():t&&(this.#wa(t),e=!this.parent&&this.div?.classList.contains("selectedEditor")),super.setParent(t),this.show(this._isVisible),e&&this.select()}#Ea(t){if(!this.#ga)return;this.#ya({highlightOutlines:this.#pa.getNewOutline(t/2)}),this.fixAndSetPosition();const[e,i]=this.parentDimensions;this.setDims(this.width*e,this.height*i)}#Ta(){null!==this.#A&&this.parent&&(this.parent.drawLayer.remove(this.#A),this.#A=null,this.parent.drawLayer.remove(this.#ba),this.#ba=null)}#wa(t=this.parent){null===this.#A&&(({id:this.#A,clipPathId:this.#la}=t.drawLayer.highlight(this.#pa,this.color,this.#fa)),this.#ba=t.drawLayer.highlightOutline(this.#ha),this.#ua&&(this.#ua.style.clipPath=this.#la))}static#xa({x:t,y:e,width:i,height:s},n){switch(n){case 90:return{x:1-e-s,y:t,width:s,height:i};case 180:return{x:1-t-i,y:1-e-s,width:i,height:s};case 270:return{x:e,y:1-t-i,width:s,height:i}}return{x:t,y:e,width:i,height:s}}rotate(t){const{drawLayer:e}=this.parent;let i;this.#ga?(t=(t-this.rotation+360)%360,i=rs.#xa(this.#pa.box,t)):i=rs.#xa(this,t),e.rotate(this.#A,t),e.rotate(this.#ba,t),e.updateBox(this.#A,i),e.updateBox(this.#ba,rs.#xa(this.#ha.box,t))}render(){if(this.div)return this.div;const t=super.render();this.#va&&(t.setAttribute("aria-label",this.#va),t.setAttribute("role","mark")),this.#ga?t.classList.add("free"):this.div.addEventListener("keydown",this.#Ma.bind(this),{signal:this._uiManager._signal});const e=this.#ua=document.createElement("div");t.append(e),e.setAttribute("aria-hidden","true"),e.className="internal",e.style.clipPath=this.#la;const[i,s]=this.parentDimensions;return this.setDims(this.width*i,this.height*s),wt(this,this.#ua,["pointerover","pointerleave"]),this.enableEditing(),t}pointerover(){this.parent.drawLayer.addClass(this.#ba,"hovered")}pointerleave(){this.parent.drawLayer.removeClass(this.#ba,"hovered")}#Ma(t){rs._keyboardManager.exec(this,t)}_moveCaret(t){switch(this.parent.unselect(this),t){case 0:case 2:this.#ka(!0);break;case 1:case 3:this.#ka(!1)}}#ka(t){if(!this.#aa)return;const e=window.getSelection();t?e.setPosition(this.#aa,this.#ra):e.setPosition(this.#da,this.#ca)}select(){super.select(),this.#ba&&(this.parent?.drawLayer.removeClass(this.#ba,"hovered"),this.parent?.drawLayer.addClass(this.#ba,"selected"))}unselect(){super.unselect(),this.#ba&&(this.parent?.drawLayer.removeClass(this.#ba,"selected"),this.#ga||this.#ka(!1))}get _mustFixPosition(){return!this.#ga}show(t=this._isVisible){super.show(t),this.parent&&(this.parent.drawLayer.show(this.#A,t),this.parent.drawLayer.show(this.#ba,t))}#Sa(){return this.#ga?this.rotation:0}#Ia(){if(this.#ga)return null;const[t,e]=this.pageDimensions,[i,s]=this.pageTranslation,n=this.#oa,a=new Float32Array(8*n.length);let r=0;for(const{x:o,y:l,width:h,height:d}of n){const n=o*t+i,c=(1-l-d)*e+s;a[r]=a[r+4]=n,a[r+1]=a[r+3]=c,a[r+2]=a[r+6]=n+h*t,a[r+5]=a[r+7]=c+d*e,r+=8}return a}#Pa(t){return this.#pa.serialize(t,this.#Sa())}static startHighlighting(t,e,{target:i,x:s,y:n}){const{x:a,y:r,width:o,height:l}=i.getBoundingClientRect(),h=new AbortController,d=t.combinedSignal(h),c=e=>{h.abort(),this.#Ra(t,e)};window.addEventListener("blur",c,{signal:d}),window.addEventListener("pointerup",c,{signal:d}),window.addEventListener("pointerdown",(t=>{t.preventDefault(),t.stopPropagation()}),{capture:!0,passive:!1,signal:d}),window.addEventListener("contextmenu",ht,{signal:d}),i.addEventListener("pointermove",this.#Da.bind(this,t),{signal:d}),this._freeHighlight=new ss({x:s,y:n},[a,r,o,l],t.scale,this._defaultThickness/2,e,.001),({id:this._freeHighlightId,clipPathId:this._freeHighlightClipId}=t.drawLayer.highlight(this._freeHighlight,this._defaultColor,this._defaultOpacity,!0))}static#Da(t,e){this._freeHighlight.add(e)&&t.drawLayer.updatePath(this._freeHighlightId,this._freeHighlight)}static#Ra(t,e){this._freeHighlight.isEmpty()?t.drawLayer.removeFreeHighlight(this._freeHighlightId):t.createAndAddNewEditor(e,!1,{highlightId:this._freeHighlightId,highlightOutlines:this._freeHighlight.getOutlines(),clipPathId:this._freeHighlightClipId,methodOfCreation:"main_toolbar"}),this._freeHighlightId=-1,this._freeHighlight=null,this._freeHighlightClipId=""}static async deserialize(t,e,i){let s=null;if(t instanceof Gi){const{data:{quadPoints:e,rect:i,rotation:n,id:a,color:r,opacity:o,popupRef:l},parent:{page:{pageNumber:d}}}=t;s=t={annotationType:h.HIGHLIGHT,color:Array.from(r),opacity:o,quadPoints:e,boxes:null,pageIndex:d-1,rect:i.slice(0),rotation:n,id:a,deleted:!1,popupRef:l}}else if(t instanceof Wi){const{data:{inkLists:e,rect:i,rotation:n,id:a,color:r,borderStyle:{rawWidth:o},popupRef:l},parent:{page:{pageNumber:d}}}=t;s=t={annotationType:h.HIGHLIGHT,color:Array.from(r),thickness:o,inkLists:e,boxes:null,pageIndex:d-1,rect:i.slice(0),rotation:n,id:a,deleted:!1,popupRef:l}}const{color:n,quadPoints:a,inkLists:r,opacity:o}=t,l=await super.deserialize(t,e,i);l.color=z.makeHexColor(...n),l.#fa=o||1,r&&(l.#Ln=t.thickness),l.annotationElementId=t.id||null,l._initialData=s;const[d,c]=l.pageDimensions,[u,p]=l.pageTranslation;if(a){const t=l.#oa=[];for(let e=0;et!==e[i]))}renderAnnotationElement(t){return t.updateEdited({rect:this.getRect(0,0)}),null}static canCreateNewEmptyEditor(){return!1}}class os extends kt{#La=0;#Fa=0;#Na=null;#Oa=new Path2D;#Ba=!1;#za=null;#Ha=!1;#ja=!1;#Ua=null;#$a=null;#Wa=0;#Ga=0;#Va=null;static _defaultColor=null;static _defaultOpacity=1;static _defaultThickness=1;static _type="ink";static _editorType=h.INK;constructor(t){super({...t,name:"inkEditor"}),this.color=t.color||null,this.thickness=t.thickness||null,this.opacity=t.opacity||null,this.paths=[],this.bezierPath2D=[],this.allRawPaths=[],this.currentPath=[],this.scaleFactor=1,this.translationX=this.translationY=0,this.x=0,this.y=0,this._willKeepAspectRatio=!0}static initialize(t,e){kt.initialize(t,e)}static updateDefaultParams(t,e){switch(t){case d.INK_THICKNESS:os._defaultThickness=e;break;case d.INK_COLOR:os._defaultColor=e;break;case d.INK_OPACITY:os._defaultOpacity=e/100}}updateParams(t,e){switch(t){case d.INK_THICKNESS:this.#Ca(e);break;case d.INK_COLOR:this.#on(e);break;case d.INK_OPACITY:this.#qa(e)}}static get defaultPropertiesToUpdate(){return[[d.INK_THICKNESS,os._defaultThickness],[d.INK_COLOR,os._defaultColor||kt._defaultLineColor],[d.INK_OPACITY,Math.round(100*os._defaultOpacity)]]}get propertiesToUpdate(){return[[d.INK_THICKNESS,this.thickness||os._defaultThickness],[d.INK_COLOR,this.color||os._defaultColor||kt._defaultLineColor],[d.INK_OPACITY,Math.round(100*(this.opacity??os._defaultOpacity))]]}#Ca(t){const e=t=>{this.thickness=t,this.#Xa()},i=this.thickness;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:d.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0})}#on(t){const e=t=>{this.color=t,this.#Ka()},i=this.color;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:d.INK_COLOR,overwriteIfSameType:!0,keepUndo:!0})}#qa(t){const e=t=>{this.opacity=t,this.#Ka()};t/=100;const i=this.opacity;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:d.INK_OPACITY,overwriteIfSameType:!0,keepUndo:!0})}rebuild(){this.parent&&(super.rebuild(),null!==this.div&&(this.canvas||(this.#Ya(),this.#Qa()),this.isAttachedToDOM||(this.parent.add(this),this.#Ja()),this.#Xa()))}remove(){null!==this.canvas&&(this.isEmpty()||this.commit(),this.canvas.width=this.canvas.height=0,this.canvas.remove(),this.canvas=null,this.#Na&&(clearTimeout(this.#Na),this.#Na=null),this.#Ua?.disconnect(),this.#Ua=null,super.remove())}setParent(t){!this.parent&&t?this._uiManager.removeShouldRescale(this):this.parent&&null===t&&this._uiManager.addShouldRescale(this),super.setParent(t)}onScaleChanging(){const[t,e]=this.parentDimensions,i=this.width*t,s=this.height*e;this.setDimensions(i,s)}enableEditMode(){this.#Ba||null===this.canvas||(super.enableEditMode(),this._isDraggable=!1,this.#Za())}disableEditMode(){this.isInEditMode()&&null!==this.canvas&&(super.disableEditMode(),this._isDraggable=!this.isEmpty(),this.div.classList.remove("editing"),this.#tr())}onceAdded(){this._isDraggable=!this.isEmpty()}isEmpty(){return 0===this.paths.length||1===this.paths.length&&0===this.paths[0].length}#er(){const{parentRotation:t,parentDimensions:[e,i]}=this;switch(t){case 90:return[0,i,i,e];case 180:return[e,i,e,i];case 270:return[e,0,i,e];default:return[0,0,e,i]}}#ir(){const{ctx:t,color:e,opacity:i,thickness:s,parentScale:n,scaleFactor:a}=this;t.lineWidth=s*n/a,t.lineCap="round",t.lineJoin="round",t.miterLimit=10,t.strokeStyle=`${e}${function(t){return Math.round(Math.min(255,Math.max(1,255*t))).toString(16).padStart(2,"0")}(i)}`}#sr(t,e){this.canvas.addEventListener("contextmenu",ht,{signal:this._uiManager._signal}),this.#tr(),this.#za=new AbortController;const i=this._uiManager.combinedSignal(this.#za);this.canvas.addEventListener("pointerleave",this.canvasPointerleave.bind(this),{signal:i}),this.canvas.addEventListener("pointermove",this.canvasPointermove.bind(this),{signal:i}),this.canvas.addEventListener("pointerup",this.canvasPointerup.bind(this),{signal:i}),this.isEditing=!0,this.#ja||(this.#ja=!0,this.#Ja(),this.thickness||=os._defaultThickness,this.color||=os._defaultColor||kt._defaultLineColor,this.opacity??=os._defaultOpacity),this.currentPath.push([t,e]),this.#Ha=!1,this.#ir(),this.#Va=()=>{this.#nr(),this.#Va&&window.requestAnimationFrame(this.#Va)},window.requestAnimationFrame(this.#Va)}#ar(t,e){const[i,s]=this.currentPath.at(-1);if(this.currentPath.length>1&&t===i&&e===s)return;const n=this.currentPath;let a=this.#Oa;if(n.push([t,e]),this.#Ha=!0,n.length<=2)return a.moveTo(...n[0]),void a.lineTo(t,e);3===n.length&&(this.#Oa=a=new Path2D,a.moveTo(...n[0])),this.#rr(a,...n.at(-3),...n.at(-2),t,e)}#or(){if(0===this.currentPath.length)return;const t=this.currentPath.at(-1);this.#Oa.lineTo(...t)}#lr(t,e){let i;if(this.#Va=null,t=Math.min(Math.max(t,0),this.canvas.width),e=Math.min(Math.max(e,0),this.canvas.height),this.#ar(t,e),this.#or(),1!==this.currentPath.length)i=this.#hr();else{const s=[t,e];i=[[s,s.slice(),s.slice(),s]]}const s=this.#Oa,n=this.currentPath;this.currentPath=[],this.#Oa=new Path2D,this.addCommands({cmd:()=>{this.allRawPaths.push(n),this.paths.push(i),this.bezierPath2D.push(s),this._uiManager.rebuild(this)},undo:()=>{this.allRawPaths.pop(),this.paths.pop(),this.bezierPath2D.pop(),0===this.paths.length?this.remove():(this.canvas||(this.#Ya(),this.#Qa()),this.#Xa())},mustExec:!0})}#nr(){if(!this.#Ha)return;this.#Ha=!1;Math.ceil(this.thickness*this.parentScale);const t=this.currentPath.slice(-3),e=t.map((t=>t[0])),i=t.map((t=>t[1])),{ctx:s}=(Math.min(...e),Math.max(...e),Math.min(...i),Math.max(...i),this);s.save(),s.clearRect(0,0,this.canvas.width,this.canvas.height);for(const t of this.bezierPath2D)s.stroke(t);s.stroke(this.#Oa),s.restore()}#rr(t,e,i,s,n,a,r){const o=(e+s)/2,l=(i+n)/2,h=(s+a)/2,d=(n+r)/2;t.bezierCurveTo(o+2*(s-o)/3,l+2*(n-l)/3,h+2*(s-h)/3,d+2*(n-d)/3,h,d)}#hr(){const t=this.currentPath;if(t.length<=2)return[[t[0],t[0],t.at(-1),t.at(-1)]];const e=[];let i,[s,n]=t[0];for(i=1;i{this.#Na=null,this.canvas.removeEventListener("contextmenu",ht)}),10),this.#lr(t.offsetX,t.offsetY),this.addToAnnotationStorage(),this.setInBackground()}#Ya(){this.canvas=document.createElement("canvas"),this.canvas.width=this.canvas.height=0,this.canvas.className="inkEditorCanvas",this.canvas.setAttribute("data-l10n-id","pdfjs-ink-canvas"),this.div.append(this.canvas),this.ctx=this.canvas.getContext("2d")}#Qa(){this.#Ua=new ResizeObserver((t=>{const e=t[0].contentRect;e.width&&e.height&&this.setDimensions(e.width,e.height)})),this.#Ua.observe(this.div),this._uiManager._signal.addEventListener("abort",(()=>{this.#Ua?.disconnect(),this.#Ua=null}),{once:!0})}get isResizable(){return!this.isEmpty()&&this.#Ba}render(){if(this.div)return this.div;let t,e;this.width&&(t=this.x,e=this.y),super.render(),this.div.setAttribute("data-l10n-id","pdfjs-ink");const[i,s,n,a]=this.#er();if(this.setAt(i,s,0,0),this.setDims(n,a),this.#Ya(),this.width){const[i,s]=this.parentDimensions;this.setAspectRatio(this.width*i,this.height*s),this.setAt(t*i,e*s,this.width*i,this.height*s),this.#ja=!0,this.#Ja(),this.setDims(this.width*i,this.height*s),this.#Ka(),this.div.classList.add("disabled")}else this.div.classList.add("editing"),this.enableEditMode();return this.#Qa(),this.div}#Ja(){if(!this.#ja)return;const[t,e]=this.parentDimensions;this.canvas.width=Math.ceil(this.width*t),this.canvas.height=Math.ceil(this.height*e),this.#dr()}setDimensions(t,e){const i=Math.round(t),s=Math.round(e);if(this.#Wa===i&&this.#Ga===s)return;this.#Wa=i,this.#Ga=s,this.canvas.style.visibility="hidden";const[n,a]=this.parentDimensions;this.width=t/n,this.height=e/a,this.fixAndSetPosition(),this.#Ba&&this.#ur(t,e),this.#Ja(),this.#Ka(),this.canvas.style.visibility="visible",this.fixDims()}#ur(t,e){const i=this.#pr(),s=(t-i)/this.#Fa,n=(e-i)/this.#La;this.scaleFactor=Math.min(s,n)}#dr(){const t=this.#pr()/2;this.ctx.setTransform(this.scaleFactor,0,0,this.scaleFactor,this.translationX*this.scaleFactor+t,this.translationY*this.scaleFactor+t)}static#gr(t){const e=new Path2D;for(let i=0,s=t.length;i`image/${t}`)))}static get supportedTypesStr(){return E(this,"supportedTypesStr",this.supportedTypes.join(","))}static isHandlingMimeForPasting(t){return this.supportedTypes.includes(t)}static paste(t,e){e.pasteEditor(h.STAMP,{bitmapFile:t.getAsFile()})}altTextFinish(){this._uiManager.useNewAltTextFlow&&(this.div.hidden=!1),super.altTextFinish()}get telemetryFinalData(){return{type:"stamp",hasAltText:!!this.altTextData?.altText}}static computeTelemetryFinalData(t){const e=t.get("hasAltText");return{hasAltText:e.get(!0)??0,hasNoAltText:e.get(!1)??0}}#kr(t,e=!1){t?(this.#Ar=t.bitmap,e||(this.#yr=t.id,this.#Tr=t.isSvg),t.file&&(this.#Cr=t.file.name),this.#Ya()):this.remove()}#Ir(){if(this.#wr=null,this._uiManager.enableWaiting(!1),this.#Er){if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#Ar)return this._editToolbar.hide(),void this._uiManager.editAltText(this,!0);if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#Ar){this._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:!1,alt_text_type:"empty"}});try{this.mlGuessAltText()}catch{}}this.div.focus()}}async mlGuessAltText(t=null,e=!0){if(this.hasAltTextData())return null;const{mlManager:i}=this._uiManager;if(!i)throw new Error("No ML.");if(!await i.isEnabledFor("altText"))throw new Error("ML isn't enabled for alt text.");const{data:s,width:n,height:a}=t||this.copyCanvas(null,null,!0).imageData,r=await i.guess({name:"altText",request:{data:s,width:n,height:a,channels:s.length/(n*a)}});if(!r)throw new Error("No response from the AI service.");if(r.error)throw new Error("Error from the AI service.");if(r.cancel)return null;if(!r.output)throw new Error("No valid response from the AI service.");const o=r.output;return await this.setGuessedAltText(o),e&&!this.hasAltTextData()&&(this.altTextData={alt:o,decorative:!1}),o}#Pr(){if(this.#yr)return this._uiManager.enableWaiting(!0),void this._uiManager.imageManager.getFromId(this.#yr).then((t=>this.#kr(t,!0))).finally((()=>this.#Ir()));if(this.#_r){const t=this.#_r;return this.#_r=null,this._uiManager.enableWaiting(!0),void(this.#wr=this._uiManager.imageManager.getFromUrl(t).then((t=>this.#kr(t))).finally((()=>this.#Ir())))}if(this.#xr){const t=this.#xr;return this.#xr=null,this._uiManager.enableWaiting(!0),void(this.#wr=this._uiManager.imageManager.getFromFile(t).then((t=>this.#kr(t))).finally((()=>this.#Ir())))}const t=document.createElement("input");t.type="file",t.accept=ls.supportedTypesStr;const e=this._uiManager._signal;this.#wr=new Promise((i=>{t.addEventListener("change",(async()=>{if(t.files&&0!==t.files.length){this._uiManager.enableWaiting(!0);const e=await this._uiManager.imageManager.getFromFile(t.files[0]);this._reportTelemetry({action:"pdfjs.image.image_selected",data:{alt_text_modal:this._uiManager.useNewAltTextFlow}}),this.#kr(e)}else this.remove();i()}),{signal:e}),t.addEventListener("cancel",(()=>{this.remove(),i()}),{signal:e})})).finally((()=>this.#Ir())),t.click()}remove(){this.#yr&&(this.#Ar=null,this._uiManager.imageManager.deleteId(this.#yr),this.#Er?.remove(),this.#Er=null,this.#Ua?.disconnect(),this.#Ua=null,this.#Sr&&(clearTimeout(this.#Sr),this.#Sr=null)),super.remove()}rebuild(){this.parent?(super.rebuild(),null!==this.div&&(this.#yr&&null===this.#Er&&this.#Pr(),this.isAttachedToDOM||this.parent.add(this))):this.#yr&&this.#Pr()}onceAdded(){this._isDraggable=!0,this.div.focus()}isEmpty(){return!(this.#wr||this.#Ar||this.#_r||this.#xr||this.#yr)}get isResizable(){return!0}render(){if(this.div)return this.div;let t,e;if(this.width&&(t=this.x,e=this.y),super.render(),this.div.hidden=!0,this.div.setAttribute("role","figure"),this.addAltTextButton(),this.#Ar?this.#Ya():this.#Pr(),this.width&&!this.annotationElementId){const[i,s]=this.parentDimensions;this.setAt(t*i,e*s,this.width*i,this.height*s)}return this.div}#Ya(){const{div:t}=this;let{width:e,height:i}=this.#Ar;const[s,n]=this.pageDimensions,a=.75;if(this.width)e=this.width*s,i=this.height*n;else if(e>a*s||i>a*n){const t=Math.min(a*s/e,a*n/i);e*=t,i*=t}const[r,o]=this.parentDimensions;this.setDims(e*r/s,i*o/n),this._uiManager.enableWaiting(!1);const l=this.#Er=document.createElement("canvas");l.setAttribute("role","img"),this.addContainer(l),this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&!this.annotationElementId||(t.hidden=!1),this.#Rr(e,i),this.#Qa(),this.#Mr||(this.parent.addUndoableEditor(this),this.#Mr=!0),this._reportTelemetry({action:"inserted_image"}),this.#Cr&&l.setAttribute("aria-label",this.#Cr)}copyCanvas(t,e,i=!1){t||(t=224);const{width:s,height:n}=this.#Ar,a=new vt;let r=this.#Ar,o=s,l=n,h=null;if(e){if(s>e||n>e){const t=Math.min(e/s,e/n);o=Math.floor(s*t),l=Math.floor(n*t)}h=document.createElement("canvas");const t=h.width=Math.ceil(o*a.sx),i=h.height=Math.ceil(l*a.sy);this.#Tr||(r=this.#Dr(t,i));const d=h.getContext("2d");d.filter=this._uiManager.hcmFilter;let c="white",u="#cfcfd8";"none"!==this._uiManager.hcmFilter?u="black":window.matchMedia?.("(prefers-color-scheme: dark)").matches&&(c="#8f8f9d",u="#42414d");const p=15,g=p*a.sx,m=p*a.sy,f=new OffscreenCanvas(2*g,2*m),b=f.getContext("2d");b.fillStyle=c,b.fillRect(0,0,2*g,2*m),b.fillStyle=u,b.fillRect(0,0,g,m),b.fillRect(g,m,g,m),d.fillStyle=d.createPattern(f,"repeat"),d.fillRect(0,0,t,i),d.drawImage(r,0,0,r.width,r.height,0,0,t,i)}let d=null;if(i){let e,i;if(a.symmetric&&r.widtht||n>t){const a=Math.min(t/s,t/n);e=Math.floor(s*a),i=Math.floor(n*a),this.#Tr||(r=this.#Dr(e,i))}const o=new OffscreenCanvas(e,i).getContext("2d",{willReadFrequently:!0});o.drawImage(r,0,0,r.width,r.height,0,0,e,i),d={width:e,height:i,data:o.getImageData(0,0,e,i).data}}return{canvas:h,width:o,height:l,imageData:d}}#Lr(t,e){const[i,s]=this.parentDimensions;this.width=t/i,this.height=e/s,this._initialOptions?.isCentered?this.center():this.fixAndSetPosition(),this._initialOptions=null,null!==this.#Sr&&clearTimeout(this.#Sr),this.#Sr=setTimeout((()=>{this.#Sr=null,this.#Rr(t,e)}),200)}#Dr(t,e){const{width:i,height:s}=this.#Ar;let n=i,a=s,r=this.#Ar;for(;n>2*t||a>2*e;){const i=n,s=a;n>2*t&&(n=n>=16384?Math.floor(n/2)-1:Math.ceil(n/2)),a>2*e&&(a=a>=16384?Math.floor(a/2)-1:Math.ceil(a/2));const o=new OffscreenCanvas(n,a);o.getContext("2d").drawImage(r,0,0,i,s,0,0,n,a),r=o.transferToImageBitmap()}return r}#Rr(t,e){const i=new vt,s=Math.ceil(t*i.sx),n=Math.ceil(e*i.sy),a=this.#Er;if(!a||a.width===s&&a.height===n)return;a.width=s,a.height=n;const r=this.#Tr?this.#Ar:this.#Dr(s,n),o=a.getContext("2d");o.filter=this._uiManager.hcmFilter,o.drawImage(r,0,0,r.width,r.height,0,0,s,n)}getImageForAltText(){return this.#Er}#Fr(t){if(t){if(this.#Tr){const t=this._uiManager.imageManager.getSvgUrl(this.#yr);if(t)return t}const t=document.createElement("canvas");return({width:t.width,height:t.height}=this.#Ar),t.getContext("2d").drawImage(this.#Ar,0,0),t.toDataURL()}if(this.#Tr){const[t,e]=this.pageDimensions,i=Math.round(this.width*t*Y.PDF_TO_CSS_UNITS),s=Math.round(this.height*e*Y.PDF_TO_CSS_UNITS),n=new OffscreenCanvas(i,s);return n.getContext("2d").drawImage(this.#Ar,0,0,this.#Ar.width,this.#Ar.height,0,0,i,s),n.transferToImageBitmap()}return structuredClone(this.#Ar)}#Qa(){this._uiManager._signal&&(this.#Ua=new ResizeObserver((t=>{const e=t[0].contentRect;e.width&&e.height&&this.#Lr(e.width,e.height)})),this.#Ua.observe(this.div),this._uiManager._signal.addEventListener("abort",(()=>{this.#Ua?.disconnect(),this.#Ua=null}),{once:!0}))}static async deserialize(t,e,i){let s=null;if(t instanceof Ki){const{data:{rect:n,rotation:a,id:r,structParent:o,popupRef:l},container:d,parent:{page:{pageNumber:c}}}=t,u=d.querySelector("canvas"),p=i.imageManager.getFromCanvas(d.id,u);u.remove();const g=(await e._structTree.getAriaAttributes(`${$}${r}`))?.get("aria-label")||"";s=t={annotationType:h.STAMP,bitmapId:p.id,bitmap:p.bitmap,pageIndex:c-1,rect:n.slice(0),rotation:a,id:r,deleted:!1,accessibilityData:{decorative:!1,altText:g},isSvg:!1,structParent:o,popupRef:l}}const n=await super.deserialize(t,e,i),{rect:a,bitmap:r,bitmapUrl:o,bitmapId:l,isSvg:d,accessibilityData:c}=t;l&&i.imageManager.isValidId(l)?(n.#yr=l,r&&(n.#Ar=r)):n.#_r=o,n.#Tr=d;const[u,p]=n.pageDimensions;return n.width=(a[2]-a[0])/u,n.height=(a[3]-a[1])/p,n.annotationElementId=t.id||null,c&&(n.altTextData=c),n._initialData=s,n.#Mr=!!s,n}serialize(t=!1,e=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const i={annotationType:h.STAMP,bitmapId:this.#yr,pageIndex:this.pageIndex,rect:this.getRect(0,0),rotation:this.rotation,isSvg:this.#Tr,structTreeParentId:this._structTreeParentId};if(t)return i.bitmapUrl=this.#Fr(!0),i.accessibilityData=this.serializeAltText(!0),i;const{decorative:s,altText:n}=this.serializeAltText(!1);if(!s&&n&&(i.accessibilityData={type:"Figure",alt:n}),this.annotationElementId){const t=this.#gn(i);if(t.isSame)return null;t.isSameAltText?delete i.accessibilityData:i.accessibilityData.structParent=this._initialData.structParent??-1}if(i.id=this.annotationElementId,null===e)return i;e.stamps||=new Map;const a=this.#Tr?(i.rect[2]-i.rect[0])*(i.rect[3]-i.rect[1]):null;if(e.stamps.has(this.#yr)){if(this.#Tr){const t=e.stamps.get(this.#yr);a>t.area&&(t.area=a,t.serialized.bitmap.close(),t.serialized.bitmap=this.#Fr(!1))}}else e.stamps.set(this.#yr,{area:a,serialized:i}),i.bitmap=this.#Fr(!1);return i}#gn(t){const{rect:e,pageIndex:i,accessibilityData:{altText:s}}=this._initialData,n=t.rect.every(((t,i)=>Math.abs(t-e[i])<1)),a=t.pageIndex===i,r=(t.accessibilityData?.alt||"")===s;return{isSame:n&&a&&r,isSameAltText:r}}renderAnnotationElement(t){return t.updateEdited({rect:this.getRect(0,0)}),null}}class hs{#Qs;#Nr=!1;#Or=null;#Br=null;#zr=null;#Hr=new Map;#jr=!1;#Ur=!1;#$r=!1;#Wr=null;#Gr=null;#m;static _initialized=!1;static#H=new Map([Zi,os,ls,rs].map((t=>[t._editorType,t])));constructor({uiManager:t,pageIndex:e,div:i,structTreeLayer:s,accessibilityManager:n,annotationLayer:a,drawLayer:r,textLayer:o,viewport:l,l10n:h}){const d=[...hs.#H.values()];if(!hs._initialized){hs._initialized=!0;for(const e of d)e.initialize(h,t)}t.registerEditorTypes(d),this.#m=t,this.pageIndex=e,this.div=i,this.#Qs=n,this.#Or=a,this.viewport=l,this.#Wr=o,this.drawLayer=r,this._structTree=s,this.#m.addLayer(this)}get isEmpty(){return 0===this.#Hr.size}get isInvisible(){return this.isEmpty&&this.#m.getMode()===h.NONE}updateToolbar(t){this.#m.updateToolbar(t)}updateMode(t=this.#m.getMode()){switch(this.#Vr(),t){case h.NONE:return this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),void this.disableClick();case h.INK:this.addInkEditorIfNeeded(!1),this.disableTextSelection(),this.togglePointerEvents(!0),this.disableClick();break;case h.HIGHLIGHT:this.enableTextSelection(),this.togglePointerEvents(!1),this.disableClick();break;default:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick()}this.toggleAnnotationLayerPointerEvents(!1);const{classList:e}=this.div;for(const i of hs.#H.values())e.toggle(`${i._type}Editing`,t===i._editorType);this.div.hidden=!1}hasTextLayer(t){return t===this.#Wr?.div}addInkEditorIfNeeded(t){if(this.#m.getMode()===h.INK){if(!t)for(const t of this.#Hr.values())if(t.isEmpty())return void t.setInBackground();this.createAndAddNewEditor({offsetX:0,offsetY:0},!1).setInBackground()}}setEditingState(t){this.#m.setEditingState(t)}addCommands(t){this.#m.addCommands(t)}toggleDrawing(t=!1){this.div.classList.toggle("drawing",!t)}togglePointerEvents(t=!1){this.div.classList.toggle("disabled",!t)}toggleAnnotationLayerPointerEvents(t=!1){this.#Or?.div.classList.toggle("disabled",!t)}async enable(){this.div.tabIndex=0,this.togglePointerEvents(!0);const t=new Set;for(const e of this.#Hr.values())e.enableEditing(),e.show(!0),e.annotationElementId&&(this.#m.removeChangedExistingAnnotation(e),t.add(e.annotationElementId));if(!this.#Or)return;const e=this.#Or.getEditableAnnotations();for(const i of e){if(i.hide(),this.#m.isDeletedAnnotationElement(i.data.id))continue;if(t.has(i.data.id))continue;const e=await this.deserialize(i);e&&(this.addOrRebuild(e),e.enableEditing())}}disable(){this.#$r=!0,this.div.tabIndex=-1,this.togglePointerEvents(!1);const t=new Map,e=new Map;for(const i of this.#Hr.values())i.disableEditing(),i.annotationElementId&&(null===i.serialize()?(e.set(i.annotationElementId,i),this.getEditableAnnotation(i.annotationElementId)?.show(),i.remove()):t.set(i.annotationElementId,i));if(this.#Or){const i=this.#Or.getEditableAnnotations();for(const s of i){const{id:i}=s.data;if(this.#m.isDeletedAnnotationElement(i))continue;let n=e.get(i);n?(n.resetAnnotationElement(s),n.show(!1),s.show()):(n=t.get(i),n&&(this.#m.addChangedExistingAnnotation(n),n.renderAnnotationElement(s)&&n.show(!1)),s.show())}}this.#Vr(),this.isEmpty&&(this.div.hidden=!0);const{classList:i}=this.div;for(const t of hs.#H.values())i.remove(`${t._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),this.#$r=!1}getEditableAnnotation(t){return this.#Or?.getEditableAnnotation(t)||null}setActiveEditor(t){this.#m.getActive()!==t&&this.#m.setActiveEditor(t)}enableTextSelection(){if(this.div.tabIndex=-1,this.#Wr?.div&&!this.#Gr){this.#Gr=new AbortController;const t=this.#m.combinedSignal(this.#Gr);this.#Wr.div.addEventListener("pointerdown",this.#qr.bind(this),{signal:t}),this.#Wr.div.classList.add("highlighting")}}disableTextSelection(){this.div.tabIndex=0,this.#Wr?.div&&this.#Gr&&(this.#Gr.abort(),this.#Gr=null,this.#Wr.div.classList.remove("highlighting"))}#qr(t){this.#m.unselectAll();const{target:e}=t;if(e===this.#Wr.div||("img"===e.getAttribute("role")||e.classList.contains("endOfContent"))&&this.#Wr.div.contains(e)){const{isMac:e}=O.platform;if(0!==t.button||t.ctrlKey&&e)return;this.#m.showAllEditors("highlight",!0,!0),this.#Wr.div.classList.add("free"),this.toggleDrawing(),rs.startHighlighting(this,"ltr"===this.#m.direction,{target:this.#Wr.div,x:t.x,y:t.y}),this.#Wr.div.addEventListener("pointerup",(()=>{this.#Wr.div.classList.remove("free"),this.toggleDrawing(!0)}),{once:!0,signal:this.#m._signal}),t.preventDefault()}}enableClick(){if(this.#Br)return;this.#Br=new AbortController;const t=this.#m.combinedSignal(this.#Br);this.div.addEventListener("pointerdown",this.pointerdown.bind(this),{signal:t}),this.div.addEventListener("pointerup",this.pointerup.bind(this),{signal:t})}disableClick(){this.#Br?.abort(),this.#Br=null}attach(t){this.#Hr.set(t.id,t);const{annotationElementId:e}=t;e&&this.#m.isDeletedAnnotationElement(e)&&this.#m.removeDeletedAnnotationElement(t)}detach(t){this.#Hr.delete(t.id),this.#Qs?.removePointerInTextLayer(t.contentDiv),!this.#$r&&t.annotationElementId&&this.#m.addDeletedAnnotationElement(t)}remove(t){this.detach(t),this.#m.removeEditor(t),t.div.remove(),t.isAttachedToDOM=!1,this.#Ur||this.addInkEditorIfNeeded(!1)}changeParent(t){t.parent!==this&&(t.parent&&t.annotationElementId&&(this.#m.addDeletedAnnotationElement(t.annotationElementId),kt.deleteAnnotationElement(t),t.annotationElementId=null),this.attach(t),t.parent?.detach(t),t.setParent(this),t.div&&t.isAttachedToDOM&&(t.div.remove(),this.div.append(t.div)))}add(t){if(t.parent!==this||!t.isAttachedToDOM){if(this.changeParent(t),this.#m.addEditor(t),this.attach(t),!t.isAttachedToDOM){const e=t.render();this.div.append(e),t.isAttachedToDOM=!0}t.fixAndSetPosition(),t.onceAdded(),this.#m.addToAnnotationStorage(t),t._reportTelemetry(t.telemetryInitialData)}}moveEditorInDOM(t){if(!t.isAttachedToDOM)return;const{activeElement:e}=document;t.div.contains(e)&&!this.#zr&&(t._focusEventsAllowed=!1,this.#zr=setTimeout((()=>{this.#zr=null,t.div.contains(document.activeElement)?t._focusEventsAllowed=!0:(t.div.addEventListener("focusin",(()=>{t._focusEventsAllowed=!0}),{once:!0,signal:this.#m._signal}),e.focus())}),0)),t._structTreeParentId=this.#Qs?.moveElementInDOM(this.div,t.div,t.contentDiv,!0)}addOrRebuild(t){t.needsToBeRebuilt()?(t.parent||=this,t.rebuild(),t.show()):this.add(t)}addUndoableEditor(t){this.addCommands({cmd:()=>t._uiManager.rebuild(t),undo:()=>{t.remove()},mustExec:!1})}getNextId(){return this.#m.getId()}get#Xr(){return hs.#H.get(this.#m.getMode())}combinedSignal(t){return this.#m.combinedSignal(t)}#Kr(t){const e=this.#Xr;return e?new e.prototype.constructor(t):null}canCreateNewEmptyEditor(){return this.#Xr?.canCreateNewEmptyEditor()}pasteEditor(t,e){this.#m.updateToolbar(t),this.#m.updateMode(t);const{offsetX:i,offsetY:s}=this.#Yr(),n=this.getNextId(),a=this.#Kr({parent:this,id:n,x:i,y:s,uiManager:this.#m,isCentered:!0,...e});a&&this.add(a)}async deserialize(t){return await(hs.#H.get(t.annotationType??t.annotationEditorType)?.deserialize(t,this,this.#m))||null}createAndAddNewEditor(t,e,i={}){const s=this.getNextId(),n=this.#Kr({parent:this,id:s,x:t.offsetX,y:t.offsetY,uiManager:this.#m,isCentered:e,...i});return n&&this.add(n),n}#Yr(){const{x:t,y:e,width:i,height:s}=this.div.getBoundingClientRect(),n=Math.max(0,t),a=Math.max(0,e),r=(n+Math.min(window.innerWidth,t+i))/2-t,o=(a+Math.min(window.innerHeight,e+s))/2-e,[l,h]=this.viewport.rotation%180==0?[r,o]:[o,r];return{offsetX:l,offsetY:h}}addNewEditor(){this.createAndAddNewEditor(this.#Yr(),!0)}setSelected(t){this.#m.setSelected(t)}toggleSelected(t){this.#m.toggleSelected(t)}isSelected(t){return this.#m.isSelected(t)}unselect(t){this.#m.unselect(t)}pointerup(t){const{isMac:e}=O.platform;0!==t.button||t.ctrlKey&&e||t.target===this.div&&this.#jr&&(this.#jr=!1,this.#Nr?this.#m.getMode()!==h.STAMP?this.createAndAddNewEditor(t,!1):this.#m.unselectAll():this.#Nr=!0)}pointerdown(t){if(this.#m.getMode()===h.HIGHLIGHT&&this.enableTextSelection(),this.#jr)return void(this.#jr=!1);const{isMac:e}=O.platform;if(0!==t.button||t.ctrlKey&&e)return;if(t.target!==this.div)return;this.#jr=!0;const i=this.#m.getActive();this.#Nr=!i||i.isEmpty()}findNewParent(t,e,i){const s=this.#m.findParent(e,i);return null!==s&&s!==this&&(s.changeParent(t),!0)}destroy(){this.#m.getActive()?.parent===this&&(this.#m.commitOrRemove(),this.#m.setActiveEditor(null)),this.#zr&&(clearTimeout(this.#zr),this.#zr=null);for(const t of this.#Hr.values())this.#Qs?.removePointerInTextLayer(t.contentDiv),t.setParent(null),t.isAttachedToDOM=!1,t.div.remove();this.div=null,this.#Hr.clear(),this.#m.removeLayer(this)}#Vr(){this.#Ur=!0;for(const t of this.#Hr.values())t.isEmpty()&&t.remove();this.#Ur=!1}render({viewport:t}){this.viewport=t,bt(this.div,t);for(const t of this.#m.getEditors(this.pageIndex))this.add(t),t.rebuild();this.updateMode()}update({viewport:t}){this.#m.commitOrRemove(),this.#Vr();const e=this.viewport.rotation,i=t.rotation;if(this.viewport=t,bt(this.div,{rotation:i}),e!==i)for(const t of this.#Hr.values())t.rotate(i);this.addInkEditorIfNeeded(!1)}get pageDimensions(){const{pageWidth:t,pageHeight:e}=this.viewport.rawDims;return[t,e]}get scale(){return this.#m.viewParameters.realScale}}class ds{#Ps=null;#A=0;#Qr=new Map;#Jr=new Map;constructor({pageIndex:t}){this.pageIndex=t}setParent(t){if(this.#Ps){if(this.#Ps!==t){if(this.#Qr.size>0)for(const e of this.#Qr.values())e.remove(),t.append(e);this.#Ps=t}}else this.#Ps=t}static get _svgFactory(){return E(this,"_svgFactory",new tt)}static#Zr(t,{x:e=0,y:i=0,width:s=1,height:n=1}={}){const{style:a}=t;a.top=100*i+"%",a.left=100*e+"%",a.width=100*s+"%",a.height=100*n+"%"}#to(t){const e=ds._svgFactory.create(1,1,!0);return this.#Ps.append(e),e.setAttribute("aria-hidden",!0),ds.#Zr(e,t),e}#eo(t,e){const i=ds._svgFactory.createElement("clipPath");t.append(i);const s=`clip_${e}`;i.setAttribute("id",s),i.setAttribute("clipPathUnits","objectBoundingBox");const n=ds._svgFactory.createElement("use");return i.append(n),n.setAttribute("href",`#${e}`),n.classList.add("clip"),s}highlight(t,e,i,s=!1){const n=this.#A++,a=this.#to(t.box);a.classList.add("highlight"),t.free&&a.classList.add("free");const r=ds._svgFactory.createElement("defs");a.append(r);const o=ds._svgFactory.createElement("path");r.append(o);const l=`path_p${this.pageIndex}_${n}`;o.setAttribute("id",l),o.setAttribute("d",t.toSVGPath()),s&&this.#Jr.set(n,o);const h=this.#eo(r,l),d=ds._svgFactory.createElement("use");return a.append(d),a.setAttribute("fill",e),a.setAttribute("fill-opacity",i),d.setAttribute("href",`#${l}`),this.#Qr.set(n,a),{id:n,clipPathId:`url(#${h})`}}highlightOutline(t){const e=this.#A++,i=this.#to(t.box);i.classList.add("highlightOutline");const s=ds._svgFactory.createElement("defs");i.append(s);const n=ds._svgFactory.createElement("path");s.append(n);const a=`path_p${this.pageIndex}_${e}`;let r;if(n.setAttribute("id",a),n.setAttribute("d",t.toSVGPath()),n.setAttribute("vector-effect","non-scaling-stroke"),t.free){i.classList.add("free");const t=ds._svgFactory.createElement("mask");s.append(t),r=`mask_p${this.pageIndex}_${e}`,t.setAttribute("id",r),t.setAttribute("maskUnits","objectBoundingBox");const n=ds._svgFactory.createElement("rect");t.append(n),n.setAttribute("width","1"),n.setAttribute("height","1"),n.setAttribute("fill","white");const o=ds._svgFactory.createElement("use");t.append(o),o.setAttribute("href",`#${a}`),o.setAttribute("stroke","none"),o.setAttribute("fill","black"),o.setAttribute("fill-rule","nonzero"),o.classList.add("mask")}const o=ds._svgFactory.createElement("use");i.append(o),o.setAttribute("href",`#${a}`),r&&o.setAttribute("mask",`url(#${r})`);const l=o.cloneNode();return i.append(l),o.classList.add("mainOutline"),l.classList.add("secondaryOutline"),this.#Qr.set(e,i),e}finalizeLine(t,e){const i=this.#Jr.get(t);this.#Jr.delete(t),this.updateBox(t,e.box),i.setAttribute("d",e.toSVGPath())}updateLine(t,e){this.#Qr.get(t).firstChild.firstChild.setAttribute("d",e.toSVGPath())}removeFreeHighlight(t){this.remove(t),this.#Jr.delete(t)}updatePath(t,e){this.#Jr.get(t).setAttribute("d",e.toSVGPath())}updateBox(t,e){ds.#Zr(this.#Qr.get(t),e)}show(t,e){this.#Qr.get(t).classList.toggle("hidden",!e)}rotate(t,e){this.#Qr.get(t).setAttribute("data-main-rotation",e)}changeColor(t,e){this.#Qr.get(t).setAttribute("fill",e)}changeOpacity(t,e){this.#Qr.get(t).setAttribute("fill-opacity",e)}addClass(t,e){this.#Qr.get(t).classList.add(e)}removeClass(t,e){this.#Qr.get(t).classList.remove(e)}getSVGRoot(t){return this.#Qr.get(t)}remove(t){null!==this.#Ps&&(this.#Qr.get(t).remove(),this.#Qr.delete(t))}destroy(){this.#Ps=null;for(const t of this.#Qr.values())t.remove();this.#Qr.clear()}}var cs=e.AbortException,us=e.AnnotationEditorLayer,ps=e.AnnotationEditorParamsType,gs=e.AnnotationEditorType,ms=e.AnnotationEditorUIManager,fs=e.AnnotationLayer,bs=e.AnnotationMode,vs=e.CMapCompressionType,As=e.ColorPicker,ys=e.DOMSVGFactory,ws=e.DrawLayer,_s=e.FeatureTest,xs=e.GlobalWorkerOptions,Cs=e.ImageKind,Es=e.InvalidPDFException,Ss=e.MissingPDFException,Ts=e.OPS,Ms=e.OutputScale,ks=e.PDFDataRangeTransport,Is=e.PDFDateString,Ps=e.PDFWorker,Rs=e.PasswordResponses,Ds=e.PermissionFlag,Ls=e.PixelsPerInch,Fs=e.RenderingCancelledException,Ns=e.TextLayer,Os=e.UnexpectedResponseException,Bs=e.Util,zs=e.VerbosityLevel,Hs=e.XfaLayer,js=e.build,Us=e.createValidAbsoluteUrl,$s=e.fetchData,Ws=e.getDocument,Gs=e.getFilenameFromUrl,Vs=e.getPdfFilenameFromUrl,qs=e.getXfaPageViewport,Xs=e.isDataScheme,Ks=e.isPdfFile,Ys=e.noContextMenu,Qs=e.normalizeUnicode,Js=e.setLayerDimensions,Zs=e.shadow,tn=e.version;"undefined"!=typeof window&&"Worker"in window&&(xs.workerPort=new Worker(new URL(i.p+i.u(13),i.b),{type:void 0}))}}]); \ No newline at end of file +/*! For license information please see 840.index.js.LICENSE.txt */ +"use strict";(self.webpackChunkFileViewer=self.webpackChunkFileViewer||[]).push([[840],{560:(t,e,i)=>{i.r(e),i.d(e,{AbortException:()=>cs,AnnotationEditorLayer:()=>us,AnnotationEditorParamsType:()=>ps,AnnotationEditorType:()=>gs,AnnotationEditorUIManager:()=>ms,AnnotationLayer:()=>fs,AnnotationMode:()=>bs,CMapCompressionType:()=>vs,ColorPicker:()=>As,DOMSVGFactory:()=>ys,DrawLayer:()=>ws,FeatureTest:()=>_s,GlobalWorkerOptions:()=>xs,ImageKind:()=>Cs,InvalidPDFException:()=>Es,MissingPDFException:()=>Ss,OPS:()=>Ts,OutputScale:()=>Ms,PDFDataRangeTransport:()=>ks,PDFDateString:()=>Is,PDFWorker:()=>Ps,PasswordResponses:()=>Rs,PermissionFlag:()=>Ds,PixelsPerInch:()=>Ls,RenderingCancelledException:()=>Fs,TextLayer:()=>Ns,UnexpectedResponseException:()=>Os,Util:()=>Bs,VerbosityLevel:()=>zs,XfaLayer:()=>Hs,build:()=>js,createValidAbsoluteUrl:()=>Us,fetchData:()=>$s,getDocument:()=>Ws,getFilenameFromUrl:()=>Gs,getPdfFilenameFromUrl:()=>Vs,getXfaPageViewport:()=>qs,isDataScheme:()=>Xs,isPdfFile:()=>Ks,noContextMenu:()=>Ys,normalizeUnicode:()=>Qs,setLayerDimensions:()=>Js,shadow:()=>Zs,version:()=>tn});var s={d:(t,e)=>{for(var i in e)s.o(e,i)&&!s.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e)};e=globalThis.pdfjsLib={},s.d(e,{AbortException:()=>D,AnnotationEditorLayer:()=>hs,AnnotationEditorParamsType:()=>d,AnnotationEditorType:()=>h,AnnotationEditorUIManager:()=>Tt,AnnotationLayer:()=>Qi,AnnotationMode:()=>l,CMapCompressionType:()=>g,ColorPicker:()=>as,DOMSVGFactory:()=>tt,DrawLayer:()=>ds,FeatureTest:()=>O,GlobalWorkerOptions:()=>fe,ImageKind:()=>u,InvalidPDFException:()=>k,MissingPDFException:()=>I,OPS:()=>m,OutputScale:()=>vt,PDFDataRangeTransport:()=>ai,PDFDateString:()=>ut,PDFWorker:()=>hi,PasswordResponses:()=>f,PermissionFlag:()=>c,PixelsPerInch:()=>Y,RenderingCancelledException:()=>it,TextLayer:()=>Ye,UnexpectedResponseException:()=>P,Util:()=>z,VerbosityLevel:()=>p,XfaLayer:()=>yi,build:()=>fi,createValidAbsoluteUrl:()=>C,fetchData:()=>Q,getDocument:()=>ii,getFilenameFromUrl:()=>at,getPdfFilenameFromUrl:()=>rt,getXfaPageViewport:()=>pt,isDataScheme:()=>st,isPdfFile:()=>nt,noContextMenu:()=>ht,normalizeUnicode:()=>U,setLayerDimensions:()=>bt,shadow:()=>E,version:()=>mi});const n=!("object"!=typeof process||process+""!="[object process]"||process.versions.nw||process.versions.electron&&process.type&&"browser"!==process.type),a=[1,0,0,1,0,0],r=[.001,0,0,.001,0,0],o=1.35,l={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},h={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15},d={RESIZE:1,CREATE:2,FREETEXT_SIZE:11,FREETEXT_COLOR:12,FREETEXT_OPACITY:13,INK_COLOR:21,INK_THICKNESS:22,INK_OPACITY:23,HIGHLIGHT_COLOR:31,HIGHLIGHT_DEFAULT_COLOR:32,HIGHLIGHT_THICKNESS:33,HIGHLIGHT_FREE:34,HIGHLIGHT_SHOW_ALL:35},c={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},u={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},p={ERRORS:0,WARNINGS:1,INFOS:5},g={NONE:0,BINARY:1},m={dependency:1,setLineWidth:2,setLineCap:3,setLineJoin:4,setMiterLimit:5,setDash:6,setRenderingIntent:7,setFlatness:8,setGState:9,save:10,restore:11,transform:12,moveTo:13,lineTo:14,curveTo:15,curveTo2:16,curveTo3:17,closePath:18,rectangle:19,stroke:20,closeStroke:21,fill:22,eoFill:23,fillStroke:24,eoFillStroke:25,closeFillStroke:26,closeEOFillStroke:27,endPath:28,clip:29,eoClip:30,beginText:31,endText:32,setCharSpacing:33,setWordSpacing:34,setHScale:35,setLeading:36,setFont:37,setTextRenderingMode:38,setTextRise:39,moveText:40,setLeadingMoveText:41,setTextMatrix:42,nextLine:43,showText:44,showSpacedText:45,nextLineShowText:46,nextLineSetSpacingShowText:47,setCharWidth:48,setCharWidthAndBounds:49,setStrokeColorSpace:50,setFillColorSpace:51,setStrokeColor:52,setStrokeColorN:53,setFillColor:54,setFillColorN:55,setStrokeGray:56,setFillGray:57,setStrokeRGBColor:58,setFillRGBColor:59,setStrokeCMYKColor:60,setFillCMYKColor:61,shadingFill:62,beginInlineImage:63,beginImageData:64,endInlineImage:65,paintXObject:66,markPoint:67,markPointProps:68,beginMarkedContent:69,beginMarkedContentProps:70,endMarkedContent:71,beginCompat:72,endCompat:73,paintFormXObjectBegin:74,paintFormXObjectEnd:75,beginGroup:76,endGroup:77,beginAnnotation:80,endAnnotation:81,paintImageMaskXObject:83,paintImageMaskXObjectGroup:84,paintImageXObject:85,paintInlineImageXObject:86,paintInlineImageXObjectGroup:87,paintImageXObjectRepeat:88,paintImageMaskXObjectRepeat:89,paintSolidColorImageMask:90,constructPath:91,setStrokeTransparent:92,setFillTransparent:93},f={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let b=p.WARNINGS;function v(t){Number.isInteger(t)&&(b=t)}function A(){return b}function y(t){b>=p.INFOS&&console.log(`Info: ${t}`)}function w(t){b>=p.WARNINGS&&console.log(`Warning: ${t}`)}function _(t){throw new Error(t)}function x(t,e){t||_(e)}function C(t,e=null,i=null){if(!t)return null;try{if(i&&"string"==typeof t&&(i.addDefaultProtocol&&t.startsWith("www.")&&t.match(/\./g)?.length>=2&&(t=`http://${t}`),i.tryConvertEncoding))try{t=decodeURIComponent(escape(t))}catch{}const s=e?new URL(t,e):new URL(t);if(function(t){switch(t?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}(s))return s}catch{}return null}function E(t,e,i,s=!1){return Object.defineProperty(t,e,{value:i,enumerable:!s,configurable:!0,writable:!1}),i}const S=function(){function t(t,e){this.message=t,this.name=e}return t.prototype=new Error,t.constructor=t,t}();class T extends S{constructor(t,e){super(t,"PasswordException"),this.code=e}}class M extends S{constructor(t,e){super(t,"UnknownErrorException"),this.details=e}}class k extends S{constructor(t){super(t,"InvalidPDFException")}}class I extends S{constructor(t){super(t,"MissingPDFException")}}class P extends S{constructor(t,e){super(t,"UnexpectedResponseException"),this.status=e}}class R extends S{constructor(t){super(t,"FormatError")}}class D extends S{constructor(t){super(t,"AbortException")}}function L(t){"object"==typeof t&&void 0!==t?.length||_("Invalid argument for bytesToString");const e=t.length,i=8192;if(et.toString(16).padStart(2,"0")));class z{static makeHexColor(t,e,i){return`#${B[t]}${B[e]}${B[i]}`}static scaleMinMax(t,e){let i;t[0]?(t[0]<0&&(i=e[0],e[0]=e[2],e[2]=i),e[0]*=t[0],e[2]*=t[0],t[3]<0&&(i=e[1],e[1]=e[3],e[3]=i),e[1]*=t[3],e[3]*=t[3]):(i=e[0],e[0]=e[1],e[1]=i,i=e[2],e[2]=e[3],e[3]=i,t[1]<0&&(i=e[1],e[1]=e[3],e[3]=i),e[1]*=t[1],e[3]*=t[1],t[2]<0&&(i=e[0],e[0]=e[2],e[2]=i),e[0]*=t[2],e[2]*=t[2]),e[0]+=t[4],e[1]+=t[5],e[2]+=t[4],e[3]+=t[5]}static transform(t,e){return[t[0]*e[0]+t[2]*e[1],t[1]*e[0]+t[3]*e[1],t[0]*e[2]+t[2]*e[3],t[1]*e[2]+t[3]*e[3],t[0]*e[4]+t[2]*e[5]+t[4],t[1]*e[4]+t[3]*e[5]+t[5]]}static applyTransform(t,e){return[t[0]*e[0]+t[1]*e[2]+e[4],t[0]*e[1]+t[1]*e[3]+e[5]]}static applyInverseTransform(t,e){const i=e[0]*e[3]-e[1]*e[2];return[(t[0]*e[3]-t[1]*e[2]+e[2]*e[5]-e[4]*e[3])/i,(-t[0]*e[1]+t[1]*e[0]+e[4]*e[1]-e[5]*e[0])/i]}static getAxialAlignedBoundingBox(t,e){const i=this.applyTransform(t,e),s=this.applyTransform(t.slice(2,4),e),n=this.applyTransform([t[0],t[3]],e),a=this.applyTransform([t[2],t[1]],e);return[Math.min(i[0],s[0],n[0],a[0]),Math.min(i[1],s[1],n[1],a[1]),Math.max(i[0],s[0],n[0],a[0]),Math.max(i[1],s[1],n[1],a[1])]}static inverseTransform(t){const e=t[0]*t[3]-t[1]*t[2];return[t[3]/e,-t[1]/e,-t[2]/e,t[0]/e,(t[2]*t[5]-t[4]*t[3])/e,(t[4]*t[1]-t[5]*t[0])/e]}static singularValueDecompose2dScale(t){const e=[t[0],t[2],t[1],t[3]],i=t[0]*e[0]+t[1]*e[2],s=t[0]*e[1]+t[1]*e[3],n=t[2]*e[0]+t[3]*e[2],a=t[2]*e[1]+t[3]*e[3],r=(i+a)/2,o=Math.sqrt((i+a)**2-4*(i*a-n*s))/2,l=r+o||1,h=r-o||1;return[Math.sqrt(l),Math.sqrt(h)]}static normalizeRect(t){const e=t.slice(0);return t[0]>t[2]&&(e[0]=t[2],e[2]=t[0]),t[1]>t[3]&&(e[1]=t[3],e[3]=t[1]),e}static intersect(t,e){const i=Math.max(Math.min(t[0],t[2]),Math.min(e[0],e[2])),s=Math.min(Math.max(t[0],t[2]),Math.max(e[0],e[2]));if(i>s)return null;const n=Math.max(Math.min(t[1],t[3]),Math.min(e[1],e[3])),a=Math.min(Math.max(t[1],t[3]),Math.max(e[1],e[3]));return n>a?null:[i,n,s,a]}static#t(t,e,i,s,n,a,r,o,l,h){if(l<=0||l>=1)return;const d=1-l,c=l*l,u=c*l,p=d*(d*(d*t+3*l*e)+3*c*i)+u*s,g=d*(d*(d*n+3*l*a)+3*c*r)+u*o;h[0]=Math.min(h[0],p),h[1]=Math.min(h[1],g),h[2]=Math.max(h[2],p),h[3]=Math.max(h[3],g)}static#e(t,e,i,s,n,a,r,o,l,h,d,c){if(Math.abs(l)<1e-12)return void(Math.abs(h)>=1e-12&&this.#t(t,e,i,s,n,a,r,o,-d/h,c));const u=h**2-4*d*l;if(u<0)return;const p=Math.sqrt(u),g=2*l;this.#t(t,e,i,s,n,a,r,o,(-h+p)/g,c),this.#t(t,e,i,s,n,a,r,o,(-h-p)/g,c)}static bezierBoundingBox(t,e,i,s,n,a,r,o,l){return l?(l[0]=Math.min(l[0],t,r),l[1]=Math.min(l[1],e,o),l[2]=Math.max(l[2],t,r),l[3]=Math.max(l[3],e,o)):l=[Math.min(t,r),Math.min(e,o),Math.max(t,r),Math.max(e,o)],this.#e(t,i,n,r,e,s,a,o,3*(3*(i-n)-t+r),6*(t-2*i+n),3*(i-t),l),this.#e(t,i,n,r,e,s,a,o,3*(3*(s-a)-e+o),6*(e-2*s+a),3*(s-e),l),l}}let H=null,j=null;function U(t){return H||(H=/([\u00a0\u00b5\u037e\u0eb3\u2000-\u200a\u202f\u2126\ufb00-\ufb04\ufb06\ufb20-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufba1\ufba4-\ufba9\ufbae-\ufbb1\ufbd3-\ufbdc\ufbde-\ufbe7\ufbea-\ufbf8\ufbfc-\ufbfd\ufc00-\ufc5d\ufc64-\ufcf1\ufcf5-\ufd3d\ufd88\ufdf4\ufdfa-\ufdfb\ufe71\ufe77\ufe79\ufe7b\ufe7d]+)|(\ufb05+)/gu,j=new Map([["ſt","ſt"]])),t.replaceAll(H,((t,e,i)=>e?e.normalize("NFKC"):j.get(i)))}const $="pdfjs_internal_id_";class W{addFilter(t){return"none"}addHCMFilter(t,e){return"none"}addAlphaFilter(t){return"none"}addLuminosityFilter(t){return"none"}addHighlightHCMFilter(t,e,i,s,n){return"none"}destroy(t=!1){}}class G{#i=!1;constructor({enableHWA:t=!1}){this.#i=t}create(t,e){if(t<=0||e<=0)throw new Error("Invalid canvas size");const i=this._createCanvas(t,e);return{canvas:i,context:i.getContext("2d",{willReadFrequently:!this.#i})}}reset(t,e,i){if(!t.canvas)throw new Error("Canvas is not specified");if(e<=0||i<=0)throw new Error("Invalid canvas size");t.canvas.width=e,t.canvas.height=i}destroy(t){if(!t.canvas)throw new Error("Canvas is not specified");t.canvas.width=0,t.canvas.height=0,t.canvas=null,t.context=null}_createCanvas(t,e){_("Abstract method `_createCanvas` called.")}}class V{constructor({baseUrl:t=null,isCompressed:e=!0}){this.baseUrl=t,this.isCompressed=e}async fetch({name:t}){if(!this.baseUrl)throw new Error("Ensure that the `cMapUrl` and `cMapPacked` API parameters are provided.");if(!t)throw new Error("CMap name must be specified.");const e=this.baseUrl+t+(this.isCompressed?".bcmap":""),i=this.isCompressed?g.BINARY:g.NONE;return this._fetchData(e,i).catch((t=>{throw new Error(`Unable to load ${this.isCompressed?"binary ":""}CMap at: ${e}`)}))}_fetchData(t,e){_("Abstract method `_fetchData` called.")}}class q{constructor({baseUrl:t=null}){this.baseUrl=t}async fetch({filename:t}){if(!this.baseUrl)throw new Error("Ensure that the `standardFontDataUrl` API parameter is provided.");if(!t)throw new Error("Font filename must be specified.");const e=`${this.baseUrl}${t}`;return this._fetchData(e).catch((t=>{throw new Error(`Unable to load font data at: ${e}`)}))}_fetchData(t){_("Abstract method `_fetchData` called.")}}class X{create(t,e,i=!1){if(t<=0||e<=0)throw new Error("Invalid SVG dimensions");const s=this._createSVG("svg:svg");return s.setAttribute("version","1.1"),i||(s.setAttribute("width",`${t}px`),s.setAttribute("height",`${e}px`)),s.setAttribute("preserveAspectRatio","none"),s.setAttribute("viewBox",`0 0 ${t} ${e}`),s}createElement(t){if("string"!=typeof t)throw new Error("Invalid SVG element type");return this._createSVG(t)}_createSVG(t){_("Abstract method `_createSVG` called.")}}const K="http://www.w3.org/2000/svg";class Y{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF}async function Q(t,e="text"){if(lt(t,document.baseURI)){const i=await fetch(t);if(!i.ok)throw new Error(i.statusText);switch(e){case"arraybuffer":return i.arrayBuffer();case"blob":return i.blob();case"json":return i.json()}return i.text()}return new Promise(((i,s)=>{const n=new XMLHttpRequest;n.open("GET",t,!0),n.responseType=e,n.onreadystatechange=()=>{if(n.readyState===XMLHttpRequest.DONE)if(200!==n.status&&0!==n.status)s(new Error(n.statusText));else{switch(e){case"arraybuffer":case"blob":case"json":return void i(n.response)}i(n.responseText)}},n.send(null)}))}class J extends V{_fetchData(t,e){return Q(t,this.isCompressed?"arraybuffer":"text").then((t=>({cMapData:t instanceof ArrayBuffer?new Uint8Array(t):F(t),compressionType:e})))}}class Z extends q{_fetchData(t){return Q(t,"arraybuffer").then((t=>new Uint8Array(t)))}}class tt extends X{_createSVG(t){return document.createElementNS(K,t)}}class et{constructor({viewBox:t,scale:e,rotation:i,offsetX:s=0,offsetY:n=0,dontFlip:a=!1}){this.viewBox=t,this.scale=e,this.rotation=i,this.offsetX=s,this.offsetY=n;const r=(t[2]+t[0])/2,o=(t[3]+t[1])/2;let l,h,d,c,u,p,g,m;switch((i%=360)<0&&(i+=360),i){case 180:l=-1,h=0,d=0,c=1;break;case 90:l=0,h=1,d=1,c=0;break;case 270:l=0,h=-1,d=-1,c=0;break;case 0:l=1,h=0,d=0,c=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}a&&(d=-d,c=-c),0===l?(u=Math.abs(o-t[1])*e+s,p=Math.abs(r-t[0])*e+n,g=(t[3]-t[1])*e,m=(t[2]-t[0])*e):(u=Math.abs(r-t[0])*e+s,p=Math.abs(o-t[1])*e+n,g=(t[2]-t[0])*e,m=(t[3]-t[1])*e),this.transform=[l*e,h*e,d*e,c*e,u-l*e*r-d*e*o,p-h*e*r-c*e*o],this.width=g,this.height=m}get rawDims(){const{viewBox:t}=this;return E(this,"rawDims",{pageWidth:t[2]-t[0],pageHeight:t[3]-t[1],pageX:t[0],pageY:t[1]})}clone({scale:t=this.scale,rotation:e=this.rotation,offsetX:i=this.offsetX,offsetY:s=this.offsetY,dontFlip:n=!1}={}){return new et({viewBox:this.viewBox.slice(),scale:t,rotation:e,offsetX:i,offsetY:s,dontFlip:n})}convertToViewportPoint(t,e){return z.applyTransform([t,e],this.transform)}convertToViewportRectangle(t){const e=z.applyTransform([t[0],t[1]],this.transform),i=z.applyTransform([t[2],t[3]],this.transform);return[e[0],e[1],i[0],i[1]]}convertToPdfPoint(t,e){return z.applyInverseTransform([t,e],this.transform)}}class it extends S{constructor(t,e=0){super(t,"RenderingCancelledException"),this.extraDelay=e}}function st(t){const e=t.length;let i=0;for(;i=1&&s<=12?s-1:0;let n=parseInt(e[3],10);n=n>=1&&n<=31?n:1;let a=parseInt(e[4],10);a=a>=0&&a<=23?a:0;let r=parseInt(e[5],10);r=r>=0&&r<=59?r:0;let o=parseInt(e[6],10);o=o>=0&&o<=59?o:0;const l=e[7]||"Z";let h=parseInt(e[8],10);h=h>=0&&h<=23?h:0;let d=parseInt(e[9],10)||0;return d=d>=0&&d<=59?d:0,"-"===l?(a+=h,r+=d):"+"===l&&(a-=h,r-=d),new Date(Date.UTC(i,s,n,a,r,o))}}function pt(t,{scale:e=1,rotation:i=0}){const{width:s,height:n}=t.attributes.style,a=[0,0,parseInt(s),parseInt(n)];return new et({viewBox:a,scale:e,rotation:i})}function gt(t){if(t.startsWith("#")){const e=parseInt(t.slice(1),16);return[(16711680&e)>>16,(65280&e)>>8,255&e]}return t.startsWith("rgb(")?t.slice(4,-1).split(",").map((t=>parseInt(t))):t.startsWith("rgba(")?t.slice(5,-1).split(",").map((t=>parseInt(t))).slice(0,3):(w(`Not a valid color format: "${t}"`),[0,0,0])}function mt(t){const{a:e,b:i,c:s,d:n,e:a,f:r}=t.getTransform();return[e,i,s,n,a,r]}function ft(t){const{a:e,b:i,c:s,d:n,e:a,f:r}=t.getTransform().invertSelf();return[e,i,s,n,a,r]}function bt(t,e,i=!1,s=!0){if(e instanceof et){const{pageWidth:s,pageHeight:n}=e.rawDims,{style:a}=t,r=O.isCSSRoundSupported,o=`var(--scale-factor) * ${s}px`,l=`var(--scale-factor) * ${n}px`,h=r?`round(down, ${o}, var(--scale-round-x, 1px))`:`calc(${o})`,d=r?`round(down, ${l}, var(--scale-round-y, 1px))`:`calc(${l})`;i&&e.rotation%180!=0?(a.width=d,a.height=h):(a.width=h,a.height=d)}s&&t.setAttribute("data-main-rotation",e.rotation)}class vt{constructor(){const t=window.devicePixelRatio||1;this.sx=t,this.sy=t}get scaled(){return 1!==this.sx||1!==this.sy}get symmetric(){return this.sx===this.sy}}class At{#s=null;#n=null;#a;#r=null;#o=null;static#l=null;constructor(t){this.#a=t,At.#l||=Object.freeze({freetext:"pdfjs-editor-remove-freetext-button",highlight:"pdfjs-editor-remove-highlight-button",ink:"pdfjs-editor-remove-ink-button",stamp:"pdfjs-editor-remove-stamp-button"})}render(){const t=this.#s=document.createElement("div");t.classList.add("editToolbar","hidden"),t.setAttribute("role","toolbar");const e=this.#a._uiManager._signal;t.addEventListener("contextmenu",ht,{signal:e}),t.addEventListener("pointerdown",At.#h,{signal:e});const i=this.#r=document.createElement("div");i.className="buttons",t.append(i);const s=this.#a.toolbarPosition;if(s){const{style:e}=t,i="ltr"===this.#a._uiManager.direction?1-s[0]:s[0];e.insetInlineEnd=100*i+"%",e.top=`calc(${100*s[1]}% + var(--editor-toolbar-vert-offset))`}return this.#d(),t}get div(){return this.#s}static#h(t){t.stopPropagation()}#c(t){this.#a._focusEventsAllowed=!1,t.preventDefault(),t.stopPropagation()}#u(t){this.#a._focusEventsAllowed=!0,t.preventDefault(),t.stopPropagation()}#p(t){const e=this.#a._uiManager._signal;t.addEventListener("focusin",this.#c.bind(this),{capture:!0,signal:e}),t.addEventListener("focusout",this.#u.bind(this),{capture:!0,signal:e}),t.addEventListener("contextmenu",ht,{signal:e})}hide(){this.#s.classList.add("hidden"),this.#n?.hideDropdown()}show(){this.#s.classList.remove("hidden"),this.#o?.shown()}#d(){const{editorType:t,_uiManager:e}=this.#a,i=document.createElement("button");i.className="delete",i.tabIndex=0,i.setAttribute("data-l10n-id",At.#l[t]),this.#p(i),i.addEventListener("click",(t=>{e.delete()}),{signal:e._signal}),this.#r.append(i)}get#g(){const t=document.createElement("div");return t.className="divider",t}async addAltText(t){const e=await t.render();this.#p(e),this.#r.prepend(e,this.#g),this.#o=t}addColorPicker(t){this.#n=t;const e=t.renderButton();this.#p(e),this.#r.prepend(e,this.#g)}remove(){this.#s.remove(),this.#n?.destroy(),this.#n=null}}class yt{#r=null;#s=null;#m;constructor(t){this.#m=t}#f(){const t=this.#s=document.createElement("div");t.className="editToolbar",t.setAttribute("role","toolbar"),t.addEventListener("contextmenu",ht,{signal:this.#m._signal});const e=this.#r=document.createElement("div");return e.className="buttons",t.append(e),this.#b(),t}#v(t,e){let i=0,s=0;for(const n of t){const t=n.y+n.height;if(ti?(s=a,i=t):e?a>s&&(s=a):a{this.#m.highlightSelection("floating_button")}),{signal:i}),this.#r.append(t)}}function wt(t,e,i){for(const s of i)e.addEventListener(s,t[s].bind(t))}class _t{#A=0;get id(){return"pdfjs_internal_editor_"+this.#A++}}class xt{#y=function(){if("undefined"!=typeof crypto&&"function"==typeof crypto?.randomUUID)return crypto.randomUUID();const t=new Uint8Array(32);if("undefined"!=typeof crypto&&"function"==typeof crypto?.getRandomValues)crypto.getRandomValues(t);else for(let e=0;e<32;e++)t[e]=Math.floor(255*Math.random());return L(t)}();#A=0;#w=null;static get _isSVGFittingCanvas(){const t=new OffscreenCanvas(1,3).getContext("2d",{willReadFrequently:!0}),e=new Image;return e.src='data:image/svg+xml;charset=UTF-8,',E(this,"_isSVGFittingCanvas",e.decode().then((()=>(t.drawImage(e,0,0,1,1,0,0,1,3),0===new Uint32Array(t.getImageData(0,0,1,1).data.buffer)[0]))))}async#_(t,e){this.#w||=new Map;let i=this.#w.get(t);if(null===i)return null;if(i?.bitmap)return i.refCounter+=1,i;try{let t;if(i||={bitmap:null,id:`image_${this.#y}_${this.#A++}`,refCounter:0,isSvg:!1},"string"==typeof e?(i.url=e,t=await Q(e,"blob")):e instanceof File?t=i.file=e:e instanceof Blob&&(t=e),"image/svg+xml"===t.type){const e=xt._isSVGFittingCanvas,s=new FileReader,n=new Image,a=new Promise(((t,a)=>{n.onload=()=>{i.bitmap=n,i.isSvg=!0,t()},s.onload=async()=>{const t=i.svgUrl=s.result;n.src=await e?`${t}#svgView(preserveAspectRatio(none))`:t},n.onerror=s.onerror=a}));s.readAsDataURL(t),await a}else i.bitmap=await createImageBitmap(t);i.refCounter=1}catch(t){console.error(t),i=null}return this.#w.set(t,i),i&&this.#w.set(i.id,i),i}async getFromFile(t){const{lastModified:e,name:i,size:s,type:n}=t;return this.#_(`${e}_${i}_${s}_${n}`,t)}async getFromUrl(t){return this.#_(t,t)}async getFromBlob(t,e){const i=await e;return this.#_(t,i)}async getFromId(t){this.#w||=new Map;const e=this.#w.get(t);if(!e)return null;if(e.bitmap)return e.refCounter+=1,e;if(e.file)return this.getFromFile(e.file);if(e.blobPromise){const{blobPromise:t}=e;return delete e.blobPromise,this.getFromBlob(e.id,t)}return this.getFromUrl(e.url)}getFromCanvas(t,e){this.#w||=new Map;let i=this.#w.get(t);if(i?.bitmap)return i.refCounter+=1,i;const s=new OffscreenCanvas(e.width,e.height);return s.getContext("2d").drawImage(e,0,0),i={bitmap:s.transferToImageBitmap(),id:`image_${this.#y}_${this.#A++}`,refCounter:1,isSvg:!1},this.#w.set(t,i),this.#w.set(i.id,i),i}getSvgUrl(t){const e=this.#w.get(t);return e?.isSvg?e.svgUrl:null}deleteId(t){this.#w||=new Map;const e=this.#w.get(t);if(!e)return;if(e.refCounter-=1,0!==e.refCounter)return;const{bitmap:i}=e;if(!e.url&&!e.file){const t=new OffscreenCanvas(i.width,i.height);t.getContext("bitmaprenderer").transferFromImageBitmap(i),e.blobPromise=t.convertToBlob()}i.close?.(),e.bitmap=null}isValidId(t){return t.startsWith(`image_${this.#y}_`)}}class Ct{#x=[];#C=!1;#E;#S=-1;constructor(t=128){this.#E=t}add({cmd:t,undo:e,post:i,mustExec:s,type:n=NaN,overwriteIfSameType:a=!1,keepUndo:r=!1}){if(s&&t(),this.#C)return;const o={cmd:t,undo:e,post:i,type:n};if(-1===this.#S)return this.#x.length>0&&(this.#x.length=0),this.#S=0,void this.#x.push(o);if(a&&this.#x[this.#S].type===n)return r&&(o.undo=this.#x[this.#S].undo),void(this.#x[this.#S]=o);const l=this.#S+1;l===this.#E?this.#x.splice(0,1):(this.#S=l,lt===e[i])))return St._colorsMapping.get(t);return e}getHexCode(t){const e=this._colors.get(t);return e?z.makeHexColor(...e):t}}class Tt{#M=new AbortController;#k=null;#I=new Map;#P=new Map;#R=null;#D=null;#L=null;#F=new Ct;#N=null;#O=0;#B=new Set;#z=null;#H=null;#j=new Set;#U=!1;#$=!1;#W=!1;#G=null;#V=null;#q=null;#X=null;#K=!1;#Y=null;#Q=new _t;#J=!1;#Z=!1;#tt=null;#et=null;#it=null;#st=null;#nt=h.NONE;#at=new Set;#rt=null;#ot=null;#lt=null;#ht={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1};#dt=[0,0];#ct=null;#ut=null;#pt=null;#gt=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){const t=Tt.prototype,e=t=>t.#ut.contains(document.activeElement)&&"BUTTON"!==document.activeElement.tagName&&t.hasSomethingToControl(),i=(t,{target:e})=>{if(e instanceof HTMLInputElement){const{type:t}=e;return"text"!==t&&"number"!==t}return!0},s=this.TRANSLATE_SMALL,n=this.TRANSLATE_BIG;return E(this,"_keyboardManager",new Et([[["ctrl+a","mac+meta+a"],t.selectAll,{checker:i}],[["ctrl+z","mac+meta+z"],t.undo,{checker:i}],[["ctrl+y","ctrl+shift+z","mac+meta+shift+z","ctrl+shift+Z","mac+meta+shift+Z"],t.redo,{checker:i}],[["Backspace","alt+Backspace","ctrl+Backspace","shift+Backspace","mac+Backspace","mac+alt+Backspace","mac+ctrl+Backspace","Delete","ctrl+Delete","shift+Delete","mac+Delete"],t.delete,{checker:i}],[["Enter","mac+Enter"],t.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#ut.contains(e)&&!t.isEnterHandled}],[[" ","mac+ "],t.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#ut.contains(document.activeElement)}],[["Escape","mac+Escape"],t.unselectAll],[["ArrowLeft","mac+ArrowLeft"],t.translateSelectedEditors,{args:[-s,0],checker:e}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t.translateSelectedEditors,{args:[-n,0],checker:e}],[["ArrowRight","mac+ArrowRight"],t.translateSelectedEditors,{args:[s,0],checker:e}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t.translateSelectedEditors,{args:[n,0],checker:e}],[["ArrowUp","mac+ArrowUp"],t.translateSelectedEditors,{args:[0,-s],checker:e}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t.translateSelectedEditors,{args:[0,-n],checker:e}],[["ArrowDown","mac+ArrowDown"],t.translateSelectedEditors,{args:[0,s],checker:e}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t.translateSelectedEditors,{args:[0,n],checker:e}]]))}constructor(t,e,i,s,n,a,r,o,l,h,d){const c=this._signal=this.#M.signal;this.#ut=t,this.#pt=e,this.#R=i,this._eventBus=s,s._on("editingaction",this.onEditingAction.bind(this),{signal:c}),s._on("pagechanging",this.onPageChanging.bind(this),{signal:c}),s._on("scalechanging",this.onScaleChanging.bind(this),{signal:c}),s._on("rotationchanging",this.onRotationChanging.bind(this),{signal:c}),s._on("setpreference",this.onSetPreference.bind(this),{signal:c}),s._on("switchannotationeditorparams",(t=>this.updateParams(t.type,t.value)),{signal:c}),this.#mt(),this.#ft(),this.#bt(),this.#D=n.annotationStorage,this.#G=n.filterFactory,this.#ot=a,this.#X=r||null,this.#U=o,this.#$=l,this.#W=h,this.#st=d||null,this.viewParameters={realScale:Y.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1}destroy(){this.#gt?.resolve(),this.#gt=null,this.#M?.abort(),this.#M=null,this._signal=null;for(const t of this.#P.values())t.destroy();this.#P.clear(),this.#I.clear(),this.#j.clear(),this.#k=null,this.#at.clear(),this.#F.destroy(),this.#R?.destroy(),this.#Y?.hide(),this.#Y=null,this.#V&&(clearTimeout(this.#V),this.#V=null),this.#ct&&(clearTimeout(this.#ct),this.#ct=null)}combinedSignal(t){return AbortSignal.any([this._signal,t.signal])}get mlManager(){return this.#st}get useNewAltTextFlow(){return this.#$}get useNewAltTextWhenAddingImage(){return this.#W}get hcmFilter(){return E(this,"hcmFilter",this.#ot?this.#G.addHCMFilter(this.#ot.foreground,this.#ot.background):"none")}get direction(){return E(this,"direction",getComputedStyle(this.#ut).direction)}get highlightColors(){return E(this,"highlightColors",this.#X?new Map(this.#X.split(",").map((t=>t.split("=").map((t=>t.trim()))))):null)}get highlightColorNames(){return E(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,(t=>t.reverse()))):null)}setMainHighlightColorPicker(t){this.#it=t}editAltText(t,e=!1){this.#R?.editAltText(this,t,e)}switchToMode(t,e){this._eventBus.on("annotationeditormodechanged",e,{once:!0,signal:this._signal}),this._eventBus.dispatch("showannotationeditorui",{source:this,mode:t})}setPreference(t,e){this._eventBus.dispatch("setpreference",{source:this,name:t,value:e})}onSetPreference({name:t,value:e}){"enableNewAltTextWhenAddingImage"===t&&(this.#W=e)}onPageChanging({pageNumber:t}){this.#O=t-1}focusMainContainer(){this.#ut.focus()}findParent(t,e){for(const i of this.#P.values()){const{x:s,y:n,width:a,height:r}=i.div.getBoundingClientRect();if(t>=s&&t<=s+a&&e>=n&&e<=n+r)return i}return null}disableUserSelect(t=!1){this.#pt.classList.toggle("noUserSelect",t)}addShouldRescale(t){this.#j.add(t)}removeShouldRescale(t){this.#j.delete(t)}onScaleChanging({scale:t}){this.commitOrRemove(),this.viewParameters.realScale=t*Y.PDF_TO_CSS_UNITS;for(const t of this.#j)t.onScaleChanging()}onRotationChanging({pagesRotation:t}){this.commitOrRemove(),this.viewParameters.rotation=t}#vt({anchorNode:t}){return t.nodeType===Node.TEXT_NODE?t.parentElement:t}#At(t){const{currentLayer:e}=this;if(e.hasTextLayer(t))return e;for(const e of this.#P.values())if(e.hasTextLayer(t))return e;return null}highlightSelection(t=""){const e=document.getSelection();if(!e||e.isCollapsed)return;const{anchorNode:i,anchorOffset:s,focusNode:n,focusOffset:a}=e,r=e.toString(),o=this.#vt(e).closest(".textLayer"),l=this.getSelectionBoxes(o);if(!l)return;e.empty();const d=this.#At(o),c=this.#nt===h.NONE,u=()=>{d?.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:t,boxes:l,anchorNode:i,anchorOffset:s,focusNode:n,focusOffset:a,text:r}),c&&this.showAllEditors("highlight",!0,!0)};c?this.switchToMode(h.HIGHLIGHT,u):u()}#yt(){const t=document.getSelection();if(!t||t.isCollapsed)return;const e=this.#vt(t).closest(".textLayer"),i=this.getSelectionBoxes(e);i&&(this.#Y||=new yt(this),this.#Y.show(e,i,"ltr"===this.direction))}addToAnnotationStorage(t){t.isEmpty()||!this.#D||this.#D.has(t.id)||this.#D.setValue(t.id,t)}#wt(){const t=document.getSelection();if(!t||t.isCollapsed)return void(this.#rt&&(this.#Y?.hide(),this.#rt=null,this.#_t({hasSelectedText:!1})));const{anchorNode:e}=t;if(e===this.#rt)return;const i=this.#vt(t).closest(".textLayer");if(i){if(this.#Y?.hide(),this.#rt=e,this.#_t({hasSelectedText:!0}),(this.#nt===h.HIGHLIGHT||this.#nt===h.NONE)&&(this.#nt===h.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0),this.#K=this.isShiftKeyDown,!this.isShiftKeyDown)){const t=this.#nt===h.HIGHLIGHT?this.#At(i):null;t?.toggleDrawing();const e=new AbortController,s=this.combinedSignal(e),n=i=>{"pointerup"===i.type&&0!==i.button||(e.abort(),t?.toggleDrawing(!0),"pointerup"===i.type&&this.#xt("main_toolbar"))};window.addEventListener("pointerup",n,{signal:s}),window.addEventListener("blur",n,{signal:s})}}else this.#rt&&(this.#Y?.hide(),this.#rt=null,this.#_t({hasSelectedText:!1}))}#xt(t=""){this.#nt===h.HIGHLIGHT?this.highlightSelection(t):this.#U&&this.#yt()}#mt(){document.addEventListener("selectionchange",this.#wt.bind(this),{signal:this._signal})}#Ct(){if(this.#q)return;this.#q=new AbortController;const t=this.combinedSignal(this.#q);window.addEventListener("focus",this.focus.bind(this),{signal:t}),window.addEventListener("blur",this.blur.bind(this),{signal:t})}#Et(){this.#q?.abort(),this.#q=null}blur(){if(this.isShiftKeyDown=!1,this.#K&&(this.#K=!1,this.#xt("main_toolbar")),!this.hasSelection)return;const{activeElement:t}=document;for(const e of this.#at)if(e.div.contains(t)){this.#et=[e,t],e._focusEventsAllowed=!1;break}}focus(){if(!this.#et)return;const[t,e]=this.#et;this.#et=null,e.addEventListener("focusin",(()=>{t._focusEventsAllowed=!0}),{once:!0,signal:this._signal}),e.focus()}#bt(){if(this.#tt)return;this.#tt=new AbortController;const t=this.combinedSignal(this.#tt);window.addEventListener("keydown",this.keydown.bind(this),{signal:t}),window.addEventListener("keyup",this.keyup.bind(this),{signal:t})}#St(){this.#tt?.abort(),this.#tt=null}#Tt(){if(this.#N)return;this.#N=new AbortController;const t=this.combinedSignal(this.#N);document.addEventListener("copy",this.copy.bind(this),{signal:t}),document.addEventListener("cut",this.cut.bind(this),{signal:t}),document.addEventListener("paste",this.paste.bind(this),{signal:t})}#Mt(){this.#N?.abort(),this.#N=null}#ft(){const t=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:t}),document.addEventListener("drop",this.drop.bind(this),{signal:t})}addEditListeners(){this.#bt(),this.#Tt()}removeEditListeners(){this.#St(),this.#Mt()}dragOver(t){for(const{type:e}of t.dataTransfer.items)for(const i of this.#H)if(i.isHandlingMimeForPasting(e))return t.dataTransfer.dropEffect="copy",void t.preventDefault()}drop(t){for(const e of t.dataTransfer.items)for(const i of this.#H)if(i.isHandlingMimeForPasting(e.type))return i.paste(e,this.currentLayer),void t.preventDefault()}copy(t){if(t.preventDefault(),this.#k?.commitOrRemove(),!this.hasSelection)return;const e=[];for(const t of this.#at){const i=t.serialize(!0);i&&e.push(i)}0!==e.length&&t.clipboardData.setData("application/pdfjs",JSON.stringify(e))}cut(t){this.copy(t),this.delete()}async paste(t){t.preventDefault();const{clipboardData:e}=t;for(const t of e.items)for(const e of this.#H)if(e.isHandlingMimeForPasting(t.type))return void e.paste(t,this.currentLayer);let i=e.getData("application/pdfjs");if(!i)return;try{i=JSON.parse(i)}catch(t){return void w(`paste: "${t.message}".`)}if(!Array.isArray(i))return;this.unselectAll();const s=this.currentLayer;try{const t=[];for(const e of i){const i=await s.deserialize(e);if(!i)return;t.push(i)}const e=()=>{for(const e of t)this.#kt(e);this.#It(t)},n=()=>{for(const e of t)e.remove()};this.addCommands({cmd:e,undo:n,mustExec:!0})}catch(t){w(`paste: "${t.message}".`)}}keydown(t){this.isShiftKeyDown||"Shift"!==t.key||(this.isShiftKeyDown=!0),this.#nt===h.NONE||this.isEditorHandlingKeyboard||Tt._keyboardManager.exec(this,t)}keyup(t){this.isShiftKeyDown&&"Shift"===t.key&&(this.isShiftKeyDown=!1,this.#K&&(this.#K=!1,this.#xt("main_toolbar")))}onEditingAction({name:t}){switch(t){case"undo":case"redo":case"delete":case"selectAll":this[t]();break;case"highlightSelection":this.highlightSelection("context_menu")}}#_t(t){Object.entries(t).some((([t,e])=>this.#ht[t]!==e))&&(this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(this.#ht,t)}),this.#nt===h.HIGHLIGHT&&!1===t.hasSelectedEditor&&this.#Pt([[d.HIGHLIGHT_FREE,!0]]))}#Pt(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})}setEditingState(t){t?(this.#Ct(),this.#Tt(),this.#_t({isEditing:this.#nt!==h.NONE,isEmpty:this.#Rt(),hasSomethingToUndo:this.#F.hasSomethingToUndo(),hasSomethingToRedo:this.#F.hasSomethingToRedo(),hasSelectedEditor:!1})):(this.#Et(),this.#Mt(),this.#_t({isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(t){if(!this.#H){this.#H=t;for(const t of this.#H)this.#Pt(t.defaultPropertiesToUpdate)}}getId(){return this.#Q.id}get currentLayer(){return this.#P.get(this.#O)}getLayer(t){return this.#P.get(t)}get currentPageIndex(){return this.#O}addLayer(t){this.#P.set(t.pageIndex,t),this.#J?t.enable():t.disable()}removeLayer(t){this.#P.delete(t.pageIndex)}async updateMode(t,e=null,i=!1){if(this.#nt!==t&&(!this.#gt||(await this.#gt.promise,this.#gt))){if(this.#gt=Promise.withResolvers(),this.#nt=t,t===h.NONE)return this.setEditingState(!1),this.#Dt(),void this.#gt.resolve();this.setEditingState(!0),await this.#Lt(),this.unselectAll();for(const e of this.#P.values())e.updateMode(t);if(!e)return i&&this.addNewEditorFromKeyboard(),void this.#gt.resolve();for(const t of this.#I.values())t.annotationElementId===e?(this.setSelected(t),t.enterInEditMode()):t.unselect();this.#gt.resolve()}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t!==this.#nt&&this._eventBus.dispatch("switchannotationeditormode",{source:this,mode:t})}updateParams(t,e){if(this.#H){switch(t){case d.CREATE:return void this.currentLayer.addNewEditor();case d.HIGHLIGHT_DEFAULT_COLOR:this.#it?.updateColor(e);break;case d.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}}),(this.#lt||=new Map).set(t,e),this.showAllEditors("highlight",e)}for(const i of this.#at)i.updateParams(t,e);for(const i of this.#H)i.updateDefaultParams(t,e)}}showAllEditors(t,e,i=!1){for(const i of this.#I.values())i.editorType===t&&i.show(e);(this.#lt?.get(d.HIGHLIGHT_SHOW_ALL)??!0)!==e&&this.#Pt([[d.HIGHLIGHT_SHOW_ALL,e]])}enableWaiting(t=!1){if(this.#Z!==t){this.#Z=t;for(const e of this.#P.values())t?e.disableClick():e.enableClick(),e.div.classList.toggle("waiting",t)}}async#Lt(){if(!this.#J){this.#J=!0;const t=[];for(const e of this.#P.values())t.push(e.enable());await Promise.all(t);for(const t of this.#I.values())t.enable()}}#Dt(){if(this.unselectAll(),this.#J){this.#J=!1;for(const t of this.#P.values())t.disable();for(const t of this.#I.values())t.disable()}}getEditors(t){const e=[];for(const i of this.#I.values())i.pageIndex===t&&e.push(i);return e}getEditor(t){return this.#I.get(t)}addEditor(t){this.#I.set(t.id,t)}removeEditor(t){t.div.contains(document.activeElement)&&(this.#V&&clearTimeout(this.#V),this.#V=setTimeout((()=>{this.focusMainContainer(),this.#V=null}),0)),this.#I.delete(t.id),this.unselect(t),t.annotationElementId&&this.#B.has(t.annotationElementId)||this.#D?.remove(t.id)}addDeletedAnnotationElement(t){this.#B.add(t.annotationElementId),this.addChangedExistingAnnotation(t),t.deleted=!0}isDeletedAnnotationElement(t){return this.#B.has(t)}removeDeletedAnnotationElement(t){this.#B.delete(t.annotationElementId),this.removeChangedExistingAnnotation(t),t.deleted=!1}#kt(t){const e=this.#P.get(t.pageIndex);e?e.addOrRebuild(t):(this.addEditor(t),this.addToAnnotationStorage(t))}setActiveEditor(t){this.#k!==t&&(this.#k=t,t&&this.#Pt(t.propertiesToUpdate))}get#Ft(){let t=null;for(t of this.#at);return t}updateUI(t){this.#Ft===t&&this.#Pt(t.propertiesToUpdate)}toggleSelected(t){if(this.#at.has(t))return this.#at.delete(t),t.unselect(),void this.#_t({hasSelectedEditor:this.hasSelection});this.#at.add(t),t.select(),this.#Pt(t.propertiesToUpdate),this.#_t({hasSelectedEditor:!0})}setSelected(t){for(const e of this.#at)e!==t&&e.unselect();this.#at.clear(),this.#at.add(t),t.select(),this.#Pt(t.propertiesToUpdate),this.#_t({hasSelectedEditor:!0})}isSelected(t){return this.#at.has(t)}get firstSelectedEditor(){return this.#at.values().next().value}unselect(t){t.unselect(),this.#at.delete(t),this.#_t({hasSelectedEditor:this.hasSelection})}get hasSelection(){return 0!==this.#at.size}get isEnterHandled(){return 1===this.#at.size&&this.firstSelectedEditor.isEnterHandled}undo(){this.#F.undo(),this.#_t({hasSomethingToUndo:this.#F.hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:this.#Rt()})}redo(){this.#F.redo(),this.#_t({hasSomethingToUndo:!0,hasSomethingToRedo:this.#F.hasSomethingToRedo(),isEmpty:this.#Rt()})}addCommands(t){this.#F.add(t),this.#_t({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#Rt()})}#Rt(){if(0===this.#I.size)return!0;if(1===this.#I.size)for(const t of this.#I.values())return t.isEmpty();return!1}delete(){if(this.commitOrRemove(),!this.hasSelection)return;const t=[...this.#at];this.addCommands({cmd:()=>{for(const e of t)e.remove()},undo:()=>{for(const e of t)this.#kt(e)},mustExec:!0})}commitOrRemove(){this.#k?.commitOrRemove()}hasSomethingToControl(){return this.#k||this.hasSelection}#It(t){for(const t of this.#at)t.unselect();this.#at.clear();for(const e of t)e.isEmpty()||(this.#at.add(e),e.select());this.#_t({hasSelectedEditor:this.hasSelection})}selectAll(){for(const t of this.#at)t.commit();this.#It(this.#I.values())}unselectAll(){if((!this.#k||(this.#k.commitOrRemove(),this.#nt===h.NONE))&&this.hasSelection){for(const t of this.#at)t.unselect();this.#at.clear(),this.#_t({hasSelectedEditor:!1})}}translateSelectedEditors(t,e,i=!1){if(i||this.commitOrRemove(),!this.hasSelection)return;this.#dt[0]+=t,this.#dt[1]+=e;const[s,n]=this.#dt,a=[...this.#at];this.#ct&&clearTimeout(this.#ct),this.#ct=setTimeout((()=>{this.#ct=null,this.#dt[0]=this.#dt[1]=0,this.addCommands({cmd:()=>{for(const t of a)this.#I.has(t.id)&&t.translateInPage(s,n)},undo:()=>{for(const t of a)this.#I.has(t.id)&&t.translateInPage(-s,-n)},mustExec:!1})}),1e3);for(const i of a)i.translateInPage(t,e)}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0),this.#z=new Map;for(const t of this.#at)this.#z.set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!this.#z)return!1;this.disableUserSelect(!1);const t=this.#z;this.#z=null;let e=!1;for(const[{x:i,y:s,pageIndex:n},a]of t)a.newX=i,a.newY=s,a.newPageIndex=n,e||=i!==a.savedX||s!==a.savedY||n!==a.savedPageIndex;if(!e)return!1;const i=(t,e,i,s)=>{if(this.#I.has(t.id)){const n=this.#P.get(s);n?t._setParentAndPosition(n,e,i):(t.pageIndex=s,t.x=e,t.y=i)}};return this.addCommands({cmd:()=>{for(const[e,{newX:s,newY:n,newPageIndex:a}]of t)i(e,s,n,a)},undo:()=>{for(const[e,{savedX:s,savedY:n,savedPageIndex:a}]of t)i(e,s,n,a)},mustExec:!0}),!0}dragSelectedEditors(t,e){if(this.#z)for(const i of this.#z.keys())i.drag(t,e)}rebuild(t){if(null===t.parent){const e=this.getLayer(t.pageIndex);e?(e.changeParent(t),e.addOrRebuild(t)):(this.addEditor(t),this.addToAnnotationStorage(t),t.rebuild())}else t.parent.addOrRebuild(t)}get isEditorHandlingKeyboard(){return this.getActive()?.shouldGetKeyboardEvents()||1===this.#at.size&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(t){return this.#k===t}getActive(){return this.#k}getMode(){return this.#nt}get imageManager(){return E(this,"imageManager",new xt)}getSelectionBoxes(t){if(!t)return null;const e=document.getSelection();for(let i=0,s=e.rangeCount;i({x:(e-s)/a,y:1-(t+r-i)/n,width:o/a,height:r/n});break;case"180":r=(t,e,r,o)=>({x:1-(t+r-i)/n,y:1-(e+o-s)/a,width:r/n,height:o/a});break;case"270":r=(t,e,r,o)=>({x:1-(e+o-s)/a,y:(t-i)/n,width:o/a,height:r/n});break;default:r=(t,e,r,o)=>({x:(t-i)/n,y:(e-s)/a,width:r/n,height:o/a})}const o=[];for(let t=0,i=e.rangeCount;tt.stopPropagation()),{signal:i});const s=t=>{t.preventDefault(),this.#a._uiManager.editAltText(this.#a),this.#Wt&&this.#a._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:this.#Vt}})};return t.addEventListener("click",s,{capture:!0,signal:i}),t.addEventListener("keydown",(e=>{e.target===t&&"Enter"===e.key&&(this.#Ht=!0,s(e))}),{signal:i}),await this.#qt(),t}get#Vt(){return(this.#o?"added":null===this.#o&&this.guessedText&&"review")||"missing"}finish(){this.#Ot&&(this.#Ot.focus({focusVisible:this.#Ht}),this.#Ht=!1)}isEmpty(){return this.#Wt?null===this.#o:!this.#o&&!this.#Nt}hasData(){return this.#Wt?null!==this.#o||!!this.#Ut:this.isEmpty()}get guessedText(){return this.#Ut}async setGuessedText(t){null===this.#o&&(this.#Ut=t,this.#$t=await Mt._l10nPromise.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer")({generatedAltText:t}),this.#qt())}toggleAltTextBadge(t=!1){if(!this.#Wt||this.#o)return this.#jt?.remove(),void(this.#jt=null);if(!this.#jt){const t=this.#jt=document.createElement("div");t.className="noAltTextBadge",this.#a.div.append(t)}this.#jt.classList.toggle("hidden",!t)}serialize(t){let e=this.#o;return t||this.#Ut!==e||(e=this.#$t),{altText:e,decorative:this.#Nt,guessedText:this.#Ut,textWithDisclaimer:this.#$t}}get data(){return{altText:this.#o,decorative:this.#Nt}}set data({altText:t,decorative:e,guessedText:i,textWithDisclaimer:s,cancel:n=!1}){i&&(this.#Ut=i,this.#$t=s),this.#o===t&&this.#Nt===e||(n||(this.#o=t,this.#Nt=e),this.#qt())}toggle(t=!1){this.#Ot&&(!t&&this.#zt&&(clearTimeout(this.#zt),this.#zt=null),this.#Ot.disabled=!t)}shown(){this.#a._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:this.#Vt}})}destroy(){this.#Ot?.remove(),this.#Ot=null,this.#Bt=null,this.#jt?.remove(),this.#jt=null}async#qt(){const t=this.#Ot;if(!t)return;if(this.#Wt){if(t.classList.toggle("done",!!this.#o),Mt._l10nPromise.get(Mt.#Gt[this.#Vt]).then((e=>{t.setAttribute("aria-label",e);for(const i of t.childNodes)if(i.nodeType===Node.TEXT_NODE){i.textContent=e;break}})),!this.#o)return void this.#Bt?.remove()}else{if(!this.#o&&!this.#Nt)return t.classList.remove("done"),void this.#Bt?.remove();t.classList.add("done"),Mt._l10nPromise.get("pdfjs-editor-alt-text-edit-button-label").then((e=>{t.setAttribute("aria-label",e)}))}let e=this.#Bt;if(!e){this.#Bt=e=document.createElement("span"),e.className="tooltip",e.setAttribute("role","tooltip"),e.id=`alt-text-tooltip-${this.#a.id}`;const i=100,s=this.#a._uiManager._signal;s.addEventListener("abort",(()=>{clearTimeout(this.#zt),this.#zt=null}),{once:!0}),t.addEventListener("mouseenter",(()=>{this.#zt=setTimeout((()=>{this.#zt=null,this.#Bt.classList.add("show"),this.#a._reportTelemetry({action:"alt_text_tooltip"})}),i)}),{signal:s}),t.addEventListener("mouseleave",(()=>{this.#zt&&(clearTimeout(this.#zt),this.#zt=null),this.#Bt?.classList.remove("show")}),{signal:s})}e.innerText=this.#Nt?await Mt._l10nPromise.get("pdfjs-editor-alt-text-decorative-tooltip"):this.#o,e.parentNode||t.append(e),this.#a.getImageForAltText()?.setAttribute("aria-describedby",e.id)}}class kt{#Xt=null;#Kt=null;#o=null;#Yt=!1;#Qt=!1;#Jt=null;#Zt=null;#te=null;#ee="";#ie=!1;#se=null;#ne=!1;#ae=!1;#re=!1;#oe=null;#le=0;#he=0;#de=null;_editToolbar=null;_initialOptions=Object.create(null);_initialData=null;_isVisible=!0;_uiManager=null;_focusEventsAllowed=!0;static _l10nPromise=null;static _l10nResizer=null;#ce=!1;#ue=kt._zIndex++;static _borderLineWidth=-1;static _colorManager=new St;static _zIndex=1;static _telemetryTimeout=1e3;static get _resizerKeyboardManager(){const t=kt.prototype._resizeWithKeyboard,e=Tt.TRANSLATE_SMALL,i=Tt.TRANSLATE_BIG;return E(this,"_resizerKeyboardManager",new Et([[["ArrowLeft","mac+ArrowLeft"],t,{args:[-e,0]}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t,{args:[-i,0]}],[["ArrowRight","mac+ArrowRight"],t,{args:[e,0]}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t,{args:[i,0]}],[["ArrowUp","mac+ArrowUp"],t,{args:[0,-e]}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t,{args:[0,-i]}],[["ArrowDown","mac+ArrowDown"],t,{args:[0,e]}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t,{args:[0,i]}],[["Escape","mac+Escape"],kt.prototype._stopResizingWithKeyboard]]))}constructor(t){this.parent=t.parent,this.id=t.id,this.width=this.height=null,this.pageIndex=t.parent.pageIndex,this.name=t.name,this.div=null,this._uiManager=t.uiManager,this.annotationElementId=null,this._willKeepAspectRatio=!1,this._initialOptions.isCentered=t.isCentered,this._structTreeParentId=null;const{rotation:e,rawDims:{pageWidth:i,pageHeight:s,pageX:n,pageY:a}}=this.parent.viewport;this.rotation=e,this.pageRotation=(360+e-this._uiManager.viewParameters.rotation)%360,this.pageDimensions=[i,s],this.pageTranslation=[n,a];const[r,o]=this.parentDimensions;this.x=t.x/r,this.y=t.y/o,this.isAttachedToDOM=!1,this.deleted=!1}get editorType(){return Object.getPrototypeOf(this).constructor._type}static get _defaultLineColor(){return E(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){const e=new It({id:t.parent.getNextId(),parent:t.parent,uiManager:t._uiManager});e.annotationElementId=t.annotationElementId,e.deleted=!0,e._uiManager.addToAnnotationStorage(e)}static initialize(t,e,i){if(kt._l10nResizer||=Object.freeze({topLeft:"pdfjs-editor-resizer-top-left",topMiddle:"pdfjs-editor-resizer-top-middle",topRight:"pdfjs-editor-resizer-top-right",middleRight:"pdfjs-editor-resizer-middle-right",bottomRight:"pdfjs-editor-resizer-bottom-right",bottomMiddle:"pdfjs-editor-resizer-bottom-middle",bottomLeft:"pdfjs-editor-resizer-bottom-left",middleLeft:"pdfjs-editor-resizer-middle-left"}),kt._l10nPromise||=new Map([...["pdfjs-editor-alt-text-button-label","pdfjs-editor-alt-text-edit-button-label","pdfjs-editor-alt-text-decorative-tooltip","pdfjs-editor-new-alt-text-added-button-label","pdfjs-editor-new-alt-text-missing-button-label","pdfjs-editor-new-alt-text-to-review-button-label"].map((e=>[e,t.get(e)])),...["pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer"].map((e=>[e,t.get.bind(t,e)]))]),i?.strings)for(const e of i.strings)kt._l10nPromise.set(e,t.get(e));if(-1!==kt._borderLineWidth)return;const s=getComputedStyle(document.documentElement);kt._borderLineWidth=parseFloat(s.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,e){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return!1}static paste(t,e){_("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return this.#ce}set _isDraggable(t){this.#ce=t,this.div?.classList.toggle("draggable",t)}get isEnterHandled(){return!0}center(){const[t,e]=this.pageDimensions;switch(this.parentRotation){case 90:this.x-=this.height*e/(2*t),this.y+=this.width*t/(2*e);break;case 180:this.x+=this.width/2,this.y+=this.height/2;break;case 270:this.x+=this.height*e/(2*t),this.y-=this.width*t/(2*e);break;default:this.x-=this.width/2,this.y-=this.height/2}this.fixAndSetPosition()}addCommands(t){this._uiManager.addCommands(t)}get currentLayer(){return this._uiManager.currentLayer}setInBackground(){this.div.style.zIndex=0}setInForeground(){this.div.style.zIndex=this.#ue}setParent(t){null!==t?(this.pageIndex=t.pageIndex,this.pageDimensions=t.pageDimensions):this.#pe(),this.parent=t}focusin(t){this._focusEventsAllowed&&(this.#ie?this.#ie=!1:this.parent.setSelected(this))}focusout(t){this._focusEventsAllowed&&this.isAttachedToDOM&&(t.relatedTarget?.closest(`#${this.id}`)||(t.preventDefault(),this.parent?.isMultipleSelection||this.commitOrRemove()))}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.addToAnnotationStorage()}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(t,e,i,s){const[n,a]=this.parentDimensions;[i,s]=this.screenToPageTranslation(i,s),this.x=(t+i)/n,this.y=(e+s)/a,this.fixAndSetPosition()}#ge([t,e],i,s){[i,s]=this.screenToPageTranslation(i,s),this.x+=i/t,this.y+=s/e,this.fixAndSetPosition()}translate(t,e){this.#ge(this.parentDimensions,t,e)}translateInPage(t,e){this.#se||=[this.x,this.y],this.#ge(this.pageDimensions,t,e),this.div.scrollIntoView({block:"nearest"})}drag(t,e){this.#se||=[this.x,this.y];const[i,s]=this.parentDimensions;if(this.x+=t/i,this.y+=e/s,this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){const{x:t,y:e}=this.div.getBoundingClientRect();this.parent.findNewParent(this,t,e)&&(this.x-=Math.floor(this.x),this.y-=Math.floor(this.y))}let{x:n,y:a}=this;const[r,o]=this.getBaseTranslation();n+=r,a+=o,this.div.style.left=`${(100*n).toFixed(2)}%`,this.div.style.top=`${(100*a).toFixed(2)}%`,this.div.scrollIntoView({block:"nearest"})}get _hasBeenMoved(){return!!this.#se&&(this.#se[0]!==this.x||this.#se[1]!==this.y)}getBaseTranslation(){const[t,e]=this.parentDimensions,{_borderLineWidth:i}=kt,s=i/t,n=i/e;switch(this.rotation){case 90:return[-s,n];case 180:return[s,n];case 270:return[s,-n];default:return[-s,-n]}}get _mustFixPosition(){return!0}fixAndSetPosition(t=this.rotation){const[e,i]=this.pageDimensions;let{x:s,y:n,width:a,height:r}=this;if(a*=e,r*=i,s*=e,n*=i,this._mustFixPosition)switch(t){case 0:s=Math.max(0,Math.min(e-a,s)),n=Math.max(0,Math.min(i-r,n));break;case 90:s=Math.max(0,Math.min(e-r,s)),n=Math.min(i,Math.max(a,n));break;case 180:s=Math.min(e,Math.max(a,s)),n=Math.min(i,Math.max(r,n));break;case 270:s=Math.min(e,Math.max(r,s)),n=Math.max(0,Math.min(i-a,n))}this.x=s/=e,this.y=n/=i;const[o,l]=this.getBaseTranslation();s+=o,n+=l;const{style:h}=this.div;h.left=`${(100*s).toFixed(2)}%`,h.top=`${(100*n).toFixed(2)}%`,this.moveInDOM()}static#me(t,e,i){switch(i){case 90:return[e,-t];case 180:return[-t,-e];case 270:return[-e,t];default:return[t,e]}}screenToPageTranslation(t,e){return kt.#me(t,e,this.parentRotation)}pageTranslationToScreen(t,e){return kt.#me(t,e,360-this.parentRotation)}#fe(t){switch(t){case 90:{const[t,e]=this.pageDimensions;return[0,-t/e,e/t,0]}case 180:return[-1,0,0,-1];case 270:{const[t,e]=this.pageDimensions;return[0,t/e,-e/t,0]}default:return[1,0,0,1]}}get parentScale(){return this._uiManager.viewParameters.realScale}get parentRotation(){return(this._uiManager.viewParameters.rotation+this.pageRotation)%360}get parentDimensions(){const{parentScale:t,pageDimensions:[e,i]}=this;return[e*t,i*t]}setDims(t,e){const[i,s]=this.parentDimensions;this.div.style.width=`${(100*t/i).toFixed(2)}%`,this.#Qt||(this.div.style.height=`${(100*e/s).toFixed(2)}%`)}fixDims(){const{style:t}=this.div,{height:e,width:i}=t,s=i.endsWith("%"),n=!this.#Qt&&e.endsWith("%");if(s&&n)return;const[a,r]=this.parentDimensions;s||(t.width=`${(100*parseFloat(i)/a).toFixed(2)}%`),this.#Qt||n||(t.height=`${(100*parseFloat(e)/r).toFixed(2)}%`)}getInitialTranslation(){return[0,0]}#be(){if(this.#Jt)return;this.#Jt=document.createElement("div"),this.#Jt.classList.add("resizers");const t=this._willKeepAspectRatio?["topLeft","topRight","bottomRight","bottomLeft"]:["topLeft","topMiddle","topRight","middleRight","bottomRight","bottomMiddle","bottomLeft","middleLeft"],e=this._uiManager._signal;for(const i of t){const t=document.createElement("div");this.#Jt.append(t),t.classList.add("resizer",i),t.setAttribute("data-resizer-name",i),t.addEventListener("pointerdown",this.#ve.bind(this,i),{signal:e}),t.addEventListener("contextmenu",ht,{signal:e}),t.tabIndex=-1}this.div.prepend(this.#Jt)}#ve(t,e){e.preventDefault();const{isMac:i}=O.platform;if(0!==e.button||e.ctrlKey&&i)return;this.#o?.toggle(!1);const s=this._isDraggable;this._isDraggable=!1;const n=new AbortController,a=this._uiManager.combinedSignal(n);this.parent.togglePointerEvents(!1),window.addEventListener("pointermove",this.#Ae.bind(this,t),{passive:!0,capture:!0,signal:a}),window.addEventListener("contextmenu",ht,{signal:a});const r=this.x,o=this.y,l=this.width,h=this.height,d=this.parent.div.style.cursor,c=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(e.target).cursor;const u=()=>{n.abort(),this.parent.togglePointerEvents(!0),this.#o?.toggle(!0),this._isDraggable=s,this.parent.div.style.cursor=d,this.div.style.cursor=c,this.#ye(r,o,l,h)};window.addEventListener("pointerup",u,{signal:a}),window.addEventListener("blur",u,{signal:a})}#ye(t,e,i,s){const n=this.x,a=this.y,r=this.width,o=this.height;n===t&&a===e&&r===i&&o===s||this.addCommands({cmd:()=>{this.width=r,this.height=o,this.x=n,this.y=a;const[t,e]=this.parentDimensions;this.setDims(t*r,e*o),this.fixAndSetPosition()},undo:()=>{this.width=i,this.height=s,this.x=t,this.y=e;const[n,a]=this.parentDimensions;this.setDims(n*i,a*s),this.fixAndSetPosition()},mustExec:!0})}#Ae(t,e){const[i,s]=this.parentDimensions,n=this.x,a=this.y,r=this.width,o=this.height,l=kt.MIN_SIZE/i,h=kt.MIN_SIZE/s,d=t=>Math.round(1e4*t)/1e4,c=this.#fe(this.rotation),u=(t,e)=>[c[0]*t+c[2]*e,c[1]*t+c[3]*e],p=this.#fe(360-this.rotation);let g,m,f=!1,b=!1;switch(t){case"topLeft":f=!0,g=(t,e)=>[0,0],m=(t,e)=>[t,e];break;case"topMiddle":g=(t,e)=>[t/2,0],m=(t,e)=>[t/2,e];break;case"topRight":f=!0,g=(t,e)=>[t,0],m=(t,e)=>[0,e];break;case"middleRight":b=!0,g=(t,e)=>[t,e/2],m=(t,e)=>[0,e/2];break;case"bottomRight":f=!0,g=(t,e)=>[t,e],m=(t,e)=>[0,0];break;case"bottomMiddle":g=(t,e)=>[t/2,e],m=(t,e)=>[t/2,0];break;case"bottomLeft":f=!0,g=(t,e)=>[0,e],m=(t,e)=>[t,0];break;case"middleLeft":b=!0,g=(t,e)=>[0,e/2],m=(t,e)=>[t,e/2]}const v=g(r,o),A=m(r,o);let y=u(...A);const w=d(n+y[0]),_=d(a+y[1]);let x=1,C=1,[E,S]=this.screenToPageTranslation(e.movementX,e.movementY);var T,M;if([E,S]=(T=E/i,M=S/s,[p[0]*T+p[2]*M,p[1]*T+p[3]*M]),f){const t=Math.hypot(r,o);x=C=Math.max(Math.min(Math.hypot(A[0]-v[0]-E,A[1]-v[1]-S)/t,1/r,1/o),l/r,h/o)}else b?x=Math.max(l,Math.min(1,Math.abs(A[0]-v[0]-E)))/r:C=Math.max(h,Math.min(1,Math.abs(A[1]-v[1]-S)))/o;const k=d(r*x),I=d(o*C);y=u(...m(k,I));const P=w-y[0],R=_-y[1];this.width=k,this.height=I,this.x=P,this.y=R,this.setDims(i*k,s*I),this.fixAndSetPosition()}altTextFinish(){this.#o?.finish()}async addEditToolbar(){return this._editToolbar||this.#ae||(this._editToolbar=new At(this),this.div.append(this._editToolbar.render()),this.#o&&await this._editToolbar.addAltText(this.#o)),this._editToolbar}removeEditToolbar(){this._editToolbar&&(this._editToolbar.remove(),this._editToolbar=null,this.#o?.destroy())}addContainer(t){const e=this._editToolbar?.div;e?e.before(t):this.div.append(t)}getClientDimensions(){return this.div.getBoundingClientRect()}async addAltTextButton(){this.#o||(Mt.initialize(kt._l10nPromise),this.#o=new Mt(this),this.#Xt&&(this.#o.data=this.#Xt,this.#Xt=null),await this.addEditToolbar())}get altTextData(){return this.#o?.data}set altTextData(t){this.#o&&(this.#o.data=t)}get guessedAltText(){return this.#o?.guessedText}async setGuessedAltText(t){await(this.#o?.setGuessedText(t))}serializeAltText(t){return this.#o?.serialize(t)}hasAltText(){return!!this.#o&&!this.#o.isEmpty()}hasAltTextData(){return this.#o?.hasData()??!1}render(){this.div=document.createElement("div"),this.div.setAttribute("data-editor-rotation",(360-this.rotation)%360),this.div.className=this.name,this.div.setAttribute("id",this.id),this.div.tabIndex=this.#Yt?-1:0,this._isVisible||this.div.classList.add("hidden"),this.setInForeground(),this.#we();const[t,e]=this.parentDimensions;this.parentRotation%180!=0&&(this.div.style.maxWidth=`${(100*e/t).toFixed(2)}%`,this.div.style.maxHeight=`${(100*t/e).toFixed(2)}%`);const[i,s]=this.getInitialTranslation();return this.translate(i,s),wt(this,this.div,["pointerdown"]),this.div}pointerdown(t){const{isMac:e}=O.platform;0!==t.button||t.ctrlKey&&e?t.preventDefault():(this.#ie=!0,this._isDraggable?this.#_e(t):this.#xe(t))}#xe(t){const{isMac:e}=O.platform;t.ctrlKey&&!e||t.shiftKey||t.metaKey&&e?this.parent.toggleSelected(this):this.parent.setSelected(this)}#_e(t){const e=this._uiManager.isSelected(this);this._uiManager.setUpDragSession();const i=new AbortController,s=this._uiManager.combinedSignal(i);if(e){this.div.classList.add("moving"),this.#le=t.clientX,this.#he=t.clientY;const e=t=>{const{clientX:e,clientY:i}=t,[s,n]=this.screenToPageTranslation(e-this.#le,i-this.#he);this.#le=e,this.#he=i,this._uiManager.dragSelectedEditors(s,n)};window.addEventListener("pointermove",e,{passive:!0,capture:!0,signal:s})}const n=()=>{i.abort(),e&&this.div.classList.remove("moving"),this.#ie=!1,this._uiManager.endDragSession()||this.#xe(t)};window.addEventListener("pointerup",n,{signal:s}),window.addEventListener("blur",n,{signal:s})}moveInDOM(){this.#oe&&clearTimeout(this.#oe),this.#oe=setTimeout((()=>{this.#oe=null,this.parent?.moveEditorInDOM(this)}),0)}_setParentAndPosition(t,e,i){t.changeParent(this),this.x=e,this.y=i,this.fixAndSetPosition()}getRect(t,e,i=this.rotation){const s=this.parentScale,[n,a]=this.pageDimensions,[r,o]=this.pageTranslation,l=t/s,h=e/s,d=this.x*n,c=this.y*a,u=this.width*n,p=this.height*a;switch(i){case 0:return[d+l+r,a-c-h-p+o,d+l+u+r,a-c-h+o];case 90:return[d+h+r,a-c+l+o,d+h+p+r,a-c+l+u+o];case 180:return[d-l-u+r,a-c+h+o,d-l+r,a-c+h+p+o];case 270:return[d-h-p+r,a-c-l-u+o,d-h+r,a-c-l+o];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(t,e){const[i,s,n,a]=t,r=n-i,o=a-s;switch(this.rotation){case 0:return[i,e-a,r,o];case 90:return[i,e-s,o,r];case 180:return[n,e-s,r,o];case 270:return[n,e-a,o,r];default:throw new Error("Invalid rotation")}}onceAdded(){}isEmpty(){return!1}enableEditMode(){this.#ae=!0}disableEditMode(){this.#ae=!1}isInEditMode(){return this.#ae}shouldGetKeyboardEvents(){return this.#re}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}#we(){if(this.#te||!this.div)return;this.#te=new AbortController;const t=this._uiManager.combinedSignal(this.#te);this.div.addEventListener("focusin",this.focusin.bind(this),{signal:t}),this.div.addEventListener("focusout",this.focusout.bind(this),{signal:t})}rebuild(){this.#we()}rotate(t){}serializeDeleted(){return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex,popupRef:this._initialData?.popupRef||""}}serialize(t=!1,e=null){_("An editor must be serializable")}static async deserialize(t,e,i){const s=new this.prototype.constructor({parent:e,id:e.getNextId(),uiManager:i});s.rotation=t.rotation,s.#Xt=t.accessibilityData;const[n,a]=s.pageDimensions,[r,o,l,h]=s.getRectInCurrentCoords(t.rect,a);return s.x=r/n,s.y=o/a,s.width=l/n,s.height=h/a,s}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||null!==this.serialize())}remove(){if(this.#te?.abort(),this.#te=null,this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),this.#oe&&(clearTimeout(this.#oe),this.#oe=null),this.#pe(),this.removeEditToolbar(),this.#de){for(const t of this.#de.values())clearTimeout(t);this.#de=null}this.parent=null}get isResizable(){return!1}makeResizable(){this.isResizable&&(this.#be(),this.#Jt.classList.remove("hidden"),wt(this,this.div,["keydown"]))}get toolbarPosition(){return null}keydown(t){if(!this.isResizable||t.target!==this.div||"Enter"!==t.key)return;this._uiManager.setSelected(this),this.#Zt={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const e=this.#Jt.children;if(!this.#Kt){this.#Kt=Array.from(e);const t=this.#Ce.bind(this),i=this.#Ee.bind(this),s=this._uiManager._signal;for(const e of this.#Kt){const n=e.getAttribute("data-resizer-name");e.setAttribute("role","spinbutton"),e.addEventListener("keydown",t,{signal:s}),e.addEventListener("blur",i,{signal:s}),e.addEventListener("focus",this.#Se.bind(this,n),{signal:s}),e.setAttribute("data-l10n-id",kt._l10nResizer[n])}}const i=this.#Kt[0];let s=0;for(const t of e){if(t===i)break;s++}const n=(360-this.rotation+this.parentRotation)%360/90*(this.#Kt.length/4);if(n!==s){if(ns)for(let t=0;t{this.div?.classList.contains("selectedEditor")&&this._editToolbar?.show()}))}unselect(){this.#Jt?.classList.add("hidden"),this.div?.classList.remove("selectedEditor"),this.div?.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0}),this._editToolbar?.hide(),this.#o?.toggleAltTextBadge(!0)}updateParams(t,e){}disableEditing(){}enableEditing(){}enterInEditMode(){}getImageForAltText(){return null}get contentDiv(){return this.div}get isEditing(){return this.#ne}set isEditing(t){this.#ne=t,this.parent&&(t?(this.parent.setSelected(this),this.parent.setActiveEditor(this)):this.parent.setActiveEditor(null))}setAspectRatio(t,e){this.#Qt=!0;const i=t/e,{style:s}=this.div;s.aspectRatio=i,s.height="auto"}static get MIN_SIZE(){return 16}static canCreateNewEmptyEditor(){return!0}get telemetryInitialData(){return{action:"added"}}get telemetryFinalData(){return null}_reportTelemetry(t,e=!1){if(e){this.#de||=new Map;const{action:e}=t;let i=this.#de.get(e);return i&&clearTimeout(i),i=setTimeout((()=>{this._reportTelemetry(t),this.#de.delete(e),0===this.#de.size&&(this.#de=null)}),kt._telemetryTimeout),void this.#de.set(e,i)}t.type||=this.editorType,this._uiManager._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:t}})}show(t=this._isVisible){this.div.classList.toggle("hidden",!t),this._isVisible=t}enable(){this.div&&(this.div.tabIndex=0),this.#Yt=!1}disable(){this.div&&(this.div.tabIndex=-1),this.#Yt=!0}renderAnnotationElement(t){let e=t.container.querySelector(".annotationContent");if(e){if("CANVAS"===e.nodeName){const t=e;e=document.createElement("div"),e.classList.add("annotationContent",this.editorType),t.before(e)}}else e=document.createElement("div"),e.classList.add("annotationContent",this.editorType),t.container.prepend(e);return e}resetAnnotationElement(t){const{firstChild:e}=t.container;"DIV"===e?.nodeName&&e.classList.contains("annotationContent")&&e.remove()}}class It extends kt{constructor(t){super(t),this.annotationElementId=t.annotationElementId,this.deleted=!0}serialize(){return this.serializeDeleted()}}const Pt=3285377520,Rt=4294901760,Dt=65535;class Lt{constructor(t){this.h1=t?4294967295&t:Pt,this.h2=t?4294967295&t:Pt}update(t){let e,i;if("string"==typeof t){e=new Uint8Array(2*t.length),i=0;for(let s=0,n=t.length;s>>8,e[i++]=255&n)}}else{if(!ArrayBuffer.isView(t))throw new Error("Invalid data format, must be a string or TypedArray.");e=t.slice(),i=e.byteLength}const s=i>>2,n=i-4*s,a=new Uint32Array(e.buffer,0,s);let r=0,o=0,l=this.h1,h=this.h2;const d=3432918353,c=461845907,u=11601,p=13715;for(let t=0;t>>17,r=r*c&Rt|r*p&Dt,l^=r,l=l<<13|l>>>19,l=5*l+3864292196):(o=a[t],o=o*d&Rt|o*u&Dt,o=o<<15|o>>>17,o=o*c&Rt|o*p&Dt,h^=o,h=h<<13|h>>>19,h=5*h+3864292196);switch(r=0,n){case 3:r^=e[4*s+2]<<16;case 2:r^=e[4*s+1]<<8;case 1:r^=e[4*s],r=r*d&Rt|r*u&Dt,r=r<<15|r>>>17,r=r*c&Rt|r*p&Dt,1&s?l^=r:h^=r}this.h1=l,this.h2=h}hexdigest(){let t=this.h1,e=this.h2;return t^=e>>>1,t=3981806797*t&Rt|36045*t&Dt,e=4283543511*e&Rt|(2950163797*(e<<16|t>>>16)&Rt)>>>16,t^=e>>>1,t=444984403*t&Rt|60499*t&Dt,e=3301882366*e&Rt|(3120437893*(e<<16|t>>>16)&Rt)>>>16,t^=e>>>1,(t>>>0).toString(16).padStart(8,"0")+(e>>>0).toString(16).padStart(8,"0")}}const Ft=Object.freeze({map:null,hash:"",transfer:void 0});class Nt{#Me=!1;#ke=null;#Ie=new Map;constructor(){this.onSetModified=null,this.onResetModified=null,this.onAnnotationEditor=null}getValue(t,e){const i=this.#Ie.get(t);return void 0===i?e:Object.assign(e,i)}getRawValue(t){return this.#Ie.get(t)}remove(t){if(this.#Ie.delete(t),0===this.#Ie.size&&this.resetModified(),"function"==typeof this.onAnnotationEditor){for(const t of this.#Ie.values())if(t instanceof kt)return;this.onAnnotationEditor(null)}}setValue(t,e){const i=this.#Ie.get(t);let s=!1;if(void 0!==i)for(const[t,n]of Object.entries(e))i[t]!==n&&(s=!0,i[t]=n);else s=!0,this.#Ie.set(t,e);s&&this.#Pe(),e instanceof kt&&"function"==typeof this.onAnnotationEditor&&this.onAnnotationEditor(e.constructor._type)}has(t){return this.#Ie.has(t)}getAll(){return this.#Ie.size>0?N(this.#Ie):null}setAll(t){for(const[e,i]of Object.entries(t))this.setValue(e,i)}get size(){return this.#Ie.size}#Pe(){this.#Me||(this.#Me=!0,"function"==typeof this.onSetModified&&this.onSetModified())}resetModified(){this.#Me&&(this.#Me=!1,"function"==typeof this.onResetModified&&this.onResetModified())}get print(){return new Ot(this)}get serializable(){if(0===this.#Ie.size)return Ft;const t=new Map,e=new Lt,i=[],s=Object.create(null);let n=!1;for(const[i,a]of this.#Ie){const r=a instanceof kt?a.serialize(!1,s):a;r&&(t.set(i,r),e.update(`${i}:${JSON.stringify(r)}`),n||=!!r.bitmap)}if(n)for(const e of t.values())e.bitmap&&i.push(e.bitmap);return t.size>0?{map:t,hash:e.hexdigest(),transfer:i}:Ft}get editorStats(){let t=null;const e=new Map;for(const i of this.#Ie.values()){if(!(i instanceof kt))continue;const s=i.telemetryFinalData;if(!s)continue;const{type:n}=s;e.has(n)||e.set(n,Object.getPrototypeOf(i).constructor),t||=Object.create(null);const a=t[n]||=new Map;for(const[t,e]of Object.entries(s)){if("type"===t)continue;let i=a.get(t);i||(i=new Map,a.set(t,i));const s=i.get(e)??0;i.set(e,s+1)}}for(const[i,s]of e)t[i]=s.computeTelemetryFinalData(t[i]);return t}resetModifiedIds(){this.#ke=null}get modifiedIds(){if(this.#ke)return this.#ke;const t=[];for(const e of this.#Ie.values())e instanceof kt&&e.annotationElementId&&e.serialize()&&t.push(e.annotationElementId);return this.#ke={ids:new Set(t),hash:t.join(",")}}}class Ot extends Nt{#Re;constructor(t){super();const{map:e,hash:i,transfer:s}=t.serializable,n=structuredClone(e,s?{transfer:s}:null);this.#Re={map:n,hash:i,transfer:s}}get print(){_("Should not call PrintAnnotationStorage.print")}get serializable(){return this.#Re}get modifiedIds(){return E(this,"modifiedIds",{ids:new Set,hash:""})}}class Bt{#De=new Set;constructor({ownerDocument:t=globalThis.document,styleElement:e=null}){this._document=t,this.nativeFontFaces=new Set,this.styleElement=null,this.loadingRequests=[],this.loadTestFontId=0}addNativeFontFace(t){this.nativeFontFaces.add(t),this._document.fonts.add(t)}removeNativeFontFace(t){this.nativeFontFaces.delete(t),this._document.fonts.delete(t)}insertRule(t){this.styleElement||(this.styleElement=this._document.createElement("style"),this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement));const e=this.styleElement.sheet;e.insertRule(t,e.cssRules.length)}clear(){for(const t of this.nativeFontFaces)this._document.fonts.delete(t);this.nativeFontFaces.clear(),this.#De.clear(),this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}async loadSystemFont({systemFontInfo:t,_inspectFont:e}){if(t&&!this.#De.has(t.loadedName))if(x(!this.disableFontFace,"loadSystemFont shouldn't be called when `disableFontFace` is set."),this.isFontLoadingAPISupported){const{loadedName:i,src:s,style:n}=t,a=new FontFace(i,s,n);this.addNativeFontFace(a);try{await a.load(),this.#De.add(i),e?.(t)}catch{w(`Cannot load system font: ${t.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(a)}}else _("Not implemented: loadSystemFont without the Font Loading API.")}async bind(t){if(t.attached||t.missingFile&&!t.systemFontInfo)return;if(t.attached=!0,t.systemFontInfo)return void await this.loadSystemFont(t);if(this.isFontLoadingAPISupported){const e=t.createNativeFontFace();if(e){this.addNativeFontFace(e);try{await e.loaded}catch(i){throw w(`Failed to load font '${e.family}': '${i}'.`),t.disableFontFace=!0,i}}return}const e=t.createFontFaceRule();if(e){if(this.insertRule(e),this.isSyncFontLoadingSupported)return;await new Promise((e=>{const i=this._queueLoadingCallback(e);this._prepareFontLoadEvent(t,i)}))}}get isFontLoadingAPISupported(){return E(this,"isFontLoadingAPISupported",!!this._document?.fonts)}get isSyncFontLoadingSupported(){let t=!1;return(n||"undefined"!=typeof navigator&&"string"==typeof navigator?.userAgent&&/Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent))&&(t=!0),E(this,"isSyncFontLoadingSupported",t)}_queueLoadingCallback(t){const{loadingRequests:e}=this,i={done:!1,complete:function(){for(x(!i.done,"completeRequest() cannot be called twice."),i.done=!0;e.length>0&&e[0].done;){const t=e.shift();setTimeout(t.callback,0)}},callback:t};return e.push(i),i}get _loadTestFont(){return E(this,"_loadTestFont",atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA=="))}_prepareFontLoadEvent(t,e){function i(t,e){return t.charCodeAt(e)<<24|t.charCodeAt(e+1)<<16|t.charCodeAt(e+2)<<8|255&t.charCodeAt(e+3)}function s(t,e,i,s){return t.substring(0,e)+s+t.substring(e+i)}let n,a;const r=this._document.createElement("canvas");r.width=1,r.height=1;const o=r.getContext("2d");let l=0;const h=`lt${Date.now()}${this.loadTestFontId++}`;let d=this._loadTestFont;d=s(d,976,h.length,h);const c=1482184792;let u=i(d,16);for(n=0,a=h.length-3;n>24&255,p>>16&255,p>>8&255,255&p)));const g=`@font-face {font-family:"${h}";src:url(data:font/opentype;base64,${btoa(d)});}`;this.insertRule(g);const m=this._document.createElement("div");m.style.visibility="hidden",m.style.width=m.style.height="10px",m.style.position="absolute",m.style.top=m.style.left="0px";for(const e of[t.loadedName,h]){const t=this._document.createElement("span");t.textContent="Hi",t.style.fontFamily=e,m.append(t)}this._document.body.append(m),function t(e,i){if(++l>30)return w("Load test font never loaded."),void i();o.font="30px "+e,o.fillText(".",0,20),o.getImageData(0,0,1,1).data[3]>0?i():setTimeout(t.bind(null,e,i))}(h,(()=>{m.remove(),e.complete()}))}}class zt{constructor(t,{disableFontFace:e=!1,inspectFont:i=null}){this.compiledGlyphs=Object.create(null);for(const e in t)this[e]=t[e];this.disableFontFace=!0===e,this._inspectFont=i}createNativeFontFace(){if(!this.data||this.disableFontFace)return null;let t;if(this.cssFontInfo){const e={weight:this.cssFontInfo.fontWeight};this.cssFontInfo.italicAngle&&(e.style=`oblique ${this.cssFontInfo.italicAngle}deg`),t=new FontFace(this.cssFontInfo.fontFamily,this.data,e)}else t=new FontFace(this.loadedName,this.data,{});return this._inspectFont?.(this),t}createFontFaceRule(){if(!this.data||this.disableFontFace)return null;const t=L(this.data),e=`url(data:${this.mimetype};base64,${btoa(t)});`;let i;if(this.cssFontInfo){let t=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(t+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`),i=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${t}src:${e}}`}else i=`@font-face {font-family:"${this.loadedName}";src:${e}}`;return this._inspectFont?.(this,e),i}getPathGenerator(t,e){if(void 0!==this.compiledGlyphs[e])return this.compiledGlyphs[e];let i;try{i=t.get(this.loadedName+"_path_"+e)}catch(t){w(`getPathGenerator - ignoring character: "${t}".`)}if(!Array.isArray(i)||0===i.length)return this.compiledGlyphs[e]=function(t,e){};const s=[];for(let t=0,e=i.length;tt.bezierCurveTo(e,n,a,r,o,l))),t+=6}break;case 1:{const[e,n]=i.slice(t,t+2);s.push((t=>t.moveTo(e,n))),t+=2}break;case 2:{const[e,n]=i.slice(t,t+2);s.push((t=>t.lineTo(e,n))),t+=2}break;case 3:{const[e,n,a,r]=i.slice(t,t+4);s.push((t=>t.quadraticCurveTo(e,n,a,r))),t+=4}break;case 4:s.push((t=>t.restore()));break;case 5:s.push((t=>t.save()));break;case 6:x(2===s.length,"Scale command is only valid at the third position.");break;case 7:{const[e,n,a,r,o,l]=i.slice(t,t+6);s.push((t=>t.transform(e,n,a,r,o,l))),t+=6}break;case 8:{const[e,n]=i.slice(t,t+2);s.push((t=>t.translate(e,n))),t+=2}}return this.compiledGlyphs[e]=function(t,e){s[0](t),s[1](t),t.scale(e,-e);for(let e=2,i=s.length;e{const t=await import("fs"),e=await import("http"),i=await import("https"),s=await import("url");return new Map(Object.entries({fs:t,http:e,https:i,url:s,canvas:void 0,path2d:void 0}))})().then((t=>{jt=t,Ht.resolve()}),(t=>{w(`loadPackages: ${t}`),jt=new Map,Ht.resolve()}))}class Ut{static get promise(){return Ht.promise}static get(t){return jt?.get(t)}}const $t=function(t){return Ut.get("fs").promises.readFile(t).then((t=>new Uint8Array(t)))},Wt="Fill",Gt="Stroke",Vt="Shading";function qt(t,e){if(!e)return;const i=e[2]-e[0],s=e[3]-e[1],n=new Path2D;n.rect(e[0],e[1],i,s),t.clip(n)}class Xt{getPattern(){_("Abstract method `getPattern` called.")}}class Kt extends Xt{constructor(t){super(),this._type=t[1],this._bbox=t[2],this._colorStops=t[3],this._p0=t[4],this._p1=t[5],this._r0=t[6],this._r1=t[7],this.matrix=null}_createGradient(t){let e;"axial"===this._type?e=t.createLinearGradient(this._p0[0],this._p0[1],this._p1[0],this._p1[1]):"radial"===this._type&&(e=t.createRadialGradient(this._p0[0],this._p0[1],this._r0,this._p1[0],this._p1[1],this._r1));for(const t of this._colorStops)e.addColorStop(t[0],t[1]);return e}getPattern(t,e,i,s){let n;if(s===Gt||s===Wt){const a=e.current.getClippedPathBoundingBox(s,mt(t))||[0,0,0,0],r=Math.ceil(a[2]-a[0])||1,o=Math.ceil(a[3]-a[1])||1,l=e.cachedCanvases.getCanvas("pattern",r,o),h=l.context;h.clearRect(0,0,h.canvas.width,h.canvas.height),h.beginPath(),h.rect(0,0,h.canvas.width,h.canvas.height),h.translate(-a[0],-a[1]),i=z.transform(i,[1,0,0,1,a[0],a[1]]),h.transform(...e.baseTransform),this.matrix&&h.transform(...this.matrix),qt(h,this._bbox),h.fillStyle=this._createGradient(h),h.fill(),n=t.createPattern(l.canvas,"no-repeat");const d=new DOMMatrix(i);n.setTransform(d)}else qt(t,this._bbox),n=this._createGradient(t);return n}}function Yt(t,e,i,s,n,a,r,o){const l=e.coords,h=e.colors,d=t.data,c=4*t.width;let u;l[i+1]>l[s+1]&&(u=i,i=s,s=u,u=a,a=r,r=u),l[s+1]>l[n+1]&&(u=s,s=n,n=u,u=r,r=o,o=u),l[i+1]>l[s+1]&&(u=i,i=s,s=u,u=a,a=r,r=u);const p=(l[i]+e.offsetX)*e.scaleX,g=(l[i+1]+e.offsetY)*e.scaleY,m=(l[s]+e.offsetX)*e.scaleX,f=(l[s+1]+e.offsetY)*e.scaleY,b=(l[n]+e.offsetX)*e.scaleX,v=(l[n+1]+e.offsetY)*e.scaleY;if(g>=v)return;const A=h[a],y=h[a+1],w=h[a+2],_=h[r],x=h[r+1],C=h[r+2],E=h[o],S=h[o+1],T=h[o+2],M=Math.round(g),k=Math.round(v);let I,P,R,D,L,F,N,O;for(let t=M;t<=k;t++){if(tv?1:f===v?0:(f-t)/(f-v),I=m-(m-b)*e,P=_-(_-E)*e,R=x-(x-S)*e,D=C-(C-T)*e}let e;e=tv?1:(g-t)/(g-v),L=p-(p-b)*e,F=A-(A-E)*e,N=y-(y-S)*e,O=w-(w-T)*e;const i=Math.round(Math.min(I,L)),s=Math.round(Math.max(I,L));let n=c*t+4*i;for(let t=i;t<=s;t++)e=(I-t)/(I-L),e<0?e=0:e>1&&(e=1),d[n++]=P-(P-F)*e|0,d[n++]=R-(R-N)*e|0,d[n++]=D-(D-O)*e|0,d[n++]=255}}function Qt(t,e,i){const s=e.coords,n=e.colors;let a,r;switch(e.type){case"lattice":const o=e.verticesPerRow,l=Math.floor(s.length/o)-1,h=o-1;for(a=0;a=Math.ceil(p*b)?A=o:_=!0,E>=Math.ceil(g*v)?w=l:x=!0;const S=this.getSizeAndScale(A,this.ctx.canvas.width,b),T=this.getSizeAndScale(w,this.ctx.canvas.height,v),M=t.cachedCanvases.getCanvas("pattern",S.size,T.size),k=M.context,I=r.createCanvasGraphics(k);if(I.groupLevel=t.groupLevel,this.setFillAndStrokeStyleToContext(I,s,a),k.translate(-S.scale*h,-T.scale*d),I.transform(S.scale,0,0,T.scale,0,0),k.save(),this.clipBbox(I,h,d,c,u),I.baseTransform=mt(I.ctx),I.executeOperatorList(i),I.endDrawing(),k.restore(),_||x){const e=M.canvas;_&&(A=o),x&&(w=l);const i=this.getSizeAndScale(A,this.ctx.canvas.width,b),s=this.getSizeAndScale(w,this.ctx.canvas.height,v),n=i.size,a=s.size,r=t.cachedCanvases.getCanvas("pattern-workaround",n,a),c=r.context,u=_?Math.floor(p/o):0,m=x?Math.floor(g/l):0;for(let t=0;t<=u;t++)for(let i=0;i<=m;i++)c.drawImage(e,n*t,a*i,n,a,0,0,n,a);return{canvas:r.canvas,scaleX:i.scale,scaleY:s.scale,offsetX:h,offsetY:d}}return{canvas:M.canvas,scaleX:S.scale,scaleY:T.scale,offsetX:h,offsetY:d}}getSizeAndScale(t,e,i){const s=Math.max(te.MAX_PATTERN_SIZE,e);let n=Math.ceil(t*i);return n>=s?n=s:i=n/t,{scale:i,size:n}}clipBbox(t,e,i,s,n){const a=s-e,r=n-i;t.ctx.rect(e,i,a,r),t.current.updateRectMinMax(mt(t.ctx),[e,i,s,n]),t.clip(),t.endPath()}setFillAndStrokeStyleToContext(t,e,i){const s=t.ctx,n=t.current;switch(e){case 1:const t=this.ctx;s.fillStyle=t.fillStyle,s.strokeStyle=t.strokeStyle,n.fillColor=t.fillStyle,n.strokeColor=t.strokeStyle;break;case 2:const a=z.makeHexColor(i[0],i[1],i[2]);s.fillStyle=a,s.strokeStyle=a,n.fillColor=a,n.strokeColor=a;break;default:throw new R(`Unsupported paint type: ${e}`)}}getPattern(t,e,i,s){let n=i;s!==Vt&&(n=z.transform(n,e.baseTransform),this.matrix&&(n=z.transform(n,this.matrix)));const a=this.createPatternCanvas(e);let r=new DOMMatrix(n);r=r.translate(a.offsetX,a.offsetY),r=r.scale(1/a.scaleX,1/a.scaleY);const o=t.createPattern(a.canvas,"repeat");return o.setTransform(r),o}}function ee({src:t,srcPos:e=0,dest:i,width:s,height:n,nonBlackColor:a=4294967295,inverseDecode:r=!1}){const o=O.isLittleEndian?4278190080:255,[l,h]=r?[a,o]:[o,a],d=s>>3,c=7&s,u=t.length;i=new Uint32Array(i.buffer);let p=0;for(let s=0;s>2),u=i.length,f=s+7>>3,b=4294967295,v=O.isLittleEndian?4278190080:255;for(p=0;pf?s:8*t-7,r=-8&a;let o=0,c=0;for(;n>=1}for(;l=a&&(m=n,f=s*m),l=0,g=f;g--;)c[l++]=d[h++],c[l++]=d[h++],c[l++]=d[h++],c[l++]=255;t.putImageData(o,0,p*ie)}}}function oe(t,e){if(e.bitmap)return void t.drawImage(e.bitmap,0,0);const i=e.height,s=e.width,n=i%ie,a=(i-n)/ie,r=0===n?a:a+1,o=t.createImageData(s,ie);let l=0;const h=e.data,d=o.data;for(let e=0;e10&&"function"==typeof i,h=l?Date.now()+15:0;let d=0;const c=this.commonObjs,u=this.objs;let p;for(;;){if(void 0!==s&&r===s.nextBreakPoint)return s.breakIt(r,i),r;if(p=a[r],p!==m.dependency)this[p].apply(this,n[r]);else for(const t of n[r]){const e=t.startsWith("g_")?c:u;if(!e.has(t))return e.get(t,i),r}if(r++,r===o)return r;if(l&&++d>10){if(Date.now()>h)return i(),r;d=0}}}#Le(){for(;this.stateStack.length||this.inSMaskMode;)this.restore();this.current.activeSMask=null,this.ctx.restore(),this.transparentCanvas&&(this.ctx=this.compositeCtx,this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.drawImage(this.transparentCanvas,0,0),this.ctx.restore(),this.transparentCanvas=null)}endDrawing(){this.#Le(),this.cachedCanvases.clear(),this.cachedPatterns.clear();for(const t of this._cachedBitmapsMap.values()){for(const e of t.values())"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement&&(e.width=e.height=0);t.clear()}this._cachedBitmapsMap.clear(),this.#Fe()}#Fe(){if(this.pageColors){const t=this.filterFactory.addHCMFilter(this.pageColors.foreground,this.pageColors.background);if("none"!==t){const e=this.ctx.filter;this.ctx.filter=t,this.ctx.drawImage(this.ctx.canvas,0,0),this.ctx.filter=e}}}_scaleImage(t,e){const i=t.width,s=t.height;let n,a,r=Math.max(Math.hypot(e[0],e[1]),1),o=Math.max(Math.hypot(e[2],e[3]),1),l=i,h=s,d="prescale1";for(;r>2&&l>1||o>2&&h>1;){let e=l,i=h;r>2&&l>1&&(e=l>=16384?Math.floor(l/2)-1||1:Math.ceil(l/2),r/=l/e),o>2&&h>1&&(i=h>=16384?Math.floor(h/2)-1||1:Math.ceil(h)/2,o/=h/i),n=this.cachedCanvases.getCanvas(d,e,i),a=n.context,a.clearRect(0,0,e,i),a.drawImage(t,0,0,l,h,0,0,e,i),t=n.canvas,l=e,h=i,d="prescale1"===d?"prescale2":"prescale1"}return{img:t,paintWidth:l,paintHeight:h}}_createMaskCanvas(t){const e=this.ctx,{width:i,height:s}=t,n=this.current.fillColor,a=this.current.patternFill,r=mt(e);let o,l,h,d;if((t.bitmap||t.data)&&t.count>1){const e=t.bitmap||t.data.buffer;l=JSON.stringify(a?r:[r.slice(0,4),n]),o=this._cachedBitmapsMap.get(e),o||(o=new Map,this._cachedBitmapsMap.set(e,o));const i=o.get(l);if(i&&!a)return{canvas:i,offsetX:Math.round(Math.min(r[0],r[2])+r[4]),offsetY:Math.round(Math.min(r[1],r[3])+r[5])};h=i}h||(d=this.cachedCanvases.getCanvas("maskCanvas",i,s),oe(d.context,t));let c=z.transform(r,[1/i,0,0,-1/s,0,0]);c=z.transform(c,[1,0,0,1,0,-s]);const[u,p,g,m]=z.getAxialAlignedBoundingBox([0,0,i,s],c),f=Math.round(g-u)||1,b=Math.round(m-p)||1,v=this.cachedCanvases.getCanvas("fillCanvas",f,b),A=v.context,y=u,w=p;A.translate(-y,-w),A.transform(...c),h||(h=this._scaleImage(d.canvas,ft(A)),h=h.img,o&&a&&o.set(l,h)),A.imageSmoothingEnabled=de(mt(A),t.interpolate),ne(A,h,0,0,h.width,h.height,0,0,i,s),A.globalCompositeOperation="source-in";const _=z.transform(ft(A),[1,0,0,1,-y,-w]);return A.fillStyle=a?n.getPattern(e,this,_,Wt):n,A.fillRect(0,0,i,s),o&&!a&&(this.cachedCanvases.delete("fillCanvas"),o.set(l,v.canvas)),{canvas:v.canvas,offsetX:Math.round(y),offsetY:Math.round(w)}}setLineWidth(t){t!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=t,this.ctx.lineWidth=t}setLineCap(t){this.ctx.lineCap=ce[t]}setLineJoin(t){this.ctx.lineJoin=ue[t]}setMiterLimit(t){this.ctx.miterLimit=t}setDash(t,e){const i=this.ctx;void 0!==i.setLineDash&&(i.setLineDash(t),i.lineDashOffset=e)}setRenderingIntent(t){}setFlatness(t){}setGState(t){for(const[e,i]of t)switch(e){case"LW":this.setLineWidth(i);break;case"LC":this.setLineCap(i);break;case"LJ":this.setLineJoin(i);break;case"ML":this.setMiterLimit(i);break;case"D":this.setDash(i[0],i[1]);break;case"RI":this.setRenderingIntent(i);break;case"FL":this.setFlatness(i);break;case"Font":this.setFont(i[0],i[1]);break;case"CA":this.current.strokeAlpha=i;break;case"ca":this.current.fillAlpha=i,this.ctx.globalAlpha=i;break;case"BM":this.ctx.globalCompositeOperation=i;break;case"SMask":this.current.activeSMask=i?this.tempSMask:null,this.tempSMask=null,this.checkSMaskState();break;case"TR":this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(i)}}get inSMaskMode(){return!!this.suspendedCtx}checkSMaskState(){const t=this.inSMaskMode;this.current.activeSMask&&!t?this.beginSMaskMode():!this.current.activeSMask&&t&&this.endSMaskMode()}beginSMaskMode(){if(this.inSMaskMode)throw new Error("beginSMaskMode called while already in smask mode");const t=this.ctx.canvas.width,e=this.ctx.canvas.height,i="smaskGroupAt"+this.groupLevel,s=this.cachedCanvases.getCanvas(i,t,e);this.suspendedCtx=this.ctx,this.ctx=s.context;const n=this.ctx;n.setTransform(...mt(this.suspendedCtx)),le(this.suspendedCtx,n),function(t,e){if(t._removeMirroring)throw new Error("Context is already forwarding operations.");t.__originalSave=t.save,t.__originalRestore=t.restore,t.__originalRotate=t.rotate,t.__originalScale=t.scale,t.__originalTranslate=t.translate,t.__originalTransform=t.transform,t.__originalSetTransform=t.setTransform,t.__originalResetTransform=t.resetTransform,t.__originalClip=t.clip,t.__originalMoveTo=t.moveTo,t.__originalLineTo=t.lineTo,t.__originalBezierCurveTo=t.bezierCurveTo,t.__originalRect=t.rect,t.__originalClosePath=t.closePath,t.__originalBeginPath=t.beginPath,t._removeMirroring=()=>{t.save=t.__originalSave,t.restore=t.__originalRestore,t.rotate=t.__originalRotate,t.scale=t.__originalScale,t.translate=t.__originalTranslate,t.transform=t.__originalTransform,t.setTransform=t.__originalSetTransform,t.resetTransform=t.__originalResetTransform,t.clip=t.__originalClip,t.moveTo=t.__originalMoveTo,t.lineTo=t.__originalLineTo,t.bezierCurveTo=t.__originalBezierCurveTo,t.rect=t.__originalRect,t.closePath=t.__originalClosePath,t.beginPath=t.__originalBeginPath,delete t._removeMirroring},t.save=function(){e.save(),this.__originalSave()},t.restore=function(){e.restore(),this.__originalRestore()},t.translate=function(t,i){e.translate(t,i),this.__originalTranslate(t,i)},t.scale=function(t,i){e.scale(t,i),this.__originalScale(t,i)},t.transform=function(t,i,s,n,a,r){e.transform(t,i,s,n,a,r),this.__originalTransform(t,i,s,n,a,r)},t.setTransform=function(t,i,s,n,a,r){e.setTransform(t,i,s,n,a,r),this.__originalSetTransform(t,i,s,n,a,r)},t.resetTransform=function(){e.resetTransform(),this.__originalResetTransform()},t.rotate=function(t){e.rotate(t),this.__originalRotate(t)},t.clip=function(t){e.clip(t),this.__originalClip(t)},t.moveTo=function(t,i){e.moveTo(t,i),this.__originalMoveTo(t,i)},t.lineTo=function(t,i){e.lineTo(t,i),this.__originalLineTo(t,i)},t.bezierCurveTo=function(t,i,s,n,a,r){e.bezierCurveTo(t,i,s,n,a,r),this.__originalBezierCurveTo(t,i,s,n,a,r)},t.rect=function(t,i,s,n){e.rect(t,i,s,n),this.__originalRect(t,i,s,n)},t.closePath=function(){e.closePath(),this.__originalClosePath()},t.beginPath=function(){e.beginPath(),this.__originalBeginPath()}}(n,this.suspendedCtx),this.setGState([["BM","source-over"],["ca",1],["CA",1]])}endSMaskMode(){if(!this.inSMaskMode)throw new Error("endSMaskMode called while not in smask mode");this.ctx._removeMirroring(),le(this.ctx,this.suspendedCtx),this.ctx=this.suspendedCtx,this.suspendedCtx=null}compose(t){if(!this.current.activeSMask)return;t?(t[0]=Math.floor(t[0]),t[1]=Math.floor(t[1]),t[2]=Math.ceil(t[2]),t[3]=Math.ceil(t[3])):t=[0,0,this.ctx.canvas.width,this.ctx.canvas.height];const e=this.current.activeSMask,i=this.suspendedCtx;this.composeSMask(i,e,this.ctx,t),this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height),this.ctx.restore()}composeSMask(t,e,i,s){const n=s[0],a=s[1],r=s[2]-n,o=s[3]-a;0!==r&&0!==o&&(this.genericComposeSMask(e.context,i,r,o,e.subtype,e.backdrop,e.transferMap,n,a,e.offsetX,e.offsetY),t.save(),t.globalAlpha=1,t.globalCompositeOperation="source-over",t.setTransform(1,0,0,1,0,0),t.drawImage(i.canvas,0,0),t.restore())}genericComposeSMask(t,e,i,s,n,a,r,o,l,h,d){let c=t.canvas,u=o-h,p=l-d;if(a)if(u<0||p<0||u+i>c.width||p+s>c.height){const t=this.cachedCanvases.getCanvas("maskExtension",i,s),e=t.context;e.drawImage(c,-u,-p),a.some((t=>0!==t))&&(e.globalCompositeOperation="destination-atop",e.fillStyle=z.makeHexColor(...a),e.fillRect(0,0,i,s),e.globalCompositeOperation="source-over"),c=t.canvas,u=p=0}else if(a.some((t=>0!==t))){t.save(),t.globalAlpha=1,t.setTransform(1,0,0,1,0,0);const e=new Path2D;e.rect(u,p,i,s),t.clip(e),t.globalCompositeOperation="destination-atop",t.fillStyle=z.makeHexColor(...a),t.fillRect(u,p,i,s),t.restore()}e.save(),e.globalAlpha=1,e.setTransform(1,0,0,1,0,0),"Alpha"===n&&r?e.filter=this.filterFactory.addAlphaFilter(r):"Luminosity"===n&&(e.filter=this.filterFactory.addLuminosityFilter(r));const g=new Path2D;g.rect(o,l,i,s),e.clip(g),e.globalCompositeOperation="destination-in",e.drawImage(c,u,p,i,s,o,l,i,s),e.restore()}save(){this.inSMaskMode?(le(this.ctx,this.suspendedCtx),this.suspendedCtx.save()):this.ctx.save();const t=this.current;this.stateStack.push(t),this.current=t.clone()}restore(){0===this.stateStack.length&&this.inSMaskMode&&this.endSMaskMode(),0!==this.stateStack.length&&(this.current=this.stateStack.pop(),this.inSMaskMode?(this.suspendedCtx.restore(),le(this.suspendedCtx,this.ctx)):this.ctx.restore(),this.checkSMaskState(),this.pendingClip=null,this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null)}transform(t,e,i,s,n,a){this.ctx.transform(t,e,i,s,n,a),this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null}constructPath(t,e,i){const s=this.ctx,n=this.current;let a,r,o=n.x,l=n.y;const h=mt(s),d=0===h[0]&&0===h[3]||0===h[1]&&0===h[2],c=d?i.slice(0):null;for(let i=0,u=0,p=t.length;i100&&(h=100),this.current.fontSizeScale=e/h,this.ctx.font=`${l} ${o} ${h}px ${a}`}setTextRenderingMode(t){this.current.textRenderingMode=t}setTextRise(t){this.current.textRise=t}moveText(t,e){this.current.x=this.current.lineX+=t,this.current.y=this.current.lineY+=e}setLeadingMoveText(t,e){this.setLeading(-e),this.moveText(t,e)}setTextMatrix(t,e,i,s,n,a){this.current.textMatrix=[t,e,i,s,n,a],this.current.textMatrixScale=Math.hypot(t,e),this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0}nextLine(){this.moveText(0,this.current.leading)}paintChar(t,e,i,s){const n=this.ctx,a=this.current,r=a.font,o=a.textRenderingMode,l=a.fontSize/a.fontSizeScale,h=3&o,d=!!(4&o),c=a.patternFill&&!r.missingFile;let u;(r.disableFontFace||d||c)&&(u=r.getPathGenerator(this.commonObjs,t)),r.disableFontFace||c?(n.save(),n.translate(e,i),n.beginPath(),u(n,l),s&&n.setTransform(...s),0!==h&&2!==h||n.fill(),1!==h&&2!==h||n.stroke(),n.restore()):(0!==h&&2!==h||n.fillText(t,e,i),1!==h&&2!==h||n.strokeText(t,e,i)),d&&(this.pendingTextPaths||=[]).push({transform:mt(n),x:e,y:i,fontSize:l,addToPath:u})}get isFontSubpixelAAEnabled(){const{context:t}=this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled",10,10);t.scale(1.5,1),t.fillText("I",0,10);const e=t.getImageData(0,0,10,10).data;let i=!1;for(let t=3;t0&&e[t]<255){i=!0;break}return E(this,"isFontSubpixelAAEnabled",i)}showText(t){const e=this.current,i=e.font;if(i.isType3Font)return this.showType3Text(t);const s=e.fontSize;if(0===s)return;const n=this.ctx,a=e.fontSizeScale,r=e.charSpacing,o=e.wordSpacing,l=e.fontDirection,h=e.textHScale*l,d=t.length,c=i.vertical,u=c?1:-1,p=i.defaultVMetrics,g=s*e.fontMatrix[0],m=0===e.textRenderingMode&&!i.disableFontFace&&!e.patternFill;let f;if(n.save(),n.transform(...e.textMatrix),n.translate(e.x,e.y+e.textRise),l>0?n.scale(h,-1):n.scale(h,1),e.patternFill){n.save();const t=e.fillColor.getPattern(n,this,ft(n),Wt);f=mt(n),n.restore(),n.fillStyle=t}let b=e.lineWidth;const v=e.textMatrixScale;if(0===v||0===b){const t=3&e.textRenderingMode;1!==t&&2!==t||(b=this.getSinglePixelWidth())}else b/=v;if(1!==a&&(n.scale(a,a),b/=a),n.lineWidth=b,i.isInvalidPDFjsFont){const i=[];let s=0;for(const e of t)i.push(e.unicode),s+=e.width;return n.fillText(i.join(""),0,0),e.x+=s*g*h,n.restore(),void this.compose()}let A,y=0;for(A=0;A0){const t=1e3*n.measureText(b).width/s*a;if(xnew me(t,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack})};e=new te(t,i,this.ctx,n,s)}else e=this._getPattern(t[1],t[2]);return e}setStrokeColorN(){this.current.strokeColor=this.getColorN_Pattern(arguments)}setFillColorN(){this.current.fillColor=this.getColorN_Pattern(arguments),this.current.patternFill=!0}setStrokeRGBColor(t,e,i){this.ctx.strokeStyle=this.current.strokeColor=z.makeHexColor(t,e,i)}setStrokeTransparent(){this.ctx.strokeStyle=this.current.strokeColor="transparent"}setFillRGBColor(t,e,i){this.ctx.fillStyle=this.current.fillColor=z.makeHexColor(t,e,i),this.current.patternFill=!1}setFillTransparent(){this.ctx.fillStyle=this.current.fillColor="transparent",this.current.patternFill=!1}_getPattern(t,e=null){let i;return this.cachedPatterns.has(t)?i=this.cachedPatterns.get(t):(i=function(t){switch(t[0]){case"RadialAxial":return new Kt(t);case"Mesh":return new Jt(t);case"Dummy":return new Zt}throw new Error(`Unknown IR type: ${t[0]}`)}(this.getObject(t)),this.cachedPatterns.set(t,i)),e&&(i.matrix=e),i}shadingFill(t){if(!this.contentVisible)return;const e=this.ctx;this.save();const i=this._getPattern(t);e.fillStyle=i.getPattern(e,this,ft(e),Vt);const s=ft(e);if(s){const{width:t,height:i}=e.canvas,[n,a,r,o]=z.getAxialAlignedBoundingBox([0,0,t,i],s);this.ctx.fillRect(n,a,r-n,o-a)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.compose(this.current.getClippedPathBoundingBox()),this.restore()}beginInlineImage(){_("Should not call beginInlineImage")}beginImageData(){_("Should not call beginImageData")}paintFormXObjectBegin(t,e){if(this.contentVisible&&(this.save(),this.baseTransformStack.push(this.baseTransform),t&&this.transform(...t),this.baseTransform=mt(this.ctx),e)){const t=e[2]-e[0],i=e[3]-e[1];this.ctx.rect(e[0],e[1],t,i),this.current.updateRectMinMax(mt(this.ctx),e),this.clip(),this.endPath()}}paintFormXObjectEnd(){this.contentVisible&&(this.restore(),this.baseTransform=this.baseTransformStack.pop())}beginGroup(t){if(!this.contentVisible)return;this.save(),this.inSMaskMode&&(this.endSMaskMode(),this.current.activeSMask=null);const e=this.ctx;t.isolated||y("TODO: Support non-isolated groups."),t.knockout&&w("Knockout groups not supported.");const i=mt(e);if(t.matrix&&e.transform(...t.matrix),!t.bbox)throw new Error("Bounding box is required.");let s=z.getAxialAlignedBoundingBox(t.bbox,mt(e));const n=[0,0,e.canvas.width,e.canvas.height];s=z.intersect(s,n)||[0,0,0,0];const a=Math.floor(s[0]),r=Math.floor(s[1]),o=Math.max(Math.ceil(s[2])-a,1),l=Math.max(Math.ceil(s[3])-r,1);this.current.startNewPathAndClipBox([0,0,o,l]);let h="groupAt"+this.groupLevel;t.smask&&(h+="_smask_"+this.smaskCounter++%2);const d=this.cachedCanvases.getCanvas(h,o,l),c=d.context;c.translate(-a,-r),c.transform(...i),t.smask?this.smaskStack.push({canvas:d.canvas,context:c,offsetX:a,offsetY:r,subtype:t.smask.subtype,backdrop:t.smask.backdrop,transferMap:t.smask.transferMap||null,startTransformInverse:null}):(e.setTransform(1,0,0,1,0,0),e.translate(a,r),e.save()),le(e,c),this.ctx=c,this.setGState([["BM","source-over"],["ca",1],["CA",1]]),this.groupStack.push(e),this.groupLevel++}endGroup(t){if(!this.contentVisible)return;this.groupLevel--;const e=this.ctx,i=this.groupStack.pop();if(this.ctx=i,this.ctx.imageSmoothingEnabled=!1,t.smask)this.tempSMask=this.smaskStack.pop(),this.restore();else{this.ctx.restore();const t=mt(this.ctx);this.restore(),this.ctx.save(),this.ctx.setTransform(...t);const i=z.getAxialAlignedBoundingBox([0,0,e.canvas.width,e.canvas.height],t);this.ctx.drawImage(e.canvas,0,0),this.ctx.restore(),this.compose(i)}}beginAnnotation(t,e,i,s,n){if(this.#Le(),he(this.ctx),this.ctx.save(),this.save(),this.baseTransform&&this.ctx.setTransform(...this.baseTransform),e){const s=e[2]-e[0],a=e[3]-e[1];if(n&&this.annotationCanvasMap){(i=i.slice())[4]-=e[0],i[5]-=e[1],(e=e.slice())[0]=e[1]=0,e[2]=s,e[3]=a;const[n,r]=z.singularValueDecompose2dScale(mt(this.ctx)),{viewportScale:o}=this,l=Math.ceil(s*this.outputScaleX*o),h=Math.ceil(a*this.outputScaleY*o);this.annotationCanvas=this.canvasFactory.create(l,h);const{canvas:d,context:c}=this.annotationCanvas;this.annotationCanvasMap.set(t,d),this.annotationCanvas.savedCtx=this.ctx,this.ctx=c,this.ctx.save(),this.ctx.setTransform(n,0,0,-r,0,a*r),he(this.ctx)}else he(this.ctx),this.endPath(),this.ctx.rect(e[0],e[1],s,a),this.ctx.clip(),this.ctx.beginPath()}this.current=new ae(this.ctx.canvas.width,this.ctx.canvas.height),this.transform(...i),this.transform(...s)}endAnnotation(){this.annotationCanvas&&(this.ctx.restore(),this.#Fe(),this.ctx=this.annotationCanvas.savedCtx,delete this.annotationCanvas.savedCtx,delete this.annotationCanvas)}paintImageMaskXObject(t){if(!this.contentVisible)return;const e=t.count;(t=this.getObject(t.data,t)).count=e;const i=this.ctx,s=this.processingType3;if(s&&(void 0===s.compiled&&(s.compiled=function(t){const{width:e,height:i}=t;if(e>1e3||i>1e3)return null;const s=new Uint8Array([0,2,4,0,1,0,5,4,8,10,0,8,0,2,1,0]),n=e+1;let a,r,o,l=new Uint8Array(n*(i+1));const h=e+7&-8;let d=new Uint8Array(h*i),c=0;for(const e of t.data){let t=128;for(;t>0;)d[c++]=e&t?0:255,t>>=1}let u=0;for(c=0,0!==d[c]&&(l[0]=1,++u),r=1;r>2)+(d[c+1]?4:0)+(d[c-h+1]?8:0),s[t]&&(l[o+r]=s[t],++u),c++;if(d[c-h]!==d[c]&&(l[o+r]=d[c]?2:4,++u),u>1e3)return null}for(c=h*(i-1),o=a*n,0!==d[c]&&(l[o]=8,++u),r=1;r1e3)return null;const p=new Int32Array([0,n,-1,0,-n,0,0,0,1]),g=new Path2D;for(a=0;u&&a<=i;a++){let t=a*n;const i=t+e;for(;t>4,l[t]&=r>>2|r<<2),g.lineTo(t%n,t/n|0),l[t]||--u}while(s!==t);--a}return d=null,l=null,function(t){t.save(),t.scale(1/e,-1/i),t.translate(0,-i),t.fill(g),t.beginPath(),t.restore()}}(t)),s.compiled))return void s.compiled(i);const n=this._createMaskCanvas(t),a=n.canvas;i.save(),i.setTransform(1,0,0,1,0,0),i.drawImage(a,n.offsetX,n.offsetY),i.restore(),this.compose()}paintImageMaskXObjectRepeat(t,e,i=0,s=0,n,a){if(!this.contentVisible)return;t=this.getObject(t.data,t);const r=this.ctx;r.save();const o=mt(r);r.transform(e,i,s,n,0,0);const l=this._createMaskCanvas(t);r.setTransform(1,0,0,1,l.offsetX-o[4],l.offsetY-o[5]);for(let t=0,h=a.length;te?h/e:1,r=l>e?l/e:1}}this._cachedScaleForStroking[0]=a,this._cachedScaleForStroking[1]=r}return this._cachedScaleForStroking}rescaleAndStroke(t){const{ctx:e}=this,{lineWidth:i}=this.current,[s,n]=this.getScaleForStroking();if(e.lineWidth=i||1,1===s&&1===n)return void e.stroke();const a=e.getLineDash();if(t&&e.save(),e.scale(s,n),a.length>0){const t=Math.max(s,n);e.setLineDash(a.map((e=>e/t))),e.lineDashOffset/=t}e.stroke(),t&&e.restore()}isContentVisible(){for(let t=this.markedContentStack.length-1;t>=0;t--)if(!this.markedContentStack[t].visible)return!1;return!0}}for(const t in m)void 0!==me.prototype[t]&&(me.prototype[m[t]]=me.prototype[t]);class fe{static#Ne=null;static#Oe="";static get workerPort(){return this.#Ne}static set workerPort(t){if(!("undefined"!=typeof Worker&&t instanceof Worker)&&null!==t)throw new Error("Invalid `workerPort` type.");this.#Ne=t}static get workerSrc(){return this.#Oe}static set workerSrc(t){if("string"!=typeof t)throw new Error("Invalid `workerSrc` type.");this.#Oe=t}}function be(t){switch(t instanceof Error||"object"==typeof t&&null!==t||_('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),t.name){case"AbortException":return new D(t.message);case"MissingPDFException":return new I(t.message);case"PasswordException":return new T(t.message,t.code);case"UnexpectedResponseException":return new P(t.message,t.status);case"UnknownErrorException":return new M(t.message,t.details);default:return new M(t.message,t.toString())}}class ve{constructor(t,e,i){this.sourceName=t,this.targetName=e,this.comObj=i,this.callbackId=1,this.streamId=1,this.streamSinks=Object.create(null),this.streamControllers=Object.create(null),this.callbackCapabilities=Object.create(null),this.actionHandler=Object.create(null),this._onComObjOnMessage=t=>{const e=t.data;if(e.targetName!==this.sourceName)return;if(e.stream)return void this.#Be(e);if(e.callback){const t=e.callbackId,i=this.callbackCapabilities[t];if(!i)throw new Error(`Cannot resolve callback ${t}`);if(delete this.callbackCapabilities[t],1===e.callback)i.resolve(e.data);else{if(2!==e.callback)throw new Error("Unexpected callback case");i.reject(be(e.reason))}return}const s=this.actionHandler[e.action];if(!s)throw new Error(`Unknown action from worker: ${e.action}`);if(e.callbackId){const t=this.sourceName,n=e.sourceName;new Promise((function(t){t(s(e.data))})).then((function(s){i.postMessage({sourceName:t,targetName:n,callback:1,callbackId:e.callbackId,data:s})}),(function(s){i.postMessage({sourceName:t,targetName:n,callback:2,callbackId:e.callbackId,reason:be(s)})}))}else e.streamId?this.#ze(e):s(e.data)},i.addEventListener("message",this._onComObjOnMessage)}on(t,e){const i=this.actionHandler;if(i[t])throw new Error(`There is already an actionName called "${t}"`);i[t]=e}send(t,e,i){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,data:e},i)}sendWithPromise(t,e,i){const s=this.callbackId++,n=Promise.withResolvers();this.callbackCapabilities[s]=n;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,callbackId:s,data:e},i)}catch(t){n.reject(t)}return n.promise}sendWithStream(t,e,i,s){const n=this.streamId++,a=this.sourceName,r=this.targetName,o=this.comObj;return new ReadableStream({start:i=>{const l=Promise.withResolvers();return this.streamControllers[n]={controller:i,startCall:l,pullCall:null,cancelCall:null,isClosed:!1},o.postMessage({sourceName:a,targetName:r,action:t,streamId:n,data:e,desiredSize:i.desiredSize},s),l.promise},pull:t=>{const e=Promise.withResolvers();return this.streamControllers[n].pullCall=e,o.postMessage({sourceName:a,targetName:r,stream:6,streamId:n,desiredSize:t.desiredSize}),e.promise},cancel:t=>{x(t instanceof Error,"cancel must have a valid reason");const e=Promise.withResolvers();return this.streamControllers[n].cancelCall=e,this.streamControllers[n].isClosed=!0,o.postMessage({sourceName:a,targetName:r,stream:1,streamId:n,reason:be(t)}),e.promise}},i)}#ze(t){const e=t.streamId,i=this.sourceName,s=t.sourceName,n=this.comObj,a=this,r=this.actionHandler[t.action],o={enqueue(t,a=1,r){if(this.isCancelled)return;const o=this.desiredSize;this.desiredSize-=a,o>0&&this.desiredSize<=0&&(this.sinkCapability=Promise.withResolvers(),this.ready=this.sinkCapability.promise),n.postMessage({sourceName:i,targetName:s,stream:4,streamId:e,chunk:t},r)},close(){this.isCancelled||(this.isCancelled=!0,n.postMessage({sourceName:i,targetName:s,stream:3,streamId:e}),delete a.streamSinks[e])},error(t){x(t instanceof Error,"error must have a valid reason"),this.isCancelled||(this.isCancelled=!0,n.postMessage({sourceName:i,targetName:s,stream:5,streamId:e,reason:be(t)}))},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:t.desiredSize,ready:null};o.sinkCapability.resolve(),o.ready=o.sinkCapability.promise,this.streamSinks[e]=o,new Promise((function(e){e(r(t.data,o))})).then((function(){n.postMessage({sourceName:i,targetName:s,stream:8,streamId:e,success:!0})}),(function(t){n.postMessage({sourceName:i,targetName:s,stream:8,streamId:e,reason:be(t)})}))}#Be(t){const e=t.streamId,i=this.sourceName,s=t.sourceName,n=this.comObj,a=this.streamControllers[e],r=this.streamSinks[e];switch(t.stream){case 8:t.success?a.startCall.resolve():a.startCall.reject(be(t.reason));break;case 7:t.success?a.pullCall.resolve():a.pullCall.reject(be(t.reason));break;case 6:if(!r){n.postMessage({sourceName:i,targetName:s,stream:7,streamId:e,success:!0});break}r.desiredSize<=0&&t.desiredSize>0&&r.sinkCapability.resolve(),r.desiredSize=t.desiredSize,new Promise((function(t){t(r.onPull?.())})).then((function(){n.postMessage({sourceName:i,targetName:s,stream:7,streamId:e,success:!0})}),(function(t){n.postMessage({sourceName:i,targetName:s,stream:7,streamId:e,reason:be(t)})}));break;case 4:if(x(a,"enqueue should have stream controller"),a.isClosed)break;a.controller.enqueue(t.chunk);break;case 3:if(x(a,"close should have stream controller"),a.isClosed)break;a.isClosed=!0,a.controller.close(),this.#He(a,e);break;case 5:x(a,"error should have stream controller"),a.controller.error(be(t.reason)),this.#He(a,e);break;case 2:t.success?a.cancelCall.resolve():a.cancelCall.reject(be(t.reason)),this.#He(a,e);break;case 1:if(!r)break;new Promise((function(e){e(r.onCancel?.(be(t.reason)))})).then((function(){n.postMessage({sourceName:i,targetName:s,stream:2,streamId:e,success:!0})}),(function(t){n.postMessage({sourceName:i,targetName:s,stream:2,streamId:e,reason:be(t)})})),r.sinkCapability.reject(be(t.reason)),r.isCancelled=!0,delete this.streamSinks[e];break;default:throw new Error("Unexpected stream case")}}async#He(t,e){await Promise.allSettled([t.startCall?.promise,t.pullCall?.promise,t.cancelCall?.promise]),delete this.streamControllers[e]}destroy(){this.comObj.removeEventListener("message",this._onComObjOnMessage)}}class Ae{#je;#Ue;constructor({parsedData:t,rawData:e}){this.#je=t,this.#Ue=e}getRaw(){return this.#Ue}get(t){return this.#je.get(t)??null}getAll(){return N(this.#je)}has(t){return this.#je.has(t)}}const ye=Symbol("INTERNAL");class we{#$e=!1;#We=!1;#Ge=!1;#Ve=!0;constructor(t,{name:e,intent:i,usage:s}){this.#$e=!!(2&t),this.#We=!!(4&t),this.name=e,this.intent=i,this.usage=s}get visible(){if(this.#Ge)return this.#Ve;if(!this.#Ve)return!1;const{print:t,view:e}=this.usage;return this.#$e?"OFF"!==e?.viewState:!this.#We||"OFF"!==t?.printState}_setVisible(t,e,i=!1){t!==ye&&_("Internal method `_setVisible` called."),this.#Ge=i,this.#Ve=e}}class _e{#qe=null;#Xe=new Map;#Ke=null;#Ye=null;constructor(t,e=2){if(this.renderingIntent=e,this.name=null,this.creator=null,null!==t){this.name=t.name,this.creator=t.creator,this.#Ye=t.order;for(const i of t.groups)this.#Xe.set(i.id,new we(e,i));if("OFF"===t.baseState)for(const t of this.#Xe.values())t._setVisible(ye,!1);for(const e of t.on)this.#Xe.get(e)._setVisible(ye,!0);for(const e of t.off)this.#Xe.get(e)._setVisible(ye,!1);this.#Ke=this.getHash()}}#Qe(t){const e=t.length;if(e<2)return!0;const i=t[0];for(let s=1;s0?N(this.#Xe):null}getGroup(t){return this.#Xe.get(t)||null}getHash(){if(null!==this.#qe)return this.#qe;const t=new Lt;for(const[e,i]of this.#Xe)t.update(`${e}:${i.visible}`);return this.#qe=t.hexdigest()}}class xe{constructor(t,{disableRange:e=!1,disableStream:i=!1}){x(t,'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');const{length:s,initialData:n,progressiveDone:a,contentDispositionFilename:r}=t;if(this._queuedChunks=[],this._progressiveDone=a,this._contentDispositionFilename=r,n?.length>0){const t=n instanceof Uint8Array&&n.byteLength===n.buffer.byteLength?n.buffer:new Uint8Array(n).buffer;this._queuedChunks.push(t)}this._pdfDataRangeTransport=t,this._isStreamingSupported=!i,this._isRangeSupported=!e,this._contentLength=s,this._fullRequestReader=null,this._rangeReaders=[],t.addRangeListener(((t,e)=>{this._onReceiveData({begin:t,chunk:e})})),t.addProgressListener(((t,e)=>{this._onProgress({loaded:t,total:e})})),t.addProgressiveReadListener((t=>{this._onReceiveData({chunk:t})})),t.addProgressiveDoneListener((()=>{this._onProgressiveDone()})),t.transportReady()}_onReceiveData({begin:t,chunk:e}){const i=e instanceof Uint8Array&&e.byteLength===e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer;void 0===t?this._fullRequestReader?this._fullRequestReader._enqueue(i):this._queuedChunks.push(i):x(this._rangeReaders.some((function(e){return e._begin===t&&(e._enqueue(i),!0)})),"_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.")}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}_onProgress(t){void 0===t.total?this._rangeReaders[0]?.onProgress?.({loaded:t.loaded}):this._fullRequestReader?.onProgress?.({loaded:t.loaded,total:t.total})}_onProgressiveDone(){this._fullRequestReader?.progressiveDone(),this._progressiveDone=!0}_removeRangeReader(t){const e=this._rangeReaders.indexOf(t);e>=0&&this._rangeReaders.splice(e,1)}getFullReader(){x(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");const t=this._queuedChunks;return this._queuedChunks=null,new Ce(this,t,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const i=new Ee(this,t,e);return this._pdfDataRangeTransport.requestDataRange(t,e),this._rangeReaders.push(i),i}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeReaders.slice(0))e.cancel(t);this._pdfDataRangeTransport.abort()}}class Ce{constructor(t,e,i=!1,s=null){this._stream=t,this._done=i||!1,this._filename=nt(s)?s:null,this._queuedChunks=e||[],this._loaded=0;for(const t of this._queuedChunks)this._loaded+=t.byteLength;this._requests=[],this._headersReady=Promise.resolve(),t._fullRequestReader=this,this.onProgress=null}_enqueue(t){this._done||(this._requests.length>0?this._requests.shift().resolve({value:t,done:!1}):this._queuedChunks.push(t),this._loaded+=t.byteLength)}get headersReady(){return this._headersReady}get filename(){return this._filename}get isRangeSupported(){return this._stream._isRangeSupported}get isStreamingSupported(){return this._stream._isStreamingSupported}get contentLength(){return this._stream._contentLength}async read(){if(this._queuedChunks.length>0)return{value:this._queuedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}progressiveDone(){this._done||(this._done=!0)}}class Ee{constructor(t,e,i){this._stream=t,this._begin=e,this._end=i,this._queuedChunk=null,this._requests=[],this._done=!1,this.onProgress=null}_enqueue(t){if(!this._done){if(0===this._requests.length)this._queuedChunk=t;else{this._requests.shift().resolve({value:t,done:!1});for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}this._done=!0,this._stream._removeRangeReader(this)}}get isStreamingSupported(){return!1}async read(){if(this._queuedChunk){const t=this._queuedChunk;return this._queuedChunk=null,{value:t,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0,this._stream._removeRangeReader(this)}}function Se(t,e){const i=new Headers;if(!t||!e||"object"!=typeof e)return i;for(const t in e){const s=e[t];void 0!==s&&i.append(t,s)}return i}function Te({responseHeaders:t,isHttp:e,rangeChunkSize:i,disableRange:s}){const n={allowRangeRequests:!1,suggestedLength:void 0},a=parseInt(t.get("Content-Length"),10);return Number.isInteger(a)?(n.suggestedLength=a,a<=2*i||s||!e||"bytes"!==t.get("Accept-Ranges")||"identity"!==(t.get("Content-Encoding")||"identity")||(n.allowRangeRequests=!0),n):n}function Me(t){const e=t.get("Content-Disposition");if(e){let t=function(t){let e=!0,i=s("filename\\*","i").exec(t);if(i){i=i[1];let t=r(i);return t=unescape(t),t=o(t),t=l(t),a(t)}if(i=function(t){const e=[];let i;const n=s("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;null!==(i=n.exec(t));){let[,t,s,n]=i;if(t=parseInt(t,10),t in e){if(0===t)break}else e[t]=[s,n]}const a=[];for(let t=0;t{if(!Ie(e.status))throw ke(e.status,s);this._reader=e.body.getReader(),this._headersCapability.resolve();const i=e.headers,{allowRangeRequests:n,suggestedLength:a}=Te({responseHeaders:i,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=n,this._contentLength=a||this._contentLength,this._filename=Me(i),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new D("Streaming is disabled."))})).catch(this._headersCapability.reject),this.onProgress=null}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._headersCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:(this._loaded+=t.byteLength,this.onProgress?.({loaded:this._loaded,total:this._contentLength}),{value:Re(t),done:!1})}cancel(t){this._reader?.cancel(t),this._abortController.abort()}}class Fe{constructor(t,e,i){this._stream=t,this._reader=null,this._loaded=0;const s=t.source;this._withCredentials=s.withCredentials||!1,this._readCapability=Promise.withResolvers(),this._isStreamingSupported=!s.disableStream,this._abortController=new AbortController;const n=new Headers(t.headers);n.append("Range",`bytes=${e}-${i-1}`);const a=s.url;fetch(a,Pe(n,this._withCredentials,this._abortController)).then((t=>{if(!Ie(t.status))throw ke(t.status,a);this._readCapability.resolve(),this._reader=t.body.getReader()})).catch(this._readCapability.reject),this.onProgress=null}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._readCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:(this._loaded+=t.byteLength,this.onProgress?.({loaded:this._loaded}),{value:Re(t),done:!1})}cancel(t){this._reader?.cancel(t),this._abortController.abort()}}class Ne{constructor({url:t,httpHeaders:e,withCredentials:i}){this.url=t,this.isHttp=/^https?:/i.test(t),this.headers=Se(this.isHttp,e),this.withCredentials=i||!1,this.currXhrId=0,this.pendingRequests=Object.create(null)}requestRange(t,e,i){const s={begin:t,end:e};for(const t in i)s[t]=i[t];return this.request(s)}requestFull(t){return this.request(t)}request(t){const e=new XMLHttpRequest,i=this.currXhrId++,s=this.pendingRequests[i]={xhr:e};e.open("GET",this.url),e.withCredentials=this.withCredentials;for(const[t,i]of this.headers)e.setRequestHeader(t,i);return this.isHttp&&"begin"in t&&"end"in t?(e.setRequestHeader("Range",`bytes=${t.begin}-${t.end-1}`),s.expectedStatus=206):s.expectedStatus=200,e.responseType="arraybuffer",t.onError&&(e.onerror=function(i){t.onError(e.status)}),e.onreadystatechange=this.onStateChange.bind(this,i),e.onprogress=this.onProgress.bind(this,i),s.onHeadersReceived=t.onHeadersReceived,s.onDone=t.onDone,s.onError=t.onError,s.onProgress=t.onProgress,e.send(null),i}onProgress(t,e){const i=this.pendingRequests[t];i&&i.onProgress?.(e)}onStateChange(t,e){const i=this.pendingRequests[t];if(!i)return;const s=i.xhr;if(s.readyState>=2&&i.onHeadersReceived&&(i.onHeadersReceived(),delete i.onHeadersReceived),4!==s.readyState)return;if(!(t in this.pendingRequests))return;if(delete this.pendingRequests[t],0===s.status&&this.isHttp)return void i.onError?.(s.status);const n=s.status||200;if((200!==n||206!==i.expectedStatus)&&n!==i.expectedStatus)return void i.onError?.(s.status);const a=function(t){const e=t.response;return"string"!=typeof e?e:F(e).buffer}(s);if(206===n){const t=s.getResponseHeader("Content-Range"),e=/bytes (\d+)-(\d+)\/(\d+)/.exec(t);i.onDone({begin:parseInt(e[1],10),chunk:a})}else a?i.onDone({begin:0,chunk:a}):i.onError?.(s.status)}getRequestXhr(t){return this.pendingRequests[t].xhr}isPendingRequest(t){return t in this.pendingRequests}abortRequest(t){const e=this.pendingRequests[t].xhr;delete this.pendingRequests[t],e.abort()}}class Oe{constructor(t){this._source=t,this._manager=new Ne(t),this._rangeChunkSize=t.rangeChunkSize,this._fullRequestReader=null,this._rangeRequestReaders=[]}_onRangeRequestReaderClosed(t){const e=this._rangeRequestReaders.indexOf(t);e>=0&&this._rangeRequestReaders.splice(e,1)}getFullReader(){return x(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once."),this._fullRequestReader=new Be(this._manager,this._source),this._fullRequestReader}getRangeReader(t,e){const i=new ze(this._manager,t,e);return i.onClosed=this._onRangeRequestReaderClosed.bind(this),this._rangeRequestReaders.push(i),i}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class Be{constructor(t,e){this._manager=t;const i={onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)};this._url=e.url,this._fullRequestId=t.requestFull(i),this._headersCapability=Promise.withResolvers(),this._disableRange=e.disableRange||!1,this._contentLength=e.length,this._rangeChunkSize=e.rangeChunkSize,this._rangeChunkSize||this._disableRange||(this._disableRange=!0),this._isStreamingSupported=!1,this._isRangeSupported=!1,this._cachedChunks=[],this._requests=[],this._done=!1,this._storedError=void 0,this._filename=null,this.onProgress=null}_onHeadersReceived(){const t=this._fullRequestId,e=this._manager.getRequestXhr(t),i=new Headers(e.getAllResponseHeaders().trim().split(/[\r\n]+/).map((t=>{const[e,...i]=t.split(": ");return[e,i.join(": ")]}))),{allowRangeRequests:s,suggestedLength:n}=Te({responseHeaders:i,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});s&&(this._isRangeSupported=!0),this._contentLength=n||this._contentLength,this._filename=Me(i),this._isRangeSupported&&this._manager.abortRequest(t),this._headersCapability.resolve()}_onDone(t){if(t&&(this._requests.length>0?this._requests.shift().resolve({value:t.chunk,done:!1}):this._cachedChunks.push(t.chunk)),this._done=!0,!(this._cachedChunks.length>0)){for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}}_onError(t){this._storedError=ke(t,this._url),this._headersCapability.reject(this._storedError);for(const t of this._requests)t.reject(this._storedError);this._requests.length=0,this._cachedChunks.length=0}_onProgress(t){this.onProgress?.({loaded:t.loaded,total:t.lengthComputable?t.total:this._contentLength})}get filename(){return this._filename}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}get contentLength(){return this._contentLength}get headersReady(){return this._headersCapability.promise}async read(){if(this._storedError)throw this._storedError;if(this._cachedChunks.length>0)return{value:this._cachedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0,this._headersCapability.reject(t);for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._fullRequestId)&&this._manager.abortRequest(this._fullRequestId),this._fullRequestReader=null}}class ze{constructor(t,e,i){this._manager=t;const s={onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)};this._url=t.url,this._requestId=t.requestRange(e,i,s),this._requests=[],this._queuedChunk=null,this._done=!1,this._storedError=void 0,this.onProgress=null,this.onClosed=null}_close(){this.onClosed?.(this)}_onDone(t){const e=t.chunk;this._requests.length>0?this._requests.shift().resolve({value:e,done:!1}):this._queuedChunk=e,this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0,this._close()}_onError(t){this._storedError=ke(t,this._url);for(const t of this._requests)t.reject(this._storedError);this._requests.length=0,this._queuedChunk=null}_onProgress(t){this.isStreamingSupported||this.onProgress?.({loaded:t.loaded})}get isStreamingSupported(){return!1}async read(){if(this._storedError)throw this._storedError;if(null!==this._queuedChunk){const t=this._queuedChunk;return this._queuedChunk=null,{value:t,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._requestId)&&this._manager.abortRequest(this._requestId),this._close()}}const He=/^[a-z][a-z0-9\-+.]+:/i;function je(t,e,i){return"http:"===t.protocol?Ut.get("http").request(t,{headers:e},i):Ut.get("https").request(t,{headers:e},i)}class Ue{constructor(t){this.source=t,this.url=function(t){if(He.test(t))return new URL(t);const e=Ut.get("url");return new URL(e.pathToFileURL(t))}(t.url),this.isHttp="http:"===this.url.protocol||"https:"===this.url.protocol,this.isFsUrl="file:"===this.url.protocol,this.headers=Se(this.isHttp,t.httpHeaders),this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return x(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once."),this._fullRequestReader=this.isFsUrl?new qe(this):new Ge(this),this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const i=this.isFsUrl?new Xe(this,t,e):new Ve(this,t,e);return this._rangeRequestReaders.push(i),i}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class $e{constructor(t){this._url=t.url,this._done=!1,this._storedError=null,this.onProgress=null;const e=t.source;this._contentLength=e.length,this._loaded=0,this._filename=null,this._disableRange=e.disableRange||!1,this._rangeChunkSize=e.rangeChunkSize,this._rangeChunkSize||this._disableRange||(this._disableRange=!0),this._isStreamingSupported=!e.disableStream,this._isRangeSupported=!e.disableRange,this._readableStream=null,this._readCapability=Promise.withResolvers(),this._headersCapability=Promise.withResolvers()}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const t=this._readableStream.read();return null===t?(this._readCapability=Promise.withResolvers(),this.read()):(this._loaded+=t.length,this.onProgress?.({loaded:this._loaded,total:this._contentLength}),{value:new Uint8Array(t).buffer,done:!1})}cancel(t){this._readableStream?this._readableStream.destroy(t):this._error(t)}_error(t){this._storedError=t,this._readCapability.resolve()}_setReadableStream(t){this._readableStream=t,t.on("readable",(()=>{this._readCapability.resolve()})),t.on("end",(()=>{t.destroy(),this._done=!0,this._readCapability.resolve()})),t.on("error",(t=>{this._error(t)})),!this._isStreamingSupported&&this._isRangeSupported&&this._error(new D("streaming is disabled")),this._storedError&&this._readableStream.destroy(this._storedError)}}class We{constructor(t){this._url=t.url,this._done=!1,this._storedError=null,this.onProgress=null,this._loaded=0,this._readableStream=null,this._readCapability=Promise.withResolvers();const e=t.source;this._isStreamingSupported=!e.disableStream}get isStreamingSupported(){return this._isStreamingSupported}async read(){if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const t=this._readableStream.read();return null===t?(this._readCapability=Promise.withResolvers(),this.read()):(this._loaded+=t.length,this.onProgress?.({loaded:this._loaded}),{value:new Uint8Array(t).buffer,done:!1})}cancel(t){this._readableStream?this._readableStream.destroy(t):this._error(t)}_error(t){this._storedError=t,this._readCapability.resolve()}_setReadableStream(t){this._readableStream=t,t.on("readable",(()=>{this._readCapability.resolve()})),t.on("end",(()=>{t.destroy(),this._done=!0,this._readCapability.resolve()})),t.on("error",(t=>{this._error(t)})),this._storedError&&this._readableStream.destroy(this._storedError)}}class Ge extends $e{constructor(t){super(t);const e=Object.fromEntries(t.headers);this._request=je(this._url,e,(e=>{if(404===e.statusCode){const t=new I(`Missing PDF "${this._url}".`);return this._storedError=t,void this._headersCapability.reject(t)}this._headersCapability.resolve(),this._setReadableStream(e);const i=new Headers(this._readableStream.headers),{allowRangeRequests:s,suggestedLength:n}=Te({responseHeaders:i,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=s,this._contentLength=n||this._contentLength,this._filename=Me(i)})),this._request.on("error",(t=>{this._storedError=t,this._headersCapability.reject(t)})),this._request.end()}}class Ve extends We{constructor(t,e,i){super(t);const s=Object.fromEntries(t.headers);s.Range=`bytes=${e}-${i-1}`,this._request=je(this._url,s,(t=>{if(404!==t.statusCode)this._setReadableStream(t);else{const t=new I(`Missing PDF "${this._url}".`);this._storedError=t}})),this._request.on("error",(t=>{this._storedError=t})),this._request.end()}}class qe extends $e{constructor(t){super(t);const e=Ut.get("fs");e.promises.lstat(this._url).then((t=>{this._contentLength=t.size,this._setReadableStream(e.createReadStream(this._url)),this._headersCapability.resolve()}),(t=>{"ENOENT"===t.code&&(t=new I(`Missing PDF "${this._url}".`)),this._storedError=t,this._headersCapability.reject(t)}))}}class Xe extends We{constructor(t,e,i){super(t);const s=Ut.get("fs");this._setReadableStream(s.createReadStream(this._url,{start:e,end:i-1}))}}const Ke=30;class Ye{#Je=Promise.withResolvers();#ut=null;#Ze=!1;#ti=!!globalThis.FontInspector?.enabled;#ei=null;#ii=null;#si=0;#ni=0;#ai=null;#ri=null;#oi=0;#li=0;#hi=Object.create(null);#di=[];#ci=null;#ui=[];#pi=new WeakMap;#gi=null;static#mi=new Map;static#fi=new Map;static#bi=new WeakMap;static#vi=null;static#Ai=new Set;constructor({textContentSource:t,container:e,viewport:i}){if(t instanceof ReadableStream)this.#ci=t;else{if("object"!=typeof t)throw new Error('No "textContentSource" parameter specified.');this.#ci=new ReadableStream({start(e){e.enqueue(t),e.close()}})}this.#ut=this.#ri=e,this.#li=i.scale*(globalThis.devicePixelRatio||1),this.#oi=i.rotation,this.#ii={div:null,properties:null,ctx:null};const{pageWidth:s,pageHeight:n,pageX:a,pageY:r}=i.rawDims;this.#gi=[1,0,0,-1,-a,r+n],this.#ni=s,this.#si=n,Ye.#yi(),bt(e,i),this.#Je.promise.finally((()=>{Ye.#Ai.delete(this),this.#ii=null,this.#hi=null})).catch((()=>{}))}static get fontFamilyMap(){const{isWindows:t,isFirefox:e}=O.platform;return E(this,"fontFamilyMap",new Map([["sans-serif",(t&&e?"Calibri, ":"")+"sans-serif"],["monospace",(t&&e?"Lucida Console, ":"")+"monospace"]]))}render(){const t=()=>{this.#ai.read().then((({value:e,done:i})=>{i?this.#Je.resolve():(this.#ei??=e.lang,Object.assign(this.#hi,e.styles),this.#wi(e.items),t())}),this.#Je.reject)};return this.#ai=this.#ci.getReader(),Ye.#Ai.add(this),t(),this.#Je.promise}update({viewport:t,onBefore:e=null}){const i=t.scale*(globalThis.devicePixelRatio||1),s=t.rotation;if(s!==this.#oi&&(e?.(),this.#oi=s,bt(this.#ri,{rotation:s})),i!==this.#li){e?.(),this.#li=i;const t={div:null,properties:null,ctx:Ye.#_i(this.#ei)};for(const e of this.#ui)t.properties=this.#pi.get(e),t.div=e,this.#xi(t)}}cancel(){const t=new D("TextLayer task cancelled.");this.#ai?.cancel(t).catch((()=>{})),this.#ai=null,this.#Je.reject(t)}get textDivs(){return this.#ui}get textContentItemsStr(){return this.#di}#wi(t){if(this.#Ze)return;this.#ii.ctx??=Ye.#_i(this.#ei);const e=this.#ui,i=this.#di;for(const s of t){if(e.length>1e5)return w("Ignoring additional textDivs for performance reasons."),void(this.#Ze=!0);if(void 0!==s.str)i.push(s.str),this.#Ci(s);else if("beginMarkedContentProps"===s.type||"beginMarkedContent"===s.type){const t=this.#ut;this.#ut=document.createElement("span"),this.#ut.classList.add("markedContent"),null!==s.id&&this.#ut.setAttribute("id",`${s.id}`),t.append(this.#ut)}else"endMarkedContent"===s.type&&(this.#ut=this.#ut.parentNode)}}#Ci(t){const e=document.createElement("span"),i={angle:0,canvasWidth:0,hasText:""!==t.str,hasEOL:t.hasEOL,fontSize:0};this.#ui.push(e);const s=z.transform(this.#gi,t.transform);let n=Math.atan2(s[1],s[0]);const a=this.#hi[t.fontName];a.vertical&&(n+=Math.PI/2);let r=this.#ti&&a.fontSubstitution||a.fontFamily;r=Ye.fontFamilyMap.get(r)||r;const o=Math.hypot(s[2],s[3]),l=o*Ye.#Ei(r,this.#ei);let h,d;0===n?(h=s[4],d=s[5]-l):(h=s[4]+l*Math.sin(n),d=s[5]-l*Math.cos(n));const c="calc(var(--scale-factor)*",u=e.style;this.#ut===this.#ri?(u.left=`${(100*h/this.#ni).toFixed(2)}%`,u.top=`${(100*d/this.#si).toFixed(2)}%`):(u.left=`${c}${h.toFixed(2)}px)`,u.top=`${c}${d.toFixed(2)}px)`),u.fontSize=`${c}${(Ye.#vi*o).toFixed(2)}px)`,u.fontFamily=r,i.fontSize=o,e.setAttribute("role","presentation"),e.textContent=t.str,e.dir=t.dir,this.#ti&&(e.dataset.fontName=a.fontSubstitutionLoadedName||t.fontName),0!==n&&(i.angle=n*(180/Math.PI));let p=!1;if(t.str.length>1)p=!0;else if(" "!==t.str&&t.transform[0]!==t.transform[3]){const e=Math.abs(t.transform[0]),i=Math.abs(t.transform[3]);e!==i&&Math.max(e,i)/Math.min(e,i)>1.5&&(p=!0)}if(p&&(i.canvasWidth=a.vertical?t.height:t.width),this.#pi.set(e,i),this.#ii.div=e,this.#ii.properties=i,this.#xi(this.#ii),i.hasText&&this.#ut.append(e),i.hasEOL){const t=document.createElement("br");t.setAttribute("role","presentation"),this.#ut.append(t)}}#xi(t){const{div:e,properties:i,ctx:s}=t,{style:n}=e;let a="";if(Ye.#vi>1&&(a=`scale(${1/Ye.#vi})`),0!==i.canvasWidth&&i.hasText){const{fontFamily:t}=n,{canvasWidth:r,fontSize:o}=i;Ye.#Si(s,o*this.#li,t);const{width:l}=s.measureText(e.textContent);l>0&&(a=`scaleX(${r*this.#li/l}) ${a}`)}0!==i.angle&&(a=`rotate(${i.angle}deg) ${a}`),a.length>0&&(n.transform=a)}static cleanup(){if(!(this.#Ai.size>0)){this.#mi.clear();for(const{canvas:t}of this.#fi.values())t.remove();this.#fi.clear()}}static#_i(t=null){let e=this.#fi.get(t||="");if(!e){const i=document.createElement("canvas");i.className="hiddenCanvasElement",i.lang=t,document.body.append(i),e=i.getContext("2d",{alpha:!1,willReadFrequently:!0}),this.#fi.set(t,e),this.#bi.set(e,{size:0,family:""})}return e}static#Si(t,e,i){const s=this.#bi.get(t);e===s.size&&i===s.family||(t.font=`${e}px ${i}`,s.size=e,s.family=i)}static#yi(){if(null!==this.#vi)return;const t=document.createElement("div");t.style.opacity=0,t.style.lineHeight=1,t.style.fontSize="1px",t.style.position="absolute",t.textContent="X",document.body.append(t),this.#vi=t.getBoundingClientRect().height,t.remove()}static#Ei(t,e){const i=this.#mi.get(t);if(i)return i;const s=this.#_i(e);s.canvas.width=s.canvas.height=Ke,this.#Si(s,Ke,t);const n=s.measureText("");let a=n.fontBoundingBoxAscent,r=Math.abs(n.fontBoundingBoxDescent);if(a){const e=a/(a+r);return this.#mi.set(t,e),s.canvas.width=s.canvas.height=0,e}s.strokeStyle="red",s.clearRect(0,0,Ke,Ke),s.strokeText("g",0,0);let o=s.getImageData(0,0,Ke,Ke).data;r=0;for(let t=o.length-1-3;t>=0;t-=4)if(o[t]>0){r=Math.ceil(t/4/Ke);break}s.clearRect(0,0,Ke,Ke),s.strokeText("A",0,Ke),o=s.getImageData(0,0,Ke,Ke).data,a=0;for(let t=0,e=o.length;t0){a=Ke-Math.floor(t/4/Ke);break}s.canvas.width=s.canvas.height=0;const l=a?a/(a+r):.8;return this.#mi.set(t,l),l}}class Qe{static textContent(t){const e=[],i={items:e,styles:Object.create(null)};return function t(i){if(!i)return;let s=null;const n=i.name;if("#text"===n)s=i.value;else{if(!Qe.shouldBuildText(n))return;i?.attributes?.textContent?s=i.attributes.textContent:i.value&&(s=i.value)}if(null!==s&&e.push({str:s}),i.children)for(const e of i.children)t(e)}(t),i}static shouldBuildText(t){return!("textarea"===t||"input"===t||"option"===t||"select"===t)}}const Je=n?class extends G{_createCanvas(t,e){return Ut.get("canvas").createCanvas(t,e)}}:class extends G{constructor({ownerDocument:t=globalThis.document,enableHWA:e=!1}){super({enableHWA:e}),this._document=t}_createCanvas(t,e){const i=this._document.createElement("canvas");return i.width=t,i.height=e,i}},Ze=n?class extends V{_fetchData(t,e){return $t(t).then((t=>({cMapData:t,compressionType:e})))}}:J,ti=n?class extends W{}:class extends W{#Ti;#Mi;#ki;#Ii;#Pi;#Ri;#A=0;constructor({docId:t,ownerDocument:e=globalThis.document}){super(),this.#Ii=t,this.#Pi=e}get#w(){return this.#Mi||=new Map}get#Di(){return this.#Ri||=new Map}get#Li(){if(!this.#ki){const t=this.#Pi.createElement("div"),{style:e}=t;e.visibility="hidden",e.contain="strict",e.width=e.height=0,e.position="absolute",e.top=e.left=0,e.zIndex=-1;const i=this.#Pi.createElementNS(K,"svg");i.setAttribute("width",0),i.setAttribute("height",0),this.#ki=this.#Pi.createElementNS(K,"defs"),t.append(i),i.append(this.#ki),this.#Pi.body.append(t)}return this.#ki}#Fi(t){if(1===t.length){const e=t[0],i=new Array(256);for(let t=0;t<256;t++)i[t]=e[t]/255;const s=i.join(",");return[s,s,s]}const[e,i,s]=t,n=new Array(256),a=new Array(256),r=new Array(256);for(let t=0;t<256;t++)n[t]=e[t]/255,a[t]=i[t]/255,r[t]=s[t]/255;return[n.join(","),a.join(","),r.join(",")]}#Ni(t){if(void 0===this.#Ti){this.#Ti="";const t=this.#Pi.URL;t!==this.#Pi.baseURI&&(st(t)?w('#createUrl: ignore "data:"-URL for performance reasons.'):this.#Ti=t.split("#",1)[0])}return`url(${this.#Ti}#${t})`}addFilter(t){if(!t)return"none";let e=this.#w.get(t);if(e)return e;const[i,s,n]=this.#Fi(t),a=1===t.length?i:`${i}${s}${n}`;if(e=this.#w.get(a),e)return this.#w.set(t,e),e;const r=`g_${this.#Ii}_transfer_map_${this.#A++}`,o=this.#Ni(r);this.#w.set(t,o),this.#w.set(a,o);const l=this.#Oi(r);return this.#Bi(i,s,n,l),o}addHCMFilter(t,e){const i=`${t}-${e}`,s="base";let n=this.#Di.get(s);if(n?.key===i)return n.url;if(n?(n.filter?.remove(),n.key=i,n.url="none",n.filter=null):(n={key:i,url:"none",filter:null},this.#Di.set(s,n)),!t||!e)return n.url;const a=this.#zi(t);t=z.makeHexColor(...a);const r=this.#zi(e);if(e=z.makeHexColor(...r),this.#Li.style.color="","#000000"===t&&"#ffffff"===e||t===e)return n.url;const o=new Array(256);for(let t=0;t<=255;t++){const e=t/255;o[t]=e<=.03928?e/12.92:((e+.055)/1.055)**2.4}const l=o.join(","),h=`g_${this.#Ii}_hcm_filter`,d=n.filter=this.#Oi(h);this.#Bi(l,l,l,d),this.#Hi(d);const c=(t,e)=>{const i=a[t]/255,s=r[t]/255,n=new Array(e+1);for(let t=0;t<=e;t++)n[t]=i+t/e*(s-i);return n.join(",")};return this.#Bi(c(0,5),c(1,5),c(2,5),d),n.url=this.#Ni(h),n.url}addAlphaFilter(t){let e=this.#w.get(t);if(e)return e;const[i]=this.#Fi([t]),s=`alpha_${i}`;if(e=this.#w.get(s),e)return this.#w.set(t,e),e;const n=`g_${this.#Ii}_alpha_map_${this.#A++}`,a=this.#Ni(n);this.#w.set(t,a),this.#w.set(s,a);const r=this.#Oi(n);return this.#ji(i,r),a}addLuminosityFilter(t){let e,i,s=this.#w.get(t||"luminosity");if(s)return s;if(t?([e]=this.#Fi([t]),i=`luminosity_${e}`):i="luminosity",s=this.#w.get(i),s)return this.#w.set(t,s),s;const n=`g_${this.#Ii}_luminosity_map_${this.#A++}`,a=this.#Ni(n);this.#w.set(t,a),this.#w.set(i,a);const r=this.#Oi(n);return this.#Ui(r),t&&this.#ji(e,r),a}addHighlightHCMFilter(t,e,i,s,n){const a=`${e}-${i}-${s}-${n}`;let r=this.#Di.get(t);if(r?.key===a)return r.url;if(r?(r.filter?.remove(),r.key=a,r.url="none",r.filter=null):(r={key:a,url:"none",filter:null},this.#Di.set(t,r)),!e||!i)return r.url;const[o,l]=[e,i].map(this.#zi.bind(this));let h=Math.round(.2126*o[0]+.7152*o[1]+.0722*o[2]),d=Math.round(.2126*l[0]+.7152*l[1]+.0722*l[2]),[c,u]=[s,n].map(this.#zi.bind(this));d{const s=new Array(256),n=(d-h)/i,a=t/255,r=(e-t)/(255*i);let o=0;for(let t=0;t<=i;t++){const e=Math.round(h+t*n),i=a+t*r;for(let t=o;t<=e;t++)s[t]=i;o=e+1}for(let t=o;t<256;t++)s[t]=s[o-1];return s.join(",")},g=`g_${this.#Ii}_hcm_${t}_filter`,m=r.filter=this.#Oi(g);return this.#Hi(m),this.#Bi(p(c[0],u[0],5),p(c[1],u[1],5),p(c[2],u[2],5),m),r.url=this.#Ni(g),r.url}destroy(t=!1){t&&0!==this.#Di.size||(this.#ki&&(this.#ki.parentNode.parentNode.remove(),this.#ki=null),this.#Mi&&(this.#Mi.clear(),this.#Mi=null),this.#A=0)}#Ui(t){const e=this.#Pi.createElementNS(K,"feColorMatrix");e.setAttribute("type","matrix"),e.setAttribute("values","0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0.59 0.11 0 0"),t.append(e)}#Hi(t){const e=this.#Pi.createElementNS(K,"feColorMatrix");e.setAttribute("type","matrix"),e.setAttribute("values","0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0"),t.append(e)}#Oi(t){const e=this.#Pi.createElementNS(K,"filter");return e.setAttribute("color-interpolation-filters","sRGB"),e.setAttribute("id",t),this.#Li.append(e),e}#$i(t,e,i){const s=this.#Pi.createElementNS(K,e);s.setAttribute("type","discrete"),s.setAttribute("tableValues",i),t.append(s)}#Bi(t,e,i,s){const n=this.#Pi.createElementNS(K,"feComponentTransfer");s.append(n),this.#$i(n,"feFuncR",t),this.#$i(n,"feFuncG",e),this.#$i(n,"feFuncB",i)}#ji(t,e){const i=this.#Pi.createElementNS(K,"feComponentTransfer");e.append(i),this.#$i(i,"feFuncA",t)}#zi(t){return this.#Li.style.color=t,gt(getComputedStyle(this.#Li).getPropertyValue("color"))}},ei=n?class extends q{_fetchData(t){return $t(t)}}:Z;function ii(t={}){"string"==typeof t||t instanceof URL?t={url:t}:(t instanceof ArrayBuffer||ArrayBuffer.isView(t))&&(t={data:t});const e=new ni,{docId:i}=e,s=t.url?function(t){if(t instanceof URL)return t.href;try{return new URL(t,window.location).href}catch{if(n&&"string"==typeof t)return t}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}(t.url):null,a=t.data?function(t){if(n&&"undefined"!=typeof Buffer&&t instanceof Buffer)throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");if(t instanceof Uint8Array&&t.byteLength===t.buffer.byteLength)return t;if("string"==typeof t)return F(t);if(t instanceof ArrayBuffer||ArrayBuffer.isView(t)||"object"==typeof t&&!isNaN(t?.length))return new Uint8Array(t);throw new Error("Invalid PDF binary data: either TypedArray, string, or array-like object is expected in the data property.")}(t.data):null,r=t.httpHeaders||null,o=!0===t.withCredentials,l=t.password??null,h=t.range instanceof ai?t.range:null,d=Number.isInteger(t.rangeChunkSize)&&t.rangeChunkSize>0?t.rangeChunkSize:65536;let c=t.worker instanceof hi?t.worker:null;const u=t.verbosity,p="string"!=typeof t.docBaseUrl||st(t.docBaseUrl)?null:t.docBaseUrl,g="string"==typeof t.cMapUrl?t.cMapUrl:null,m=!1!==t.cMapPacked,f=t.CMapReaderFactory||Ze,b="string"==typeof t.standardFontDataUrl?t.standardFontDataUrl:null,A=t.StandardFontDataFactory||ei,y=!0!==t.stopAtErrors,w=Number.isInteger(t.maxImageSize)&&t.maxImageSize>-1?t.maxImageSize:-1,_=!1!==t.isEvalSupported,x="boolean"==typeof t.isOffscreenCanvasSupported?t.isOffscreenCanvasSupported:!n,C=Number.isInteger(t.canvasMaxAreaInBytes)?t.canvasMaxAreaInBytes:-1,E="boolean"==typeof t.disableFontFace?t.disableFontFace:n,S=!0===t.fontExtraProperties,T=!0===t.enableXfa,M=t.ownerDocument||globalThis.document,k=!0===t.disableRange,I=!0===t.disableStream,P=!0===t.disableAutoFetch,R=!0===t.pdfBug,D=t.CanvasFactory||Je,L=t.FilterFactory||ti,N=!0===t.enableHWA,O=h?h.length:t.length??NaN,B="boolean"==typeof t.useSystemFonts?t.useSystemFonts:!n&&!E,z="boolean"==typeof t.useWorkerFetch?t.useWorkerFetch:f===J&&A===Z&&g&&b&<(g,document.baseURI)&<(b,document.baseURI);t.canvasFactory&&dt("`canvasFactory`-instance option, please use `CanvasFactory` instead."),t.filterFactory&&dt("`filterFactory`-instance option, please use `FilterFactory` instead."),v(u);const H={canvasFactory:new D({ownerDocument:M,enableHWA:N}),filterFactory:new L({docId:i,ownerDocument:M}),cMapReaderFactory:z?null:new f({baseUrl:g,isCompressed:m}),standardFontDataFactory:z?null:new A({baseUrl:b})};if(!c){const t={verbosity:u,port:fe.workerPort};c=t.port?hi.fromPort(t):new hi(t),e._worker=c}const j={docId:i,apiVersion:"4.7.76",data:a,password:l,disableAutoFetch:P,rangeChunkSize:d,length:O,docBaseUrl:p,enableXfa:T,evaluatorOptions:{maxImageSize:w,disableFontFace:E,ignoreErrors:y,isEvalSupported:_,isOffscreenCanvasSupported:x,canvasMaxAreaInBytes:C,fontExtraProperties:S,useSystemFonts:B,cMapUrl:z?g:null,standardFontDataUrl:z?b:null}},U={disableFontFace:E,fontExtraProperties:S,ownerDocument:M,pdfBug:R,styleElement:null,loadingParams:{disableAutoFetch:P,enableXfa:T}};return c.promise.then((function(){if(e.destroyed)throw new Error("Loading aborted");if(c.destroyed)throw new Error("Worker was destroyed");const t=c.messageHandler.sendWithPromise("GetDocRequest",j,a?[a.buffer]:null);let l;if(h)l=new xe(h,{disableRange:k,disableStream:I});else if(!a){if(!s)throw new Error("getDocument - no `url` parameter provided.");let t;t=n?"undefined"!=typeof fetch&&"undefined"!=typeof Response&&"body"in Response.prototype&<(s)?De:Ue:lt(s)?De:Oe,l=new t({url:s,length:O,httpHeaders:r,withCredentials:o,rangeChunkSize:d,disableRange:k,disableStream:I})}return t.then((t=>{if(e.destroyed)throw new Error("Loading aborted");if(c.destroyed)throw new Error("Worker was destroyed");const s=new ve(i,t,c.port),n=new di(s,e,l,U,H);e._transport=n,s.send("Ready",null)}))})).catch(e._capability.reject),e}function si(t){return"object"==typeof t&&Number.isInteger(t?.num)&&t.num>=0&&Number.isInteger(t?.gen)&&t.gen>=0}class ni{static#Ii=0;constructor(){this._capability=Promise.withResolvers(),this._transport=null,this._worker=null,this.docId="d"+ni.#Ii++,this.destroyed=!1,this.onPassword=null,this.onProgress=null}get promise(){return this._capability.promise}async destroy(){this.destroyed=!0;try{this._worker?.port&&(this._worker._pendingDestroy=!0),await(this._transport?.destroy())}catch(t){throw this._worker?.port&&delete this._worker._pendingDestroy,t}this._transport=null,this._worker&&(this._worker.destroy(),this._worker=null)}}class ai{constructor(t,e,i=!1,s=null){this.length=t,this.initialData=e,this.progressiveDone=i,this.contentDispositionFilename=s,this._rangeListeners=[],this._progressListeners=[],this._progressiveReadListeners=[],this._progressiveDoneListeners=[],this._readyCapability=Promise.withResolvers()}addRangeListener(t){this._rangeListeners.push(t)}addProgressListener(t){this._progressListeners.push(t)}addProgressiveReadListener(t){this._progressiveReadListeners.push(t)}addProgressiveDoneListener(t){this._progressiveDoneListeners.push(t)}onDataRange(t,e){for(const i of this._rangeListeners)i(t,e)}onDataProgress(t,e){this._readyCapability.promise.then((()=>{for(const i of this._progressListeners)i(t,e)}))}onDataProgressiveRead(t){this._readyCapability.promise.then((()=>{for(const e of this._progressiveReadListeners)e(t)}))}onDataProgressiveDone(){this._readyCapability.promise.then((()=>{for(const t of this._progressiveDoneListeners)t()}))}transportReady(){this._readyCapability.resolve()}requestDataRange(t,e){_("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class ri{constructor(t,e){this._pdfInfo=t,this._transport=e}get annotationStorage(){return this._transport.annotationStorage}get canvasFactory(){return this._transport.canvasFactory}get filterFactory(){return this._transport.filterFactory}get numPages(){return this._pdfInfo.numPages}get fingerprints(){return this._pdfInfo.fingerprints}get isPureXfa(){return E(this,"isPureXfa",!!this._transport._htmlForXfa)}get allXfaHtml(){return this._transport._htmlForXfa}getPage(t){return this._transport.getPage(t)}getPageIndex(t){return this._transport.getPageIndex(t)}getDestinations(){return this._transport.getDestinations()}getDestination(t){return this._transport.getDestination(t)}getPageLabels(){return this._transport.getPageLabels()}getPageLayout(){return this._transport.getPageLayout()}getPageMode(){return this._transport.getPageMode()}getViewerPreferences(){return this._transport.getViewerPreferences()}getOpenAction(){return this._transport.getOpenAction()}getAttachments(){return this._transport.getAttachments()}getJSActions(){return this._transport.getDocJSActions()}getOutline(){return this._transport.getOutline()}getOptionalContentConfig({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getOptionalContentConfig(e)}getPermissions(){return this._transport.getPermissions()}getMetadata(){return this._transport.getMetadata()}getMarkInfo(){return this._transport.getMarkInfo()}getData(){return this._transport.getData()}saveDocument(){return this._transport.saveDocument()}getDownloadInfo(){return this._transport.downloadInfoCapability.promise}cleanup(t=!1){return this._transport.startCleanup(t||this.isPureXfa)}destroy(){return this.loadingTask.destroy()}cachedPageNumber(t){return this._transport.cachedPageNumber(t)}get loadingParams(){return this._transport.loadingParams}get loadingTask(){return this._transport.loadingTask}getFieldObjects(){return this._transport.getFieldObjects()}hasJSActions(){return this._transport.hasJSActions()}getCalculationOrderIds(){return this._transport.getCalculationOrderIds()}}class oi{#Wi=null;#Gi=!1;constructor(t,e,i,s=!1){this._pageIndex=t,this._pageInfo=e,this._transport=i,this._stats=s?new ot:null,this._pdfBug=s,this.commonObjs=i.commonObjs,this.objs=new ui,this._maybeCleanupAfterRender=!1,this._intentStates=new Map,this.destroyed=!1}get pageNumber(){return this._pageIndex+1}get rotate(){return this._pageInfo.rotate}get ref(){return this._pageInfo.ref}get userUnit(){return this._pageInfo.userUnit}get view(){return this._pageInfo.view}getViewport({scale:t,rotation:e=this.rotate,offsetX:i=0,offsetY:s=0,dontFlip:n=!1}={}){return new et({viewBox:this.view,scale:t,rotation:e,offsetX:i,offsetY:s,dontFlip:n})}getAnnotations({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getAnnotations(this._pageIndex,e)}getJSActions(){return this._transport.getPageJSActions(this._pageIndex)}get filterFactory(){return this._transport.filterFactory}get isPureXfa(){return E(this,"isPureXfa",!!this._transport._htmlForXfa)}async getXfa(){return this._transport._htmlForXfa?.children[this._pageIndex]||null}render({canvasContext:t,viewport:e,intent:i="display",annotationMode:s=l.ENABLE,transform:n=null,background:a=null,optionalContentConfigPromise:r=null,annotationCanvasMap:o=null,pageColors:h=null,printAnnotationStorage:d=null,isEditing:c=!1}){this._stats?.time("Overall");const u=this._transport.getRenderingIntent(i,s,d,c),{renderingIntent:p,cacheKey:g}=u;this.#Gi=!1,this.#Vi(),r||=this._transport.getOptionalContentConfig(p);let m=this._intentStates.get(g);m||(m=Object.create(null),this._intentStates.set(g,m)),m.streamReaderCancelTimeout&&(clearTimeout(m.streamReaderCancelTimeout),m.streamReaderCancelTimeout=null);const f=!!(4&p);m.displayReadyCapability||(m.displayReadyCapability=Promise.withResolvers(),m.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(u));const b=t=>{m.renderTasks.delete(v),(this._maybeCleanupAfterRender||f)&&(this.#Gi=!0),this.#qi(!f),t?(v.capability.reject(t),this._abortOperatorList({intentState:m,reason:t instanceof Error?t:new Error(t)})):v.capability.resolve(),this._stats&&(this._stats.timeEnd("Rendering"),this._stats.timeEnd("Overall"),globalThis.Stats?.enabled&&globalThis.Stats.add(this.pageNumber,this._stats))},v=new gi({callback:b,params:{canvasContext:t,viewport:e,transform:n,background:a},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:o,operatorList:m.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!f,pdfBug:this._pdfBug,pageColors:h});(m.renderTasks||=new Set).add(v);const A=v.task;return Promise.all([m.displayReadyCapability.promise,r]).then((([t,e])=>{if(this.destroyed)b();else{if(this._stats?.time("Rendering"),!(e.renderingIntent&p))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");v.initializeGraphics({transparency:t,optionalContentConfig:e}),v.operatorListChanged()}})).catch(b),A}getOperatorList({intent:t="display",annotationMode:e=l.ENABLE,printAnnotationStorage:i=null,isEditing:s=!1}={}){const n=this._transport.getRenderingIntent(t,e,i,s,!0);let a,r=this._intentStates.get(n.cacheKey);return r||(r=Object.create(null),this._intentStates.set(n.cacheKey,r)),r.opListReadCapability||(a=Object.create(null),a.operatorListChanged=function(){r.operatorList.lastChunk&&(r.opListReadCapability.resolve(r.operatorList),r.renderTasks.delete(a))},r.opListReadCapability=Promise.withResolvers(),(r.renderTasks||=new Set).add(a),r.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(n)),r.opListReadCapability.promise}streamTextContent({includeMarkedContent:t=!1,disableNormalization:e=!1}={}){return this._transport.messageHandler.sendWithStream("GetTextContent",{pageIndex:this._pageIndex,includeMarkedContent:!0===t,disableNormalization:!0===e},{highWaterMark:100,size:t=>t.items.length})}getTextContent(t={}){if(this._transport._htmlForXfa)return this.getXfa().then((t=>Qe.textContent(t)));const e=this.streamTextContent(t);return new Promise((function(t,i){const s=e.getReader(),n={items:[],styles:Object.create(null),lang:null};!function e(){s.read().then((function({value:i,done:s}){s?t(n):(n.lang??=i.lang,Object.assign(n.styles,i.styles),n.items.push(...i.items),e())}),i)}()}))}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;const t=[];for(const e of this._intentStates.values())if(this._abortOperatorList({intentState:e,reason:new Error("Page was destroyed."),force:!0}),!e.opListReadCapability)for(const i of e.renderTasks)t.push(i.completed),i.cancel();return this.objs.clear(),this.#Gi=!1,this.#Vi(),Promise.all(t)}cleanup(t=!1){this.#Gi=!0;const e=this.#qi(!1);return t&&e&&(this._stats&&=new ot),e}#qi(t=!1){if(this.#Vi(),!this.#Gi||this.destroyed)return!1;if(t)return this.#Wi=setTimeout((()=>{this.#Wi=null,this.#qi(!1)}),5e3),!1;for(const{renderTasks:t,operatorList:e}of this._intentStates.values())if(t.size>0||!e.lastChunk)return!1;return this._intentStates.clear(),this.objs.clear(),this.#Gi=!1,!0}#Vi(){this.#Wi&&(clearTimeout(this.#Wi),this.#Wi=null)}_startRenderPage(t,e){const i=this._intentStates.get(e);i&&(this._stats?.timeEnd("Page Request"),i.displayReadyCapability?.resolve(t))}_renderPageChunk(t,e){for(let i=0,s=t.length;i{r.read().then((({value:t,done:e})=>{e?o.streamReader=null:this._transport.destroyed||(this._renderPageChunk(t,o),l())}),(t=>{if(o.streamReader=null,!this._transport.destroyed){if(o.operatorList){o.operatorList.lastChunk=!0;for(const t of o.renderTasks)t.operatorListChanged();this.#qi(!0)}if(o.displayReadyCapability)o.displayReadyCapability.reject(t);else{if(!o.opListReadCapability)throw t;o.opListReadCapability.reject(t)}}}))};l()}_abortOperatorList({intentState:t,reason:e,force:i=!1}){if(t.streamReader){if(t.streamReaderCancelTimeout&&(clearTimeout(t.streamReaderCancelTimeout),t.streamReaderCancelTimeout=null),!i){if(t.renderTasks.size>0)return;if(e instanceof it){let i=100;return e.extraDelay>0&&e.extraDelay<1e3&&(i+=e.extraDelay),void(t.streamReaderCancelTimeout=setTimeout((()=>{t.streamReaderCancelTimeout=null,this._abortOperatorList({intentState:t,reason:e,force:!0})}),i))}}if(t.streamReader.cancel(new D(e.message)).catch((()=>{})),t.streamReader=null,!this._transport.destroyed){for(const[e,i]of this._intentStates)if(i===t){this._intentStates.delete(e);break}this.cleanup()}}}get stats(){return this._stats}}class li{#Xi=new Set;#Ki=Promise.resolve();postMessage(t,e){const i={data:structuredClone(t,e?{transfer:e}:null)};this.#Ki.then((()=>{for(const t of this.#Xi)t.call(this,i)}))}addEventListener(t,e){this.#Xi.add(e)}removeEventListener(t,e){this.#Xi.delete(e)}terminate(){this.#Xi.clear()}}class hi{static#Yi=0;static#Qi=!1;static#Ji;static{n&&(this.#Qi=!0,fe.workerSrc||="./pdf.worker.mjs"),this._isSameOrigin=(t,e)=>{let i;try{if(i=new URL(t),!i.origin||"null"===i.origin)return!1}catch{return!1}const s=new URL(e,i);return i.origin===s.origin},this._createCDNWrapper=t=>{const e=`await import("${t}");`;return URL.createObjectURL(new Blob([e],{type:"text/javascript"}))}}constructor({name:t=null,port:e=null,verbosity:i=A()}={}){if(this.name=t,this.destroyed=!1,this.verbosity=i,this._readyCapability=Promise.withResolvers(),this._port=null,this._webWorker=null,this._messageHandler=null,e){if(hi.#Ji?.has(e))throw new Error("Cannot use more than one PDFWorker per port.");return(hi.#Ji||=new WeakMap).set(e,this),void this._initializeFromPort(e)}this._initialize()}get promise(){return n?Promise.all([Ut.promise,this._readyCapability.promise]):this._readyCapability.promise}#Zi(){this._readyCapability.resolve(),this._messageHandler.send("configure",{verbosity:this.verbosity})}get port(){return this._port}get messageHandler(){return this._messageHandler}_initializeFromPort(t){this._port=t,this._messageHandler=new ve("main","worker",t),this._messageHandler.on("ready",(function(){})),this.#Zi()}_initialize(){if(hi.#Qi||hi.#ts)return void this._setupFakeWorker();let{workerSrc:t}=hi;try{hi._isSameOrigin(window.location.href,t)||(t=hi._createCDNWrapper(new URL(t,window.location).href));const e=new Worker(t,{type:"module"}),i=new ve("main","worker",e),s=()=>{n.abort(),i.destroy(),e.terminate(),this.destroyed?this._readyCapability.reject(new Error("Worker was destroyed")):this._setupFakeWorker()},n=new AbortController;e.addEventListener("error",(()=>{this._webWorker||s()}),{signal:n.signal}),i.on("test",(t=>{n.abort(),!this.destroyed&&t?(this._messageHandler=i,this._port=e,this._webWorker=e,this.#Zi()):s()})),i.on("ready",(t=>{if(n.abort(),this.destroyed)s();else try{a()}catch{this._setupFakeWorker()}}));const a=()=>{const t=new Uint8Array;i.send("test",t,[t.buffer])};return void a()}catch{y("The worker has been disabled.")}this._setupFakeWorker()}_setupFakeWorker(){hi.#Qi||(w("Setting up fake worker."),hi.#Qi=!0),hi._setupFakeWorkerGlobal.then((t=>{if(this.destroyed)return void this._readyCapability.reject(new Error("Worker was destroyed"));const e=new li;this._port=e;const i="fake"+hi.#Yi++,s=new ve(i+"_worker",i,e);t.setup(s,e),this._messageHandler=new ve(i,i+"_worker",e),this.#Zi()})).catch((t=>{this._readyCapability.reject(new Error(`Setting up fake worker failed: "${t.message}".`))}))}destroy(){this.destroyed=!0,this._webWorker&&(this._webWorker.terminate(),this._webWorker=null),hi.#Ji?.delete(this._port),this._port=null,this._messageHandler&&(this._messageHandler.destroy(),this._messageHandler=null)}static fromPort(t){if(!t?.port)throw new Error("PDFWorker.fromPort - invalid method signature.");const e=this.#Ji?.get(t.port);if(e){if(e._pendingDestroy)throw new Error("PDFWorker.fromPort - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return e}return new hi(t)}static get workerSrc(){if(fe.workerSrc)return fe.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get#ts(){try{return globalThis.pdfjsWorker?.WorkerMessageHandler||null}catch{return null}}static get _setupFakeWorkerGlobal(){return E(this,"_setupFakeWorkerGlobal",(async()=>this.#ts?this.#ts:(await import(this.workerSrc)).WorkerMessageHandler)())}}class di{#es=new Map;#is=new Map;#ss=new Map;#ns=new Map;#as=null;constructor(t,e,i,s,n){this.messageHandler=t,this.loadingTask=e,this.commonObjs=new ui,this.fontLoader=new Bt({ownerDocument:s.ownerDocument,styleElement:s.styleElement}),this.loadingParams=s.loadingParams,this._params=s,this.canvasFactory=n.canvasFactory,this.filterFactory=n.filterFactory,this.cMapReaderFactory=n.cMapReaderFactory,this.standardFontDataFactory=n.standardFontDataFactory,this.destroyed=!1,this.destroyCapability=null,this._networkStream=i,this._fullReader=null,this._lastProgress=null,this.downloadInfoCapability=Promise.withResolvers(),this.setupMessageHandler()}#rs(t,e=null){const i=this.#es.get(t);if(i)return i;const s=this.messageHandler.sendWithPromise(t,e);return this.#es.set(t,s),s}get annotationStorage(){return E(this,"annotationStorage",new Nt)}getRenderingIntent(t,e=l.ENABLE,i=null,s=!1,n=!1){let a=2,r=Ft;switch(t){case"any":a=1;break;case"display":break;case"print":a=4;break;default:w(`getRenderingIntent - invalid intent: ${t}`)}const o=4&a&&i instanceof Ot?i:this.annotationStorage;switch(e){case l.DISABLE:a+=64;break;case l.ENABLE:break;case l.ENABLE_FORMS:a+=16;break;case l.ENABLE_STORAGE:a+=32,r=o.serializable;break;default:w(`getRenderingIntent - invalid annotationMode: ${e}`)}s&&(a+=128),n&&(a+=256);const{ids:h,hash:d}=o.modifiedIds;return{renderingIntent:a,cacheKey:[a,r.hash,d].join("_"),annotationStorageSerializable:r,modifiedIds:h}}destroy(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=Promise.withResolvers(),this.#as?.reject(new Error("Worker was destroyed during onPassword callback"));const t=[];for(const e of this.#is.values())t.push(e._destroy());this.#is.clear(),this.#ss.clear(),this.#ns.clear(),this.hasOwnProperty("annotationStorage")&&this.annotationStorage.resetModified();const e=this.messageHandler.sendWithPromise("Terminate",null);return t.push(e),Promise.all(t).then((()=>{this.commonObjs.clear(),this.fontLoader.clear(),this.#es.clear(),this.filterFactory.destroy(),Ye.cleanup(),this._networkStream?.cancelAllRequests(new D("Worker was terminated.")),this.messageHandler&&(this.messageHandler.destroy(),this.messageHandler=null),this.destroyCapability.resolve()}),this.destroyCapability.reject),this.destroyCapability.promise}setupMessageHandler(){const{messageHandler:t,loadingTask:e}=this;t.on("GetReader",((t,e)=>{x(this._networkStream,"GetReader - no `IPDFStream` instance available."),this._fullReader=this._networkStream.getFullReader(),this._fullReader.onProgress=t=>{this._lastProgress={loaded:t.loaded,total:t.total}},e.onPull=()=>{this._fullReader.read().then((function({value:t,done:i}){i?e.close():(x(t instanceof ArrayBuffer,"GetReader - expected an ArrayBuffer."),e.enqueue(new Uint8Array(t),1,[t]))})).catch((t=>{e.error(t)}))},e.onCancel=t=>{this._fullReader.cancel(t),e.ready.catch((t=>{if(!this.destroyed)throw t}))}})),t.on("ReaderHeadersReady",(t=>{const i=Promise.withResolvers(),s=this._fullReader;return s.headersReady.then((()=>{s.isStreamingSupported&&s.isRangeSupported||(this._lastProgress&&e.onProgress?.(this._lastProgress),s.onProgress=t=>{e.onProgress?.({loaded:t.loaded,total:t.total})}),i.resolve({isStreamingSupported:s.isStreamingSupported,isRangeSupported:s.isRangeSupported,contentLength:s.contentLength})}),i.reject),i.promise})),t.on("GetRangeReader",((t,e)=>{x(this._networkStream,"GetRangeReader - no `IPDFStream` instance available.");const i=this._networkStream.getRangeReader(t.begin,t.end);i?(e.onPull=()=>{i.read().then((function({value:t,done:i}){i?e.close():(x(t instanceof ArrayBuffer,"GetRangeReader - expected an ArrayBuffer."),e.enqueue(new Uint8Array(t),1,[t]))})).catch((t=>{e.error(t)}))},e.onCancel=t=>{i.cancel(t),e.ready.catch((t=>{if(!this.destroyed)throw t}))}):e.close()})),t.on("GetDoc",(({pdfInfo:t})=>{this._numPages=t.numPages,this._htmlForXfa=t.htmlForXfa,delete t.htmlForXfa,e._capability.resolve(new ri(t,this))})),t.on("DocException",(function(t){let i;switch(t.name){case"PasswordException":i=new T(t.message,t.code);break;case"InvalidPDFException":i=new k(t.message);break;case"MissingPDFException":i=new I(t.message);break;case"UnexpectedResponseException":i=new P(t.message,t.status);break;case"UnknownErrorException":i=new M(t.message,t.details);break;default:_("DocException - expected a valid Error.")}e._capability.reject(i)})),t.on("PasswordRequest",(t=>{if(this.#as=Promise.withResolvers(),e.onPassword){const i=t=>{t instanceof Error?this.#as.reject(t):this.#as.resolve({password:t})};try{e.onPassword(i,t.code)}catch(t){this.#as.reject(t)}}else this.#as.reject(new T(t.message,t.code));return this.#as.promise})),t.on("DataLoaded",(t=>{e.onProgress?.({loaded:t.length,total:t.length}),this.downloadInfoCapability.resolve(t)})),t.on("StartRenderPage",(t=>{this.destroyed||this.#is.get(t.pageIndex)._startRenderPage(t.transparency,t.cacheKey)})),t.on("commonobj",(([e,i,s])=>{if(this.destroyed)return null;if(this.commonObjs.has(e))return null;switch(i){case"Font":const{disableFontFace:n,fontExtraProperties:a,pdfBug:r}=this._params;if("error"in s){const t=s.error;w(`Error during font loading: ${t}`),this.commonObjs.resolve(e,t);break}const o=r&&globalThis.FontInspector?.enabled?(t,e)=>globalThis.FontInspector.fontAdded(t,e):null,l=new zt(s,{disableFontFace:n,inspectFont:o});this.fontLoader.bind(l).catch((()=>t.sendWithPromise("FontFallback",{id:e}))).finally((()=>{!a&&l.data&&(l.data=null),this.commonObjs.resolve(e,l)}));break;case"CopyLocalImage":const{imageRef:h}=s;x(h,"The imageRef must be defined.");for(const t of this.#is.values())for(const[,i]of t.objs)if(i?.ref===h)return i.dataLen?(this.commonObjs.resolve(e,structuredClone(i)),i.dataLen):null;break;case"FontPath":case"Image":case"Pattern":this.commonObjs.resolve(e,s);break;default:throw new Error(`Got unknown common object type ${i}`)}return null})),t.on("obj",(([t,e,i,s])=>{if(this.destroyed)return;const n=this.#is.get(e);if(!n.objs.has(t))if(0!==n._intentStates.size)switch(i){case"Image":n.objs.resolve(t,s),s?.dataLen>1e7&&(n._maybeCleanupAfterRender=!0);break;case"Pattern":n.objs.resolve(t,s);break;default:throw new Error(`Got unknown object type ${i}`)}else s?.bitmap?.close()})),t.on("DocProgress",(t=>{this.destroyed||e.onProgress?.({loaded:t.loaded,total:t.total})})),t.on("FetchBuiltInCMap",(t=>this.destroyed?Promise.reject(new Error("Worker was destroyed.")):this.cMapReaderFactory?this.cMapReaderFactory.fetch(t):Promise.reject(new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter.")))),t.on("FetchStandardFontData",(t=>this.destroyed?Promise.reject(new Error("Worker was destroyed.")):this.standardFontDataFactory?this.standardFontDataFactory.fetch(t):Promise.reject(new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter."))))}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){this.annotationStorage.size<=0&&w("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");const{map:t,transfer:e}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:t,filename:this._fullReader?.filename??null},e).finally((()=>{this.annotationStorage.resetModified()}))}getPage(t){if(!Number.isInteger(t)||t<=0||t>this._numPages)return Promise.reject(new Error("Invalid page request."));const e=t-1,i=this.#ss.get(e);if(i)return i;const s=this.messageHandler.sendWithPromise("GetPage",{pageIndex:e}).then((i=>{if(this.destroyed)throw new Error("Transport destroyed");i.refStr&&this.#ns.set(i.refStr,t);const s=new oi(e,i,this,this._params.pdfBug);return this.#is.set(e,s),s}));return this.#ss.set(e,s),s}getPageIndex(t){return si(t)?this.messageHandler.sendWithPromise("GetPageIndex",{num:t.num,gen:t.gen}):Promise.reject(new Error("Invalid pageIndex request."))}getAnnotations(t,e){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:t,intent:e})}getFieldObjects(){return this.#rs("GetFieldObjects")}hasJSActions(){return this.#rs("HasJSActions")}getCalculationOrderIds(){return this.messageHandler.sendWithPromise("GetCalculationOrderIds",null)}getDestinations(){return this.messageHandler.sendWithPromise("GetDestinations",null)}getDestination(t){return"string"!=typeof t?Promise.reject(new Error("Invalid destination request.")):this.messageHandler.sendWithPromise("GetDestination",{id:t})}getPageLabels(){return this.messageHandler.sendWithPromise("GetPageLabels",null)}getPageLayout(){return this.messageHandler.sendWithPromise("GetPageLayout",null)}getPageMode(){return this.messageHandler.sendWithPromise("GetPageMode",null)}getViewerPreferences(){return this.messageHandler.sendWithPromise("GetViewerPreferences",null)}getOpenAction(){return this.messageHandler.sendWithPromise("GetOpenAction",null)}getAttachments(){return this.messageHandler.sendWithPromise("GetAttachments",null)}getDocJSActions(){return this.#rs("GetDocJSActions")}getPageJSActions(t){return this.messageHandler.sendWithPromise("GetPageJSActions",{pageIndex:t})}getStructTree(t){return this.messageHandler.sendWithPromise("GetStructTree",{pageIndex:t})}getOutline(){return this.messageHandler.sendWithPromise("GetOutline",null)}getOptionalContentConfig(t){return this.#rs("GetOptionalContentConfig").then((e=>new _e(e,t)))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const t="GetMetadata",e=this.#es.get(t);if(e)return e;const i=this.messageHandler.sendWithPromise(t,null).then((t=>({info:t[0],metadata:t[1]?new Ae(t[1]):null,contentDispositionFilename:this._fullReader?.filename??null,contentLength:this._fullReader?.contentLength??null})));return this.#es.set(t,i),i}getMarkInfo(){return this.messageHandler.sendWithPromise("GetMarkInfo",null)}async startCleanup(t=!1){if(!this.destroyed){await this.messageHandler.sendWithPromise("Cleanup",null);for(const t of this.#is.values())if(!t.cleanup())throw new Error(`startCleanup: Page ${t.pageNumber} is currently rendering.`);this.commonObjs.clear(),t||this.fontLoader.clear(),this.#es.clear(),this.filterFactory.destroy(!0),Ye.cleanup()}}cachedPageNumber(t){if(!si(t))return null;const e=0===t.gen?`${t.num}R`:`${t.num}R${t.gen}`;return this.#ns.get(e)??null}}const ci=Symbol("INITIAL_DATA");class ui{#os=Object.create(null);#ls(t){return this.#os[t]||={...Promise.withResolvers(),data:ci}}get(t,e=null){if(e){const i=this.#ls(t);return i.promise.then((()=>e(i.data))),null}const i=this.#os[t];if(!i||i.data===ci)throw new Error(`Requesting object that isn't resolved yet ${t}.`);return i.data}has(t){const e=this.#os[t];return!!e&&e.data!==ci}resolve(t,e=null){const i=this.#ls(t);i.data=e,i.resolve()}clear(){for(const t in this.#os){const{data:e}=this.#os[t];e?.bitmap?.close()}this.#os=Object.create(null)}*[Symbol.iterator](){for(const t in this.#os){const{data:e}=this.#os[t];e!==ci&&(yield[t,e])}}}class pi{#hs=null;constructor(t){this.#hs=t,this.onContinue=null}get promise(){return this.#hs.capability.promise}cancel(t=0){this.#hs.cancel(null,t)}get separateAnnots(){const{separateAnnots:t}=this.#hs.operatorList;if(!t)return!1;const{annotationCanvasMap:e}=this.#hs;return t.form||t.canvas&&e?.size>0}}class gi{#ds=null;static#cs=new WeakSet;constructor({callback:t,params:e,objs:i,commonObjs:s,annotationCanvasMap:n,operatorList:a,pageIndex:r,canvasFactory:o,filterFactory:l,useRequestAnimationFrame:h=!1,pdfBug:d=!1,pageColors:c=null}){this.callback=t,this.params=e,this.objs=i,this.commonObjs=s,this.annotationCanvasMap=n,this.operatorListIdx=null,this.operatorList=a,this._pageIndex=r,this.canvasFactory=o,this.filterFactory=l,this._pdfBug=d,this.pageColors=c,this.running=!1,this.graphicsReadyCallback=null,this.graphicsReady=!1,this._useRequestAnimationFrame=!0===h&&"undefined"!=typeof window,this.cancelled=!1,this.capability=Promise.withResolvers(),this.task=new pi(this),this._cancelBound=this.cancel.bind(this),this._continueBound=this._continue.bind(this),this._scheduleNextBound=this._scheduleNext.bind(this),this._nextBound=this._next.bind(this),this._canvas=e.canvasContext.canvas}get completed(){return this.capability.promise.catch((function(){}))}initializeGraphics({transparency:t=!1,optionalContentConfig:e}){if(this.cancelled)return;if(this._canvas){if(gi.#cs.has(this._canvas))throw new Error("Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.");gi.#cs.add(this._canvas)}this._pdfBug&&globalThis.StepperManager?.enabled&&(this.stepper=globalThis.StepperManager.create(this._pageIndex),this.stepper.init(this.operatorList),this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint());const{canvasContext:i,viewport:s,transform:n,background:a}=this.params;this.gfx=new me(i,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:e},this.annotationCanvasMap,this.pageColors),this.gfx.beginDrawing({transform:n,viewport:s,transparency:t,background:a}),this.operatorListIdx=0,this.graphicsReady=!0,this.graphicsReadyCallback?.()}cancel(t=null,e=0){this.running=!1,this.cancelled=!0,this.gfx?.endDrawing(),this.#ds&&(window.cancelAnimationFrame(this.#ds),this.#ds=null),gi.#cs.delete(this._canvas),this.callback(t||new it(`Rendering cancelled, page ${this._pageIndex+1}`,e))}operatorListChanged(){this.graphicsReady?(this.stepper?.updateOperatorList(this.operatorList),this.running||this._continue()):this.graphicsReadyCallback||=this._continueBound}_continue(){this.running=!0,this.cancelled||(this.task.onContinue?this.task.onContinue(this._scheduleNextBound):this._scheduleNext())}_scheduleNext(){this._useRequestAnimationFrame?this.#ds=window.requestAnimationFrame((()=>{this.#ds=null,this._nextBound().catch(this._cancelBound)})):Promise.resolve().then(this._nextBound).catch(this._cancelBound)}async _next(){this.cancelled||(this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper),this.operatorListIdx===this.operatorList.argsArray.length&&(this.running=!1,this.operatorList.lastChunk&&(this.gfx.endDrawing(),gi.#cs.delete(this._canvas),this.callback())))}}const mi="4.7.76",fi="8b73b828b";function bi(t){return Math.floor(255*Math.max(0,Math.min(1,t))).toString(16).padStart(2,"0")}function vi(t){return Math.max(0,Math.min(255,255*t))}class Ai{static CMYK_G([t,e,i,s]){return["G",1-Math.min(1,.3*t+.59*i+.11*e+s)]}static G_CMYK([t]){return["CMYK",0,0,0,1-t]}static G_RGB([t]){return["RGB",t,t,t]}static G_rgb([t]){return[t=vi(t),t,t]}static G_HTML([t]){const e=bi(t);return`#${e}${e}${e}`}static RGB_G([t,e,i]){return["G",.3*t+.59*e+.11*i]}static RGB_rgb(t){return t.map(vi)}static RGB_HTML(t){return`#${t.map(bi).join("")}`}static T_HTML(){return"#00000000"}static T_rgb(){return[null]}static CMYK_RGB([t,e,i,s]){return["RGB",1-Math.min(1,t+s),1-Math.min(1,i+s),1-Math.min(1,e+s)]}static CMYK_rgb([t,e,i,s]){return[vi(1-Math.min(1,t+s)),vi(1-Math.min(1,i+s)),vi(1-Math.min(1,e+s))]}static CMYK_HTML(t){const e=this.CMYK_RGB(t).slice(1);return this.RGB_HTML(e)}static RGB_CMYK([t,e,i]){const s=1-t,n=1-e,a=1-i;return["CMYK",s,n,a,Math.min(s,n,a)]}}class yi{static setupStorage(t,e,i,s,n){const a=s.getValue(e,{value:null});switch(i.name){case"textarea":if(null!==a.value&&(t.textContent=a.value),"print"===n)break;t.addEventListener("input",(t=>{s.setValue(e,{value:t.target.value})}));break;case"input":if("radio"===i.attributes.type||"checkbox"===i.attributes.type){if(a.value===i.attributes.xfaOn?t.setAttribute("checked",!0):a.value===i.attributes.xfaOff&&t.removeAttribute("checked"),"print"===n)break;t.addEventListener("change",(t=>{s.setValue(e,{value:t.target.checked?t.target.getAttribute("xfaOn"):t.target.getAttribute("xfaOff")})}))}else{if(null!==a.value&&t.setAttribute("value",a.value),"print"===n)break;t.addEventListener("input",(t=>{s.setValue(e,{value:t.target.value})}))}break;case"select":if(null!==a.value){t.setAttribute("value",a.value);for(const t of i.children)t.attributes.value===a.value?t.attributes.selected=!0:t.attributes.hasOwnProperty("selected")&&delete t.attributes.selected}t.addEventListener("input",(t=>{const i=t.target.options,n=-1===i.selectedIndex?"":i[i.selectedIndex].value;s.setValue(e,{value:n})}))}}static setAttributes({html:t,element:e,storage:i=null,intent:s,linkService:n}){const{attributes:a}=e,r=t instanceof HTMLAnchorElement;"radio"===a.type&&(a.name=`${a.name}-${s}`);for(const[e,i]of Object.entries(a))if(null!=i)switch(e){case"class":i.length&&t.setAttribute(e,i.join(" "));break;case"dataId":break;case"id":t.setAttribute("data-element-id",i);break;case"style":Object.assign(t.style,i);break;case"textContent":t.textContent=i;break;default:(!r||"href"!==e&&"newWindow"!==e)&&t.setAttribute(e,i)}r&&n.addLinkAttributes(t,a.href,a.newWindow),i&&a.dataId&&this.setupStorage(t,a.dataId,e,i)}static render(t){const e=t.annotationStorage,i=t.linkService,s=t.xfaHtml,n=t.intent||"display",a=document.createElement(s.name);s.attributes&&this.setAttributes({html:a,element:s,intent:n,linkService:i});const r="richText"!==n,o=t.div;if(o.append(a),t.viewport){const e=`matrix(${t.viewport.transform.join(",")})`;o.style.transform=e}r&&o.setAttribute("class","xfaLayer xfaFont");const l=[];if(0===s.children.length){if(s.value){const t=document.createTextNode(s.value);a.append(t),r&&Qe.shouldBuildText(s.name)&&l.push(t)}return{textDivs:l}}const h=[[s,-1,a]];for(;h.length>0;){const[t,s,a]=h.at(-1);if(s+1===t.children.length){h.pop();continue}const o=t.children[++h.at(-1)[1]];if(null===o)continue;const{name:d}=o;if("#text"===d){const t=document.createTextNode(o.value);l.push(t),a.append(t);continue}const c=o?.attributes?.xmlns?document.createElementNS(o.attributes.xmlns,d):document.createElement(d);if(a.append(c),o.attributes&&this.setAttributes({html:c,element:o,storage:e,intent:n,linkService:i}),o.children?.length>0)h.push([o,-1,c]);else if(o.value){const t=document.createTextNode(o.value);r&&Qe.shouldBuildText(d)&&l.push(t),c.append(t)}}for(const t of o.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))t.setAttribute("readOnly",!0);return{textDivs:l}}static update(t){const e=`matrix(${t.viewport.transform.join(",")})`;t.div.style.transform=e,t.div.hidden=!1}}const wi=1e3,_i=new WeakSet;function xi(t){return{width:t[2]-t[0],height:t[3]-t[1]}}class Ci{static create(t){switch(t.data.annotationType){case 2:return new Si(t);case 1:return new Ti(t);case 20:switch(t.data.fieldType){case"Tx":return new ki(t);case"Btn":return t.data.radioButton?new Ri(t):t.data.checkBox?new Pi(t):new Di(t);case"Ch":return new Li(t);case"Sig":return new Ii(t)}return new Mi(t);case 16:return new Fi(t);case 3:return new Oi(t);case 4:return new Bi(t);case 5:return new zi(t);case 6:return new Hi(t);case 8:return new ji(t);case 14:return new $i(t);case 15:return new Wi(t);case 7:return new Ui(t);case 9:return new Gi(t);case 10:return new Vi(t);case 11:return new qi(t);case 12:return new Xi(t);case 13:return new Ki(t);case 17:return new Yi(t);default:return new Ei(t)}}}class Ei{#us=null;#ps=!1;#gs=null;constructor(t,{isRenderable:e=!1,ignoreBorder:i=!1,createQuadrilaterals:s=!1}={}){this.isRenderable=e,this.data=t.data,this.layer=t.layer,this.linkService=t.linkService,this.downloadManager=t.downloadManager,this.imageResourcesPath=t.imageResourcesPath,this.renderForms=t.renderForms,this.svgFactory=t.svgFactory,this.annotationStorage=t.annotationStorage,this.enableScripting=t.enableScripting,this.hasJSActions=t.hasJSActions,this._fieldObjects=t.fieldObjects,this.parent=t.parent,e&&(this.container=this._createContainer(i)),s&&this._createQuadrilaterals()}static _hasPopupData({titleObj:t,contentsObj:e,richText:i}){return!!(t?.str||e?.str||i?.str)}get _isEditable(){return this.data.isEditable}get hasPopupData(){return Ei._hasPopupData(this.data)}updateEdited(t){if(!this.container)return;this.#us||={rect:this.data.rect.slice(0)};const{rect:e}=t;e&&this.#ms(e),this.#gs?.popup.updateEdited(t)}resetEdited(){this.#us&&(this.#ms(this.#us.rect),this.#gs?.popup.resetEdited(),this.#us=null)}#ms(t){const{container:{style:e},data:{rect:i,rotation:s},parent:{viewport:{rawDims:{pageWidth:n,pageHeight:a,pageX:r,pageY:o}}}}=this;i?.splice(0,4,...t);const{width:l,height:h}=xi(t);e.left=100*(t[0]-r)/n+"%",e.top=100*(a-t[3]+o)/a+"%",0===s?(e.width=100*l/n+"%",e.height=100*h/a+"%"):this.setRotation(s)}_createContainer(t){const{data:e,parent:{page:i,viewport:s}}=this,n=document.createElement("section");n.setAttribute("data-annotation-id",e.id),this instanceof Mi||(n.tabIndex=wi);const{style:a}=n;if(a.zIndex=this.parent.zIndex++,e.popupRef&&n.setAttribute("aria-haspopup","dialog"),e.alternativeText&&(n.title=e.alternativeText),e.noRotate&&n.classList.add("norotate"),!e.rect||this instanceof Fi){const{rotation:t}=e;return e.hasOwnCanvas||0===t||this.setRotation(t,n),n}const{width:r,height:o}=xi(e.rect);if(!t&&e.borderStyle.width>0){a.borderWidth=`${e.borderStyle.width}px`;const t=e.borderStyle.horizontalCornerRadius,i=e.borderStyle.verticalCornerRadius;if(t>0||i>0){const e=`calc(${t}px * var(--scale-factor)) / calc(${i}px * var(--scale-factor))`;a.borderRadius=e}else if(this instanceof Ri){const t=`calc(${r}px * var(--scale-factor)) / calc(${o}px * var(--scale-factor))`;a.borderRadius=t}switch(e.borderStyle.style){case 1:a.borderStyle="solid";break;case 2:a.borderStyle="dashed";break;case 3:w("Unimplemented border style: beveled");break;case 4:w("Unimplemented border style: inset");break;case 5:a.borderBottomStyle="solid"}const s=e.borderColor||null;s?(this.#ps=!0,a.borderColor=z.makeHexColor(0|s[0],0|s[1],0|s[2])):a.borderWidth=0}const l=z.normalizeRect([e.rect[0],i.view[3]-e.rect[1]+i.view[1],e.rect[2],i.view[3]-e.rect[3]+i.view[1]]),{pageWidth:h,pageHeight:d,pageX:c,pageY:u}=s.rawDims;a.left=100*(l[0]-c)/h+"%",a.top=100*(l[1]-u)/d+"%";const{rotation:p}=e;return e.hasOwnCanvas||0===p?(a.width=100*r/h+"%",a.height=100*o/d+"%"):this.setRotation(p,n),n}setRotation(t,e=this.container){if(!this.data.rect)return;const{pageWidth:i,pageHeight:s}=this.parent.viewport.rawDims,{width:n,height:a}=xi(this.data.rect);let r,o;t%180==0?(r=100*n/i,o=100*a/s):(r=100*a/i,o=100*n/s),e.style.width=`${r}%`,e.style.height=`${o}%`,e.setAttribute("data-main-rotation",(360-t)%360)}get _commonActions(){const t=(t,e,i)=>{const s=i.detail[t],n=s[0],a=s.slice(1);i.target.style[e]=Ai[`${n}_HTML`](a),this.annotationStorage.setValue(this.data.id,{[e]:Ai[`${n}_rgb`](a)})};return E(this,"_commonActions",{display:t=>{const{display:e}=t.detail,i=e%2==1;this.container.style.visibility=i?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noView:i,noPrint:1===e||2===e})},print:t=>{this.annotationStorage.setValue(this.data.id,{noPrint:!t.detail.print})},hidden:t=>{const{hidden:e}=t.detail;this.container.style.visibility=e?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noPrint:e,noView:e})},focus:t=>{setTimeout((()=>t.target.focus({preventScroll:!1})),0)},userName:t=>{t.target.title=t.detail.userName},readonly:t=>{t.target.disabled=t.detail.readonly},required:t=>{this._setRequired(t.target,t.detail.required)},bgColor:e=>{t("bgColor","backgroundColor",e)},fillColor:e=>{t("fillColor","backgroundColor",e)},fgColor:e=>{t("fgColor","color",e)},textColor:e=>{t("textColor","color",e)},borderColor:e=>{t("borderColor","borderColor",e)},strokeColor:e=>{t("strokeColor","borderColor",e)},rotation:t=>{const e=t.detail.rotation;this.setRotation(e),this.annotationStorage.setValue(this.data.id,{rotation:e})}})}_dispatchEventFromSandbox(t,e){const i=this._commonActions;for(const s of Object.keys(e.detail))(t[s]||i[s])?.(e)}_setDefaultPropertiesFromJS(t){if(!this.enableScripting)return;const e=this.annotationStorage.getRawValue(this.data.id);if(!e)return;const i=this._commonActions;for(const[s,n]of Object.entries(e)){const a=i[s];a&&(a({detail:{[s]:n},target:t}),delete e[s])}}_createQuadrilaterals(){if(!this.container)return;const{quadPoints:t}=this.data;if(!t)return;const[e,i,s,n]=this.data.rect.map((t=>Math.fround(t)));if(8===t.length){const[a,r,o,l]=t.subarray(2,6);if(s===a&&n===r&&e===o&&i===l)return}const{style:a}=this.container;let r;if(this.#ps){const{borderColor:t,borderWidth:e}=a;a.borderWidth=0,r=["url('data:image/svg+xml;utf8,",'',``],this.container.classList.add("hasBorder")}const o=s-e,l=n-i,{svgFactory:h}=this,d=h.createElement("svg");d.classList.add("quadrilateralsContainer"),d.setAttribute("width",0),d.setAttribute("height",0);const c=h.createElement("defs");d.append(c);const u=h.createElement("clipPath"),p=`clippath_${this.data.id}`;u.setAttribute("id",p),u.setAttribute("clipPathUnits","objectBoundingBox"),c.append(u);for(let i=2,s=t.length;i`)}this.#ps&&(r.push("')"),a.backgroundImage=r.join("")),this.container.append(d),this.container.style.clipPath=`url(#${p})`}_createPopup(){const{container:t,data:e}=this;t.setAttribute("aria-haspopup","dialog");const i=this.#gs=new Fi({data:{color:e.color,titleObj:e.titleObj,modificationDate:e.modificationDate,contentsObj:e.contentsObj,richText:e.richText,parentRect:e.rect,borderStyle:0,id:`popup_${e.id}`,rotation:e.rotation},parent:this.parent,elements:[this]});this.parent.div.append(i.render())}render(){_("Abstract method `AnnotationElement.render` called")}_getElementsByName(t,e=null){const i=[];if(this._fieldObjects){const s=this._fieldObjects[t];if(s)for(const{page:t,id:n,exportValues:a}of s){if(-1===t)continue;if(n===e)continue;const s="string"==typeof a?a:null,r=document.querySelector(`[data-element-id="${n}"]`);!r||_i.has(r)?i.push({id:n,exportValue:s,domElement:r}):w(`_getElementsByName - element not allowed: ${n}`)}return i}for(const s of document.getElementsByName(t)){const{exportValue:t}=s,n=s.getAttribute("data-element-id");n!==e&&_i.has(s)&&i.push({id:n,exportValue:t,domElement:s})}return i}show(){this.container&&(this.container.hidden=!1),this.popup?.maybeShow()}hide(){this.container&&(this.container.hidden=!0),this.popup?.forceHide()}getElementsToTriggerPopup(){return this.container}addHighlightArea(){const t=this.getElementsToTriggerPopup();if(Array.isArray(t))for(const e of t)e.classList.add("highlightArea");else t.classList.add("highlightArea")}_editOnDoubleClick(){if(!this._isEditable)return;const{annotationEditorType:t,data:{id:e}}=this;this.container.addEventListener("dblclick",(()=>{this.linkService.eventBus?.dispatch("switchannotationeditormode",{source:this,mode:t,editId:e})}))}}class Si extends Ei{constructor(t,e=null){super(t,{isRenderable:!0,ignoreBorder:!!e?.ignoreBorder,createQuadrilaterals:!0}),this.isTooltipOnly=t.data.isTooltipOnly}render(){const{data:t,linkService:e}=this,i=document.createElement("a");i.setAttribute("data-element-id",t.id);let s=!1;return t.url?(e.addLinkAttributes(i,t.url,t.newWindow),s=!0):t.action?(this._bindNamedAction(i,t.action),s=!0):t.attachment?(this.#fs(i,t.attachment,t.attachmentDest),s=!0):t.setOCGState?(this.#bs(i,t.setOCGState),s=!0):t.dest?(this._bindLink(i,t.dest),s=!0):(t.actions&&(t.actions.Action||t.actions["Mouse Up"]||t.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions&&(this._bindJSAction(i,t),s=!0),t.resetForm?(this._bindResetFormAction(i,t.resetForm),s=!0):this.isTooltipOnly&&!s&&(this._bindLink(i,""),s=!0)),this.container.classList.add("linkAnnotation"),s&&this.container.append(i),this.container}#vs(){this.container.setAttribute("data-internal-link","")}_bindLink(t,e){t.href=this.linkService.getDestinationHash(e),t.onclick=()=>(e&&this.linkService.goToDestination(e),!1),(e||""===e)&&this.#vs()}_bindNamedAction(t,e){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeNamedAction(e),!1),this.#vs()}#fs(t,e,i=null){t.href=this.linkService.getAnchorUrl(""),e.description&&(t.title=e.description),t.onclick=()=>(this.downloadManager?.openOrDownloadData(e.content,e.filename,i),!1),this.#vs()}#bs(t,e){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeSetOCGState(e),!1),this.#vs()}_bindJSAction(t,e){t.href=this.linkService.getAnchorUrl("");const i=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(const s of Object.keys(e.actions)){const n=i.get(s);n&&(t[n]=()=>(this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e.id,name:s}}),!1))}t.onclick||(t.onclick=()=>!1),this.#vs()}_bindResetFormAction(t,e){const i=t.onclick;if(i||(t.href=this.linkService.getAnchorUrl("")),this.#vs(),!this._fieldObjects)return w('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.'),void(i||(t.onclick=()=>!1));t.onclick=()=>{i?.();const{fields:t,refs:s,include:n}=e,a=[];if(0!==t.length||0!==s.length){const e=new Set(s);for(const i of t){const t=this._fieldObjects[i]||[];for(const{id:i}of t)e.add(i)}for(const t of Object.values(this._fieldObjects))for(const i of t)e.has(i.id)===n&&a.push(i)}else for(const t of Object.values(this._fieldObjects))a.push(...t);const r=this.annotationStorage,o=[];for(const t of a){const{id:e}=t;switch(o.push(e),t.type){case"text":{const i=t.defaultValue||"";r.setValue(e,{value:i});break}case"checkbox":case"radiobutton":{const i=t.defaultValue===t.exportValues;r.setValue(e,{value:i});break}case"combobox":case"listbox":{const i=t.defaultValue||"";r.setValue(e,{value:i});break}default:continue}const i=document.querySelector(`[data-element-id="${e}"]`);i&&(_i.has(i)?i.dispatchEvent(new Event("resetform")):w(`_bindResetFormAction - element not allowed: ${e}`))}return this.enableScripting&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:o,name:"ResetForm"}}),!1}}}class Ti extends Ei{constructor(t){super(t,{isRenderable:!0})}render(){this.container.classList.add("textAnnotation");const t=document.createElement("img");return t.src=this.imageResourcesPath+"annotation-"+this.data.name.toLowerCase()+".svg",t.setAttribute("data-l10n-id","pdfjs-text-annotation-type"),t.setAttribute("data-l10n-args",JSON.stringify({type:this.data.name})),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.append(t),this.container}}class Mi extends Ei{render(){return this.container}showElementAndHideCanvas(t){this.data.hasOwnCanvas&&("CANVAS"===t.previousSibling?.nodeName&&(t.previousSibling.hidden=!0),t.hidden=!1)}_getKeyModifier(t){return O.platform.isMac?t.metaKey:t.ctrlKey}_setEventListener(t,e,i,s,n){i.includes("mouse")?t.addEventListener(i,(t=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:s,value:n(t),shift:t.shiftKey,modifier:this._getKeyModifier(t)}})})):t.addEventListener(i,(t=>{if("blur"===i){if(!e.focused||!t.relatedTarget)return;e.focused=!1}else if("focus"===i){if(e.focused)return;e.focused=!0}n&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:s,value:n(t)}})}))}_setEventListeners(t,e,i,s){for(const[n,a]of i)("Action"===a||this.data.actions?.[a])&&("Focus"!==a&&"Blur"!==a||(e||={focused:!1}),this._setEventListener(t,e,n,a,s),"Focus"!==a||this.data.actions?.Blur?"Blur"!==a||this.data.actions?.Focus||this._setEventListener(t,e,"focus","Focus",null):this._setEventListener(t,e,"blur","Blur",null))}_setBackgroundColor(t){const e=this.data.backgroundColor||null;t.style.backgroundColor=null===e?"transparent":z.makeHexColor(e[0],e[1],e[2])}_setTextStyle(t){const{fontColor:e}=this.data.defaultAppearanceData,i=this.data.defaultAppearanceData.fontSize||9,s=t.style;let n;const a=t=>Math.round(10*t)/10;if(this.data.multiLine){const t=Math.abs(this.data.rect[3]-this.data.rect[1]-2),e=t/(Math.round(t/(o*i))||1);n=Math.min(i,a(e/o))}else{const t=Math.abs(this.data.rect[3]-this.data.rect[1]-2);n=Math.min(i,a(t/o))}s.fontSize=`calc(${n}px * var(--scale-factor))`,s.color=z.makeHexColor(e[0],e[1],e[2]),null!==this.data.textAlignment&&(s.textAlign=["left","center","right"][this.data.textAlignment])}_setRequired(t,e){e?t.setAttribute("required",!0):t.removeAttribute("required"),t.setAttribute("aria-required",e)}}class ki extends Mi{constructor(t){super(t,{isRenderable:t.renderForms||t.data.hasOwnCanvas||!t.data.hasAppearance&&!!t.data.fieldValue})}setPropertyOnSiblings(t,e,i,s){const n=this.annotationStorage;for(const a of this._getElementsByName(t.name,t.id))a.domElement&&(a.domElement[e]=i),n.setValue(a.id,{[s]:i})}render(){const t=this.annotationStorage,e=this.data.id;this.container.classList.add("textWidgetAnnotation");let i=null;if(this.renderForms){const s=t.getValue(e,{value:this.data.fieldValue});let n=s.value||"";const a=t.getValue(e,{charLimit:this.data.maxLen}).charLimit;a&&n.length>a&&(n=n.slice(0,a));let r=s.formattedValue||this.data.textContent?.join("\n")||null;r&&this.data.comb&&(r=r.replaceAll(/\s+/g,""));const o={userValue:n,formattedValue:r,lastCommittedValue:null,commitKey:1,focused:!1};this.data.multiLine?(i=document.createElement("textarea"),i.textContent=r??n,this.data.doNotScroll&&(i.style.overflowY="hidden")):(i=document.createElement("input"),i.type="text",i.setAttribute("value",r??n),this.data.doNotScroll&&(i.style.overflowX="hidden")),this.data.hasOwnCanvas&&(i.hidden=!0),_i.add(i),i.setAttribute("data-element-id",e),i.disabled=this.data.readOnly,i.name=this.data.fieldName,i.tabIndex=wi,this._setRequired(i,this.data.required),a&&(i.maxLength=a),i.addEventListener("input",(s=>{t.setValue(e,{value:s.target.value}),this.setPropertyOnSiblings(i,"value",s.target.value,"value"),o.formattedValue=null})),i.addEventListener("resetform",(t=>{const e=this.data.defaultFieldValue??"";i.value=o.userValue=e,o.formattedValue=null}));let l=t=>{const{formattedValue:e}=o;null!=e&&(t.target.value=e),t.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){i.addEventListener("focus",(t=>{if(o.focused)return;const{target:e}=t;o.userValue&&(e.value=o.userValue),o.lastCommittedValue=e.value,o.commitKey=1,this.data.actions?.Focus||(o.focused=!0)})),i.addEventListener("updatefromsandbox",(i=>{this.showElementAndHideCanvas(i.target);const s={value(i){o.userValue=i.detail.value??"",t.setValue(e,{value:o.userValue.toString()}),i.target.value=o.userValue},formattedValue(i){const{formattedValue:s}=i.detail;o.formattedValue=s,null!=s&&i.target!==document.activeElement&&(i.target.value=s),t.setValue(e,{formattedValue:s})},selRange(t){t.target.setSelectionRange(...t.detail.selRange)},charLimit:i=>{const{charLimit:s}=i.detail,{target:n}=i;if(0===s)return void n.removeAttribute("maxLength");n.setAttribute("maxLength",s);let a=o.userValue;!a||a.length<=s||(a=a.slice(0,s),n.value=o.userValue=a,t.setValue(e,{value:a}),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:a,willCommit:!0,commitKey:1,selStart:n.selectionStart,selEnd:n.selectionEnd}}))}};this._dispatchEventFromSandbox(s,i)})),i.addEventListener("keydown",(t=>{o.commitKey=1;let i=-1;if("Escape"===t.key?i=0:"Enter"!==t.key||this.data.multiLine?"Tab"===t.key&&(o.commitKey=3):i=2,-1===i)return;const{value:s}=t.target;o.lastCommittedValue!==s&&(o.lastCommittedValue=s,o.userValue=s,this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:s,willCommit:!0,commitKey:i,selStart:t.target.selectionStart,selEnd:t.target.selectionEnd}}))}));const s=l;l=null,i.addEventListener("blur",(t=>{if(!o.focused||!t.relatedTarget)return;this.data.actions?.Blur||(o.focused=!1);const{value:i}=t.target;o.userValue=i,o.lastCommittedValue!==i&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:i,willCommit:!0,commitKey:o.commitKey,selStart:t.target.selectionStart,selEnd:t.target.selectionEnd}}),s(t)})),this.data.actions?.Keystroke&&i.addEventListener("beforeinput",(t=>{o.lastCommittedValue=null;const{data:i,target:s}=t,{value:n,selectionStart:a,selectionEnd:r}=s;let l=a,h=r;switch(t.inputType){case"deleteWordBackward":{const t=n.substring(0,a).match(/\w*[^\w]*$/);t&&(l-=t[0].length);break}case"deleteWordForward":{const t=n.substring(a).match(/^[^\w]*\w*/);t&&(h+=t[0].length);break}case"deleteContentBackward":a===r&&(l-=1);break;case"deleteContentForward":a===r&&(h+=1)}t.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:n,change:i||"",willCommit:!1,selStart:l,selEnd:h}})})),this._setEventListeners(i,o,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(t=>t.target.value))}if(l&&i.addEventListener("blur",l),this.data.comb){const t=(this.data.rect[2]-this.data.rect[0])/a;i.classList.add("comb"),i.style.letterSpacing=`calc(${t}px * var(--scale-factor) - 1ch)`}}else i=document.createElement("div"),i.textContent=this.data.fieldValue,i.style.verticalAlign="middle",i.style.display="table-cell",this.data.hasOwnCanvas&&(i.hidden=!0);return this._setTextStyle(i),this._setBackgroundColor(i),this._setDefaultPropertiesFromJS(i),this.container.append(i),this.container}}class Ii extends Mi{constructor(t){super(t,{isRenderable:!!t.data.hasOwnCanvas})}}class Pi extends Mi{constructor(t){super(t,{isRenderable:t.renderForms})}render(){const t=this.annotationStorage,e=this.data,i=e.id;let s=t.getValue(i,{value:e.exportValue===e.fieldValue}).value;"string"==typeof s&&(s="Off"!==s,t.setValue(i,{value:s})),this.container.classList.add("buttonWidgetAnnotation","checkBox");const n=document.createElement("input");return _i.add(n),n.setAttribute("data-element-id",i),n.disabled=e.readOnly,this._setRequired(n,this.data.required),n.type="checkbox",n.name=e.fieldName,s&&n.setAttribute("checked",!0),n.setAttribute("exportValue",e.exportValue),n.tabIndex=wi,n.addEventListener("change",(s=>{const{name:n,checked:a}=s.target;for(const s of this._getElementsByName(n,i)){const i=a&&s.exportValue===e.exportValue;s.domElement&&(s.domElement.checked=i),t.setValue(s.id,{value:i})}t.setValue(i,{value:a})})),n.addEventListener("resetform",(t=>{const i=e.defaultFieldValue||"Off";t.target.checked=i===e.exportValue})),this.enableScripting&&this.hasJSActions&&(n.addEventListener("updatefromsandbox",(e=>{const s={value(e){e.target.checked="Off"!==e.detail.value,t.setValue(i,{value:e.target.checked})}};this._dispatchEventFromSandbox(s,e)})),this._setEventListeners(n,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(t=>t.target.checked))),this._setBackgroundColor(n),this._setDefaultPropertiesFromJS(n),this.container.append(n),this.container}}class Ri extends Mi{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("buttonWidgetAnnotation","radioButton");const t=this.annotationStorage,e=this.data,i=e.id;let s=t.getValue(i,{value:e.fieldValue===e.buttonValue}).value;if("string"==typeof s&&(s=s!==e.buttonValue,t.setValue(i,{value:s})),s)for(const s of this._getElementsByName(e.fieldName,i))t.setValue(s.id,{value:!1});const n=document.createElement("input");if(_i.add(n),n.setAttribute("data-element-id",i),n.disabled=e.readOnly,this._setRequired(n,this.data.required),n.type="radio",n.name=e.fieldName,s&&n.setAttribute("checked",!0),n.tabIndex=wi,n.addEventListener("change",(e=>{const{name:s,checked:n}=e.target;for(const e of this._getElementsByName(s,i))t.setValue(e.id,{value:!1});t.setValue(i,{value:n})})),n.addEventListener("resetform",(t=>{const i=e.defaultFieldValue;t.target.checked=null!=i&&i===e.buttonValue})),this.enableScripting&&this.hasJSActions){const s=e.buttonValue;n.addEventListener("updatefromsandbox",(e=>{const n={value:e=>{const n=s===e.detail.value;for(const s of this._getElementsByName(e.target.name)){const e=n&&s.id===i;s.domElement&&(s.domElement.checked=e),t.setValue(s.id,{value:e})}}};this._dispatchEventFromSandbox(n,e)})),this._setEventListeners(n,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(t=>t.target.checked))}return this._setBackgroundColor(n),this._setDefaultPropertiesFromJS(n),this.container.append(n),this.container}}class Di extends Si{constructor(t){super(t,{ignoreBorder:t.data.hasAppearance})}render(){const t=super.render();t.classList.add("buttonWidgetAnnotation","pushButton");const e=t.lastChild;return this.enableScripting&&this.hasJSActions&&e&&(this._setDefaultPropertiesFromJS(e),e.addEventListener("updatefromsandbox",(t=>{this._dispatchEventFromSandbox({},t)}))),t}}class Li extends Mi{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("choiceWidgetAnnotation");const t=this.annotationStorage,e=this.data.id,i=t.getValue(e,{value:this.data.fieldValue}),s=document.createElement("select");_i.add(s),s.setAttribute("data-element-id",e),s.disabled=this.data.readOnly,this._setRequired(s,this.data.required),s.name=this.data.fieldName,s.tabIndex=wi;let n=this.data.combo&&this.data.options.length>0;this.data.combo||(s.size=this.data.options.length,this.data.multiSelect&&(s.multiple=!0)),s.addEventListener("resetform",(t=>{const e=this.data.defaultFieldValue;for(const t of s.options)t.selected=t.value===e}));for(const t of this.data.options){const e=document.createElement("option");e.textContent=t.displayValue,e.value=t.exportValue,i.value.includes(t.exportValue)&&(e.setAttribute("selected",!0),n=!1),s.append(e)}let a=null;if(n){const t=document.createElement("option");t.value=" ",t.setAttribute("hidden",!0),t.setAttribute("selected",!0),s.prepend(t),a=()=>{t.remove(),s.removeEventListener("input",a),a=null},s.addEventListener("input",a)}const r=t=>{const e=t?"value":"textContent",{options:i,multiple:n}=s;return n?Array.prototype.filter.call(i,(t=>t.selected)).map((t=>t[e])):-1===i.selectedIndex?null:i[i.selectedIndex][e]};let o=r(!1);const l=t=>{const e=t.target.options;return Array.prototype.map.call(e,(t=>({displayValue:t.textContent,exportValue:t.value})))};return this.enableScripting&&this.hasJSActions?(s.addEventListener("updatefromsandbox",(i=>{const n={value(i){a?.();const n=i.detail.value,l=new Set(Array.isArray(n)?n:[n]);for(const t of s.options)t.selected=l.has(t.value);t.setValue(e,{value:r(!0)}),o=r(!1)},multipleSelection(t){s.multiple=!0},remove(i){const n=s.options,a=i.detail.remove;n[a].selected=!1,s.remove(a),n.length>0&&-1===Array.prototype.findIndex.call(n,(t=>t.selected))&&(n[0].selected=!0),t.setValue(e,{value:r(!0),items:l(i)}),o=r(!1)},clear(i){for(;0!==s.length;)s.remove(0);t.setValue(e,{value:null,items:[]}),o=r(!1)},insert(i){const{index:n,displayValue:a,exportValue:h}=i.detail.insert,d=s.children[n],c=document.createElement("option");c.textContent=a,c.value=h,d?d.before(c):s.append(c),t.setValue(e,{value:r(!0),items:l(i)}),o=r(!1)},items(i){const{items:n}=i.detail;for(;0!==s.length;)s.remove(0);for(const t of n){const{displayValue:e,exportValue:i}=t,n=document.createElement("option");n.textContent=e,n.value=i,s.append(n)}s.options.length>0&&(s.options[0].selected=!0),t.setValue(e,{value:r(!0),items:l(i)}),o=r(!1)},indices(i){const s=new Set(i.detail.indices);for(const t of i.target.options)t.selected=s.has(t.index);t.setValue(e,{value:r(!0)}),o=r(!1)},editable(t){t.target.disabled=!t.detail.editable}};this._dispatchEventFromSandbox(n,i)})),s.addEventListener("input",(i=>{const s=r(!0),n=r(!1);t.setValue(e,{value:s}),i.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:o,change:n,changeEx:s,willCommit:!1,commitKey:1,keyDown:!1}})})),this._setEventListeners(s,null,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"],["input","Action"],["input","Validate"]],(t=>t.target.value))):s.addEventListener("input",(function(i){t.setValue(e,{value:r(!0)})})),this.data.combo&&this._setTextStyle(s),this._setBackgroundColor(s),this._setDefaultPropertiesFromJS(s),this.container.append(s),this.container}}class Fi extends Ei{constructor(t){const{data:e,elements:i}=t;super(t,{isRenderable:Ei._hasPopupData(e)}),this.elements=i,this.popup=null}render(){this.container.classList.add("popupAnnotation");const t=this.popup=new Ni({container:this.container,color:this.data.color,titleObj:this.data.titleObj,modificationDate:this.data.modificationDate,contentsObj:this.data.contentsObj,richText:this.data.richText,rect:this.data.rect,parentRect:this.data.parentRect||null,parent:this.parent,elements:this.elements,open:this.data.open}),e=[];for(const i of this.elements)i.popup=t,e.push(i.data.id),i.addHighlightArea();return this.container.setAttribute("aria-controls",e.map((t=>`${$}${t}`)).join(",")),this.container}}class Ni{#As=this.#ys.bind(this);#ws=this.#_s.bind(this);#xs=this.#Cs.bind(this);#Es=this.#Ss.bind(this);#Ts=null;#ut=null;#Ms=null;#ks=null;#Is=null;#Ps=null;#Rs=null;#Ds=!1;#Ls=null;#S=null;#Fs=null;#Ns=null;#Os=null;#us=null;#Bs=!1;constructor({container:t,color:e,elements:i,titleObj:s,modificationDate:n,contentsObj:a,richText:r,parent:o,rect:l,parentRect:h,open:d}){this.#ut=t,this.#Os=s,this.#Ms=a,this.#Ns=r,this.#Ps=o,this.#Ts=e,this.#Fs=l,this.#Rs=h,this.#Is=i,this.#ks=ut.toDateObject(n),this.trigger=i.flatMap((t=>t.getElementsToTriggerPopup()));for(const t of this.trigger)t.addEventListener("click",this.#Es),t.addEventListener("mouseenter",this.#xs),t.addEventListener("mouseleave",this.#ws),t.classList.add("popupTriggerArea");for(const t of i)t.container?.addEventListener("keydown",this.#As);this.#ut.hidden=!0,d&&this.#Ss()}render(){if(this.#Ls)return;const t=this.#Ls=document.createElement("div");if(t.className="popup",this.#Ts){const e=t.style.outlineColor=z.makeHexColor(...this.#Ts);if(CSS.supports("background-color","color-mix(in srgb, red 30%, white)"))t.style.backgroundColor=`color-mix(in srgb, ${e} 30%, white)`;else{const e=.7;t.style.backgroundColor=z.makeHexColor(...this.#Ts.map((t=>Math.floor(e*(255-t)+t))))}}const e=document.createElement("span");e.className="header";const i=document.createElement("h1");if(e.append(i),({dir:i.dir,str:i.textContent}=this.#Os),t.append(e),this.#ks){const t=document.createElement("span");t.classList.add("popupDate"),t.setAttribute("data-l10n-id","pdfjs-annotation-date-time-string"),t.setAttribute("data-l10n-args",JSON.stringify({dateObj:this.#ks.valueOf()})),e.append(t)}const s=this.#zs;if(s)yi.render({xfaHtml:s,intent:"richText",div:t}),t.lastChild.classList.add("richText","popupContent");else{const e=this._formatContents(this.#Ms);t.append(e)}this.#ut.append(t)}get#zs(){const t=this.#Ns,e=this.#Ms;return!t?.str||e?.str&&e.str!==t.str?null:this.#Ns.html||null}get#Hs(){return this.#zs?.attributes?.style?.fontSize||0}get#js(){return this.#zs?.attributes?.style?.color||null}#Us(t){const e=[],i={str:t,html:{name:"div",attributes:{dir:"auto"},children:[{name:"p",children:e}]}},s={style:{color:this.#js,fontSize:this.#Hs?`calc(${this.#Hs}px * var(--scale-factor))`:""}};for(const i of t.split("\n"))e.push({name:"span",value:i,attributes:s});return i}_formatContents({str:t,dir:e}){const i=document.createElement("p");i.classList.add("popupContent"),i.dir=e;const s=t.split(/(?:\r\n?|\n)/);for(let t=0,e=s.length;t{"Enter"===t.key&&(s?t.metaKey:t.ctrlKey)&&this.#Ys()})),!e.popupRef&&this.hasPopupData?this._createPopup():i.classList.add("popupTriggerArea"),t.append(i),t}getElementsToTriggerPopup(){return this.#Ks}addHighlightArea(){this.container.classList.add("highlightArea")}#Ys(){this.downloadManager?.openOrDownloadData(this.content,this.filename)}}class Qi{#Qs=null;#Js=null;#Zs=new Map;#tn=null;constructor({div:t,accessibilityManager:e,annotationCanvasMap:i,annotationEditorUIManager:s,page:n,viewport:a,structTreeLayer:r}){this.div=t,this.#Qs=e,this.#Js=i,this.#tn=r||null,this.page=n,this.viewport=a,this.zIndex=0,this._annotationEditorUIManager=s}hasEditableAnnotations(){return this.#Zs.size>0}async#en(t,e){const i=t.firstChild||t,s=i.id=`${$}${e}`,n=await(this.#tn?.getAriaAttributes(s));if(n)for(const[t,e]of n)i.setAttribute(t,e);this.div.append(t),this.#Qs?.moveElementInDOM(this.div,t,i,!1)}async render(t){const{annotations:e}=t,i=this.div;bt(i,this.viewport);const s=new Map,n={data:null,layer:i,linkService:t.linkService,downloadManager:t.downloadManager,imageResourcesPath:t.imageResourcesPath||"",renderForms:!1!==t.renderForms,svgFactory:new tt,annotationStorage:t.annotationStorage||new Nt,enableScripting:!0===t.enableScripting,hasJSActions:t.hasJSActions,fieldObjects:t.fieldObjects,parent:this,elements:null};for(const t of e){if(t.noHTML)continue;const e=16===t.annotationType;if(e){const e=s.get(t.id);if(!e)continue;n.elements=e}else{const{width:e,height:i}=xi(t.rect);if(e<=0||i<=0)continue}n.data=t;const i=Ci.create(n);if(!i.isRenderable)continue;if(!e&&t.popupRef){const e=s.get(t.popupRef);e?e.push(i):s.set(t.popupRef,[i])}const a=i.render();t.hidden&&(a.style.visibility="hidden"),await this.#en(a,t.id),i._isEditable&&(this.#Zs.set(i.data.id,i),this._annotationEditorUIManager?.renderAnnotationElement(i))}this.#in()}update({viewport:t}){const e=this.div;this.viewport=t,bt(e,{rotation:t.rotation}),this.#in(),e.hidden=!1}#in(){if(!this.#Js)return;const t=this.div;for(const[e,i]of this.#Js){const s=t.querySelector(`[data-annotation-id="${e}"]`);if(!s)continue;i.className="annotationContent";const{firstChild:n}=s;n?"CANVAS"===n.nodeName?n.replaceWith(i):n.classList.contains("annotationContent")?n.after(i):n.before(i):s.append(i)}this.#Js.clear()}getEditableAnnotations(){return Array.from(this.#Zs.values())}getEditableAnnotation(t){return this.#Zs.get(t)}}const Ji=/\r\n?|\n/g;class Zi extends kt{#Ts;#sn="";#nn=`${this.id}-editor`;#an=null;#Hs;static _freeTextDefaultContent="";static _internalPadding=0;static _defaultColor=null;static _defaultFontSize=10;static get _keyboardManager(){const t=Zi.prototype,e=t=>t.isEmpty(),i=Tt.TRANSLATE_SMALL,s=Tt.TRANSLATE_BIG;return E(this,"_keyboardManager",new Et([[["ctrl+s","mac+meta+s","ctrl+p","mac+meta+p"],t.commitOrRemove,{bubbles:!0}],[["ctrl+Enter","mac+meta+Enter","Escape","mac+Escape"],t.commitOrRemove],[["ArrowLeft","mac+ArrowLeft"],t._translateEmpty,{args:[-i,0],checker:e}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t._translateEmpty,{args:[-s,0],checker:e}],[["ArrowRight","mac+ArrowRight"],t._translateEmpty,{args:[i,0],checker:e}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t._translateEmpty,{args:[s,0],checker:e}],[["ArrowUp","mac+ArrowUp"],t._translateEmpty,{args:[0,-i],checker:e}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t._translateEmpty,{args:[0,-s],checker:e}],[["ArrowDown","mac+ArrowDown"],t._translateEmpty,{args:[0,i],checker:e}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t._translateEmpty,{args:[0,s],checker:e}]]))}static _type="freetext";static _editorType=h.FREETEXT;constructor(t){super({...t,name:"freeTextEditor"}),this.#Ts=t.color||Zi._defaultColor||kt._defaultLineColor,this.#Hs=t.fontSize||Zi._defaultFontSize}static initialize(t,e){kt.initialize(t,e,{strings:["pdfjs-free-text-default-content"]});const i=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(i.getPropertyValue("--freetext-padding"))}static updateDefaultParams(t,e){switch(t){case d.FREETEXT_SIZE:Zi._defaultFontSize=e;break;case d.FREETEXT_COLOR:Zi._defaultColor=e}}updateParams(t,e){switch(t){case d.FREETEXT_SIZE:this.#rn(e);break;case d.FREETEXT_COLOR:this.#on(e)}}static get defaultPropertiesToUpdate(){return[[d.FREETEXT_SIZE,Zi._defaultFontSize],[d.FREETEXT_COLOR,Zi._defaultColor||kt._defaultLineColor]]}get propertiesToUpdate(){return[[d.FREETEXT_SIZE,this.#Hs],[d.FREETEXT_COLOR,this.#Ts]]}#rn(t){const e=t=>{this.editorDiv.style.fontSize=`calc(${t}px * var(--scale-factor))`,this.translate(0,-(t-this.#Hs)*this.parentScale),this.#Hs=t,this.#ln()},i=this.#Hs;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:d.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})}#on(t){const e=t=>{this.#Ts=this.editorDiv.style.color=t},i=this.#Ts;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:d.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})}_translateEmpty(t,e){this._uiManager.translateSelectedEditors(t,e,!0)}getInitialTranslation(){const t=this.parentScale;return[-Zi._internalPadding*t,-(Zi._internalPadding+this.#Hs)*t]}rebuild(){this.parent&&(super.rebuild(),null!==this.div&&(this.isAttachedToDOM||this.parent.add(this)))}enableEditMode(){if(this.isInEditMode())return;this.parent.setEditingState(!1),this.parent.updateToolbar(h.FREETEXT),super.enableEditMode(),this.overlayDiv.classList.remove("enabled"),this.editorDiv.contentEditable=!0,this._isDraggable=!1,this.div.removeAttribute("aria-activedescendant"),this.#an=new AbortController;const t=this._uiManager.combinedSignal(this.#an);this.editorDiv.addEventListener("keydown",this.editorDivKeydown.bind(this),{signal:t}),this.editorDiv.addEventListener("focus",this.editorDivFocus.bind(this),{signal:t}),this.editorDiv.addEventListener("blur",this.editorDivBlur.bind(this),{signal:t}),this.editorDiv.addEventListener("input",this.editorDivInput.bind(this),{signal:t}),this.editorDiv.addEventListener("paste",this.editorDivPaste.bind(this),{signal:t})}disableEditMode(){this.isInEditMode()&&(this.parent.setEditingState(!0),super.disableEditMode(),this.overlayDiv.classList.add("enabled"),this.editorDiv.contentEditable=!1,this.div.setAttribute("aria-activedescendant",this.#nn),this._isDraggable=!0,this.#an?.abort(),this.#an=null,this.div.focus({preventScroll:!0}),this.isEditing=!1,this.parent.div.classList.add("freetextEditing"))}focusin(t){this._focusEventsAllowed&&(super.focusin(t),t.target!==this.editorDiv&&this.editorDiv.focus())}onceAdded(){this.width||(this.enableEditMode(),this.editorDiv.focus(),this._initialOptions?.isCentered&&this.center(),this._initialOptions=null)}isEmpty(){return!this.editorDiv||""===this.editorDiv.innerText.trim()}remove(){this.isEditing=!1,this.parent&&(this.parent.setEditingState(!0),this.parent.div.classList.add("freetextEditing")),super.remove()}#hn(){const t=[];this.editorDiv.normalize();let e=null;for(const i of this.editorDiv.childNodes)e?.nodeType===Node.TEXT_NODE&&"BR"===i.nodeName||(t.push(Zi.#dn(i)),e=i);return t.join("\n")}#ln(){const[t,e]=this.parentDimensions;let i;if(this.isAttachedToDOM)i=this.div.getBoundingClientRect();else{const{currentLayer:t,div:e}=this,s=e.style.display,n=e.classList.contains("hidden");e.classList.remove("hidden"),e.style.display="hidden",t.div.append(this.div),i=e.getBoundingClientRect(),e.remove(),e.style.display=s,e.classList.toggle("hidden",n)}this.rotation%180==this.parentRotation%180?(this.width=i.width/t,this.height=i.height/e):(this.width=i.height/t,this.height=i.width/e),this.fixAndSetPosition()}commit(){if(!this.isInEditMode())return;super.commit(),this.disableEditMode();const t=this.#sn,e=this.#sn=this.#hn().trimEnd();if(t===e)return;const i=t=>{this.#sn=t,t?(this.#cn(),this._uiManager.rebuild(this),this.#ln()):this.remove()};this.addCommands({cmd:()=>{i(e)},undo:()=>{i(t)},mustExec:!1}),this.#ln()}shouldGetKeyboardEvents(){return this.isInEditMode()}enterInEditMode(){this.enableEditMode(),this.editorDiv.focus()}dblclick(t){this.enterInEditMode()}keydown(t){t.target===this.div&&"Enter"===t.key&&(this.enterInEditMode(),t.preventDefault())}editorDivKeydown(t){Zi._keyboardManager.exec(this,t)}editorDivFocus(t){this.isEditing=!0}editorDivBlur(t){this.isEditing=!1}editorDivInput(t){this.parent.div.classList.toggle("freetextEditing",this.isEmpty())}disableEditing(){this.editorDiv.setAttribute("role","comment"),this.editorDiv.removeAttribute("aria-multiline")}enableEditing(){this.editorDiv.setAttribute("role","textbox"),this.editorDiv.setAttribute("aria-multiline",!0)}render(){if(this.div)return this.div;let t,e;this.width&&(t=this.x,e=this.y),super.render(),this.editorDiv=document.createElement("div"),this.editorDiv.className="internal",this.editorDiv.setAttribute("id",this.#nn),this.editorDiv.setAttribute("data-l10n-id","pdfjs-free-text"),this.enableEditing(),kt._l10nPromise.get("pdfjs-free-text-default-content").then((t=>this.editorDiv?.setAttribute("default-content",t))),this.editorDiv.contentEditable=!0;const{style:i}=this.editorDiv;if(i.fontSize=`calc(${this.#Hs}px * var(--scale-factor))`,i.color=this.#Ts,this.div.append(this.editorDiv),this.overlayDiv=document.createElement("div"),this.overlayDiv.classList.add("overlay","enabled"),this.div.append(this.overlayDiv),wt(this,this.div,["dblclick","keydown"]),this.width){const[i,s]=this.parentDimensions;if(this.annotationElementId){const{position:n}=this._initialData;let[a,r]=this.getInitialTranslation();[a,r]=this.pageTranslationToScreen(a,r);const[o,l]=this.pageDimensions,[h,d]=this.pageTranslation;let c,u;switch(this.rotation){case 0:c=t+(n[0]-h)/o,u=e+this.height-(n[1]-d)/l;break;case 90:c=t+(n[0]-h)/o,u=e-(n[1]-d)/l,[a,r]=[r,-a];break;case 180:c=t-this.width+(n[0]-h)/o,u=e-(n[1]-d)/l,[a,r]=[-a,-r];break;case 270:c=t+(n[0]-h-this.height*l)/o,u=e+(n[1]-d-this.width*o)/l,[a,r]=[-r,a]}this.setAt(c*i,u*s,a,r)}else this.setAt(t*i,e*s,this.width*i,this.height*s);this.#cn(),this._isDraggable=!0,this.editorDiv.contentEditable=!1}else this._isDraggable=!1,this.editorDiv.contentEditable=!0;return this.div}static#dn(t){return(t.nodeType===Node.TEXT_NODE?t.nodeValue:t.innerText).replaceAll(Ji,"")}editorDivPaste(t){const e=t.clipboardData||window.clipboardData,{types:i}=e;if(1===i.length&&"text/plain"===i[0])return;t.preventDefault();const s=Zi.#un(e.getData("text")||"").replaceAll(Ji,"\n");if(!s)return;const n=window.getSelection();if(!n.rangeCount)return;this.editorDiv.normalize(),n.deleteFromDocument();const a=n.getRangeAt(0);if(!s.includes("\n"))return a.insertNode(document.createTextNode(s)),this.editorDiv.normalize(),void n.collapseToStart();const{startContainer:r,startOffset:o}=a,l=[],h=[];if(r.nodeType===Node.TEXT_NODE){const t=r.parentElement;if(h.push(r.nodeValue.slice(o).replaceAll(Ji,"")),t!==this.editorDiv){let e=l;for(const i of this.editorDiv.childNodes)i!==t?e.push(Zi.#dn(i)):e=h}l.push(r.nodeValue.slice(0,o).replaceAll(Ji,""))}else if(r===this.editorDiv){let t=l,e=0;for(const i of this.editorDiv.childNodes)e++===o&&(t=h),t.push(Zi.#dn(i))}this.#sn=`${l.join("\n")}${s}${h.join("\n")}`,this.#cn();const d=new Range;let c=l.reduce(((t,e)=>t+e.length),0);for(const{firstChild:t}of this.editorDiv.childNodes)if(t.nodeType===Node.TEXT_NODE){const e=t.nodeValue.length;if(c<=e){d.setStart(t,c),d.setEnd(t,c);break}c-=e}n.removeAllRanges(),n.addRange(d)}#cn(){if(this.editorDiv.replaceChildren(),this.#sn)for(const t of this.#sn.split("\n")){const e=document.createElement("div");e.append(t?document.createTextNode(t):document.createElement("br")),this.editorDiv.append(e)}}#pn(){return this.#sn.replaceAll(" "," ")}static#un(t){return t.replaceAll(" "," ")}get contentDiv(){return this.editorDiv}static async deserialize(t,e,i){let s=null;if(t instanceof Oi){const{data:{defaultAppearanceData:{fontSize:e,fontColor:i},rect:n,rotation:a,id:r,popupRef:o},textContent:l,textPosition:d,parent:{page:{pageNumber:c}}}=t;if(!l||0===l.length)return null;s=t={annotationType:h.FREETEXT,color:Array.from(i),fontSize:e,value:l.join("\n"),position:d,pageIndex:c-1,rect:n.slice(0),rotation:a,id:r,deleted:!1,popupRef:o}}const n=await super.deserialize(t,e,i);return n.#Hs=t.fontSize,n.#Ts=z.makeHexColor(...t.color),n.#sn=Zi.#un(t.value),n.annotationElementId=t.id||null,n._initialData=s,n}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const e=Zi._internalPadding*this.parentScale,i=this.getRect(e,e),s=kt._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:this.#Ts),n={annotationType:h.FREETEXT,color:s,fontSize:this.#Hs,value:this.#pn(),pageIndex:this.pageIndex,rect:i,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return t?n:this.annotationElementId&&!this.#gn(n)?null:(n.id=this.annotationElementId,n)}#gn(t){const{value:e,fontSize:i,color:s,pageIndex:n}=this._initialData;return this._hasBeenMoved||t.value!==e||t.fontSize!==i||t.color.some(((t,e)=>t!==s[e]))||t.pageIndex!==n}renderAnnotationElement(t){const e=super.renderAnnotationElement(t);if(this.deleted)return e;const{style:i}=e;i.fontSize=`calc(${this.#Hs}px * var(--scale-factor))`,i.color=this.#Ts,e.replaceChildren();for(const t of this.#sn.split("\n")){const i=document.createElement("div");i.append(t?document.createTextNode(t):document.createElement("br")),e.append(i)}const s=Zi._internalPadding*this.parentScale;return t.updateEdited({rect:this.getRect(s,s),popupContent:this.#sn}),e}resetAnnotationElement(t){super.resetAnnotationElement(t),t.resetEdited()}}class ts{#mn;#fn=[];#bn=[];constructor(t,e=0,i=0,s=!0){let n=1/0,a=-1/0,r=1/0,o=-1/0;const l=10**-4;for(const{x:i,y:s,width:h,height:d}of t){const t=Math.floor((i-e)/l)*l,c=Math.ceil((i+h+e)/l)*l,u=Math.floor((s-e)/l)*l,p=Math.ceil((s+d+e)/l)*l,g=[t,u,p,!0],m=[c,u,p,!1];this.#fn.push(g,m),n=Math.min(n,t),a=Math.max(a,c),r=Math.min(r,u),o=Math.max(o,p)}const h=a-n+2*i,d=o-r+2*i,c=n-i,u=r-i,p=this.#fn.at(s?-1:-2),g=[p[0],p[2]];for(const t of this.#fn){const[e,i,s]=t;t[0]=(e-c)/h,t[1]=(i-u)/d,t[2]=(s-u)/d}this.#mn={x:c,y:u,width:h,height:d,lastPoint:g}}getOutlines(){this.#fn.sort(((t,e)=>t[0]-e[0]||t[1]-e[1]||t[2]-e[2]));const t=[];for(const e of this.#fn)e[3]?(t.push(...this.#vn(e)),this.#An(e)):(this.#yn(e),t.push(...this.#vn(e)));return this.#wn(t)}#wn(t){const e=[],i=new Set;for(const i of t){const[t,s,n]=i;e.push([t,s,i],[t,n,i])}e.sort(((t,e)=>t[1]-e[1]||t[0]-e[0]));for(let t=0,s=e.length;t0;){const t=i.values().next().value;let[e,a,r,o,l]=t;i.delete(t);let h=e,d=a;for(n=[e,r],s.push(n);;){let t;if(i.has(o))t=o;else{if(!i.has(l))break;t=l}i.delete(t),[e,a,r,o,l]=t,h!==e&&(n.push(h,d,e,d===a?a:r),h=e),d=d===a?r:a}n.push(h,d)}return new is(s,this.#mn)}#_n(t){const e=this.#bn;let i=0,s=e.length-1;for(;i<=s;){const n=i+s>>1,a=e[n][0];if(a===t)return n;a=0;s--){const[i,n]=this.#bn[s];if(i!==t)break;if(i===t&&n===e)return void this.#bn.splice(s,1)}}#vn(t){const[e,i,s]=t,n=[[e,i,s]],a=this.#_n(s);for(let t=0;t=i)if(o>s)n[t][1]=s;else{if(1===a)return[];n.splice(t,1),t--,a--}else n[t][2]=i,o>s&&n.push([e,s,o])}}return n}}class es{toSVGPath(){throw new Error("Abstract method `toSVGPath` must be implemented.")}get box(){throw new Error("Abstract getter `box` must be implemented.")}serialize(t,e){throw new Error("Abstract method `serialize` must be implemented.")}get free(){return this instanceof ns}}class is extends es{#mn;#xn;constructor(t,e){super(),this.#xn=t,this.#mn=e}toSVGPath(){const t=[];for(const e of this.#xn){let[i,s]=e;t.push(`M${i} ${s}`);for(let n=2;n=6;t-=6)isNaN(e[t])?u.push(`L${e[t+4]} ${e[t+5]}`):u.push(`C${e[t]} ${e[t+1]} ${e[t+2]} ${e[t+3]} ${e[t+4]} ${e[t+5]}`);return u.push(`L${e[4]} ${e[5]} Z`),u.join(" ")}getOutlines(){const t=this.#Tn,e=this.#Cn,i=this.#Mn,s=i.subarray(4,6),n=i.subarray(16,18),[a,r,o,l]=this.#mn,h=new Float64Array((this.#Fn?.length??0)+2);for(let t=0,e=h.length-2;t=6;t-=6)for(let i=0;i<6;i+=2)isNaN(e[t+i])?(g[m]=g[m+1]=NaN,m+=2):(g[m]=e[t+i],g[m+1]=e[t+i+1],m+=2);return g.set([NaN,NaN,NaN,NaN,e[4],e[5]],m),new ns(g,h,this.#mn,this.#Dn,this.#En,this.#Sn)}}class ns extends es{#mn;#Hn=null;#En;#Sn;#Fn;#Dn;#jn;constructor(t,e,i,s,n,a){super(),this.#jn=t,this.#Fn=e,this.#mn=i,this.#Dn=s,this.#En=n,this.#Sn=a,this.#Un(a);const{x:r,y:o,width:l,height:h}=this.#Hn;for(let e=0,i=t.length;e-1?(this.#ga=!0,this.#ya(t),this.#wa()):this.#oa&&(this.#aa=t.anchorNode,this.#ra=t.anchorOffset,this.#da=t.focusNode,this.#ca=t.focusOffset,this.#_a(),this.#wa(),this.rotate(this.rotation))}get telemetryInitialData(){return{action:"added",type:this.#ga?"free_highlight":"highlight",color:this._uiManager.highlightColorNames.get(this.color),thickness:this.#Ln,methodOfCreation:this.#Aa}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.highlightColorNames.get(this.color)}}static computeTelemetryFinalData(t){return{numberOfColors:t.get("color").size}}#_a(){const t=new ts(this.#oa,.001);this.#pa=t.getOutlines(),({x:this.x,y:this.y,width:this.width,height:this.height}=this.#pa.box);const e=new ts(this.#oa,.0025,.001,"ltr"===this._uiManager.direction);this.#ha=e.getOutlines();const{lastPoint:i}=this.#ha.box;this.#ma=[(i[0]-this.x)/this.width,(i[1]-this.y)/this.height]}#ya({highlightOutlines:t,highlightId:e,clipPathId:i}){if(this.#pa=t,this.#ha=t.getNewOutline(this.#Ln/2+1.5,.0025),e>=0)this.#A=e,this.#la=i,this.parent.drawLayer.finalizeLine(e,t),this.#ba=this.parent.drawLayer.highlightOutline(this.#ha);else if(this.parent){const e=this.parent.viewport.rotation;this.parent.drawLayer.updateLine(this.#A,t),this.parent.drawLayer.updateBox(this.#A,rs.#xa(this.#pa.box,(e-this.rotation+360)%360)),this.parent.drawLayer.updateLine(this.#ba,this.#ha),this.parent.drawLayer.updateBox(this.#ba,rs.#xa(this.#ha.box,e))}const{x:s,y:n,width:a,height:r}=t.box;switch(this.rotation){case 0:this.x=s,this.y=n,this.width=a,this.height=r;break;case 90:{const[t,e]=this.parentDimensions;this.x=n,this.y=1-s,this.width=a*e/t,this.height=r*t/e;break}case 180:this.x=1-s,this.y=1-n,this.width=a,this.height=r;break;case 270:{const[t,e]=this.parentDimensions;this.x=1-n,this.y=s,this.width=a*e/t,this.height=r*t/e;break}}const{lastPoint:o}=this.#ha.box;this.#ma=[(o[0]-s)/a,(o[1]-n)/r]}static initialize(t,e){kt.initialize(t,e),rs._defaultColor||=e.highlightColors?.values().next().value||"#fff066"}static updateDefaultParams(t,e){switch(t){case d.HIGHLIGHT_DEFAULT_COLOR:rs._defaultColor=e;break;case d.HIGHLIGHT_THICKNESS:rs._defaultThickness=e}}translateInPage(t,e){}get toolbarPosition(){return this.#ma}updateParams(t,e){switch(t){case d.HIGHLIGHT_COLOR:this.#on(e);break;case d.HIGHLIGHT_THICKNESS:this.#Ca(e)}}static get defaultPropertiesToUpdate(){return[[d.HIGHLIGHT_DEFAULT_COLOR,rs._defaultColor],[d.HIGHLIGHT_THICKNESS,rs._defaultThickness]]}get propertiesToUpdate(){return[[d.HIGHLIGHT_COLOR,this.color||rs._defaultColor],[d.HIGHLIGHT_THICKNESS,this.#Ln||rs._defaultThickness],[d.HIGHLIGHT_FREE,this.#ga]]}#on(t){const e=(t,e)=>{this.color=t,this.parent?.drawLayer.changeColor(this.#A,t),this.#n?.updateColor(t),this.#fa=e,this.parent?.drawLayer.changeOpacity(this.#A,e)},i=this.color,s=this.#fa;this.addCommands({cmd:e.bind(this,t,rs._defaultOpacity),undo:e.bind(this,i,s),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:d.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"color_changed",color:this._uiManager.highlightColorNames.get(t)},!0)}#Ca(t){const e=this.#Ln,i=t=>{this.#Ln=t,this.#Ea(t)};this.addCommands({cmd:i.bind(this,t),undo:i.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:d.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"thickness_changed",thickness:t},!0)}async addEditToolbar(){const t=await super.addEditToolbar();return t?(this._uiManager.highlightColors&&(this.#n=new as({editor:this}),t.addColorPicker(this.#n)),t):null}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(this.#Sa())}getBaseTranslation(){return[0,0]}getRect(t,e){return super.getRect(t,e,this.#Sa())}onceAdded(){this.annotationElementId||this.parent.addUndoableEditor(this),this.div.focus()}remove(){this.#Ta(),this._reportTelemetry({action:"deleted"}),super.remove()}rebuild(){this.parent&&(super.rebuild(),null!==this.div&&(this.#wa(),this.isAttachedToDOM||this.parent.add(this)))}setParent(t){let e=!1;this.parent&&!t?this.#Ta():t&&(this.#wa(t),e=!this.parent&&this.div?.classList.contains("selectedEditor")),super.setParent(t),this.show(this._isVisible),e&&this.select()}#Ea(t){if(!this.#ga)return;this.#ya({highlightOutlines:this.#pa.getNewOutline(t/2)}),this.fixAndSetPosition();const[e,i]=this.parentDimensions;this.setDims(this.width*e,this.height*i)}#Ta(){null!==this.#A&&this.parent&&(this.parent.drawLayer.remove(this.#A),this.#A=null,this.parent.drawLayer.remove(this.#ba),this.#ba=null)}#wa(t=this.parent){null===this.#A&&(({id:this.#A,clipPathId:this.#la}=t.drawLayer.highlight(this.#pa,this.color,this.#fa)),this.#ba=t.drawLayer.highlightOutline(this.#ha),this.#ua&&(this.#ua.style.clipPath=this.#la))}static#xa({x:t,y:e,width:i,height:s},n){switch(n){case 90:return{x:1-e-s,y:t,width:s,height:i};case 180:return{x:1-t-i,y:1-e-s,width:i,height:s};case 270:return{x:e,y:1-t-i,width:s,height:i}}return{x:t,y:e,width:i,height:s}}rotate(t){const{drawLayer:e}=this.parent;let i;this.#ga?(t=(t-this.rotation+360)%360,i=rs.#xa(this.#pa.box,t)):i=rs.#xa(this,t),e.rotate(this.#A,t),e.rotate(this.#ba,t),e.updateBox(this.#A,i),e.updateBox(this.#ba,rs.#xa(this.#ha.box,t))}render(){if(this.div)return this.div;const t=super.render();this.#va&&(t.setAttribute("aria-label",this.#va),t.setAttribute("role","mark")),this.#ga?t.classList.add("free"):this.div.addEventListener("keydown",this.#Ma.bind(this),{signal:this._uiManager._signal});const e=this.#ua=document.createElement("div");t.append(e),e.setAttribute("aria-hidden","true"),e.className="internal",e.style.clipPath=this.#la;const[i,s]=this.parentDimensions;return this.setDims(this.width*i,this.height*s),wt(this,this.#ua,["pointerover","pointerleave"]),this.enableEditing(),t}pointerover(){this.parent.drawLayer.addClass(this.#ba,"hovered")}pointerleave(){this.parent.drawLayer.removeClass(this.#ba,"hovered")}#Ma(t){rs._keyboardManager.exec(this,t)}_moveCaret(t){switch(this.parent.unselect(this),t){case 0:case 2:this.#ka(!0);break;case 1:case 3:this.#ka(!1)}}#ka(t){if(!this.#aa)return;const e=window.getSelection();t?e.setPosition(this.#aa,this.#ra):e.setPosition(this.#da,this.#ca)}select(){super.select(),this.#ba&&(this.parent?.drawLayer.removeClass(this.#ba,"hovered"),this.parent?.drawLayer.addClass(this.#ba,"selected"))}unselect(){super.unselect(),this.#ba&&(this.parent?.drawLayer.removeClass(this.#ba,"selected"),this.#ga||this.#ka(!1))}get _mustFixPosition(){return!this.#ga}show(t=this._isVisible){super.show(t),this.parent&&(this.parent.drawLayer.show(this.#A,t),this.parent.drawLayer.show(this.#ba,t))}#Sa(){return this.#ga?this.rotation:0}#Ia(){if(this.#ga)return null;const[t,e]=this.pageDimensions,[i,s]=this.pageTranslation,n=this.#oa,a=new Float32Array(8*n.length);let r=0;for(const{x:o,y:l,width:h,height:d}of n){const n=o*t+i,c=(1-l-d)*e+s;a[r]=a[r+4]=n,a[r+1]=a[r+3]=c,a[r+2]=a[r+6]=n+h*t,a[r+5]=a[r+7]=c+d*e,r+=8}return a}#Pa(t){return this.#pa.serialize(t,this.#Sa())}static startHighlighting(t,e,{target:i,x:s,y:n}){const{x:a,y:r,width:o,height:l}=i.getBoundingClientRect(),h=new AbortController,d=t.combinedSignal(h),c=e=>{h.abort(),this.#Ra(t,e)};window.addEventListener("blur",c,{signal:d}),window.addEventListener("pointerup",c,{signal:d}),window.addEventListener("pointerdown",(t=>{t.preventDefault(),t.stopPropagation()}),{capture:!0,passive:!1,signal:d}),window.addEventListener("contextmenu",ht,{signal:d}),i.addEventListener("pointermove",this.#Da.bind(this,t),{signal:d}),this._freeHighlight=new ss({x:s,y:n},[a,r,o,l],t.scale,this._defaultThickness/2,e,.001),({id:this._freeHighlightId,clipPathId:this._freeHighlightClipId}=t.drawLayer.highlight(this._freeHighlight,this._defaultColor,this._defaultOpacity,!0))}static#Da(t,e){this._freeHighlight.add(e)&&t.drawLayer.updatePath(this._freeHighlightId,this._freeHighlight)}static#Ra(t,e){this._freeHighlight.isEmpty()?t.drawLayer.removeFreeHighlight(this._freeHighlightId):t.createAndAddNewEditor(e,!1,{highlightId:this._freeHighlightId,highlightOutlines:this._freeHighlight.getOutlines(),clipPathId:this._freeHighlightClipId,methodOfCreation:"main_toolbar"}),this._freeHighlightId=-1,this._freeHighlight=null,this._freeHighlightClipId=""}static async deserialize(t,e,i){let s=null;if(t instanceof Gi){const{data:{quadPoints:e,rect:i,rotation:n,id:a,color:r,opacity:o,popupRef:l},parent:{page:{pageNumber:d}}}=t;s=t={annotationType:h.HIGHLIGHT,color:Array.from(r),opacity:o,quadPoints:e,boxes:null,pageIndex:d-1,rect:i.slice(0),rotation:n,id:a,deleted:!1,popupRef:l}}else if(t instanceof Wi){const{data:{inkLists:e,rect:i,rotation:n,id:a,color:r,borderStyle:{rawWidth:o},popupRef:l},parent:{page:{pageNumber:d}}}=t;s=t={annotationType:h.HIGHLIGHT,color:Array.from(r),thickness:o,inkLists:e,boxes:null,pageIndex:d-1,rect:i.slice(0),rotation:n,id:a,deleted:!1,popupRef:l}}const{color:n,quadPoints:a,inkLists:r,opacity:o}=t,l=await super.deserialize(t,e,i);l.color=z.makeHexColor(...n),l.#fa=o||1,r&&(l.#Ln=t.thickness),l.annotationElementId=t.id||null,l._initialData=s;const[d,c]=l.pageDimensions,[u,p]=l.pageTranslation;if(a){const t=l.#oa=[];for(let e=0;et!==e[i]))}renderAnnotationElement(t){return t.updateEdited({rect:this.getRect(0,0)}),null}static canCreateNewEmptyEditor(){return!1}}class os extends kt{#La=0;#Fa=0;#Na=null;#Oa=new Path2D;#Ba=!1;#za=null;#Ha=!1;#ja=!1;#Ua=null;#$a=null;#Wa=0;#Ga=0;#Va=null;static _defaultColor=null;static _defaultOpacity=1;static _defaultThickness=1;static _type="ink";static _editorType=h.INK;constructor(t){super({...t,name:"inkEditor"}),this.color=t.color||null,this.thickness=t.thickness||null,this.opacity=t.opacity||null,this.paths=[],this.bezierPath2D=[],this.allRawPaths=[],this.currentPath=[],this.scaleFactor=1,this.translationX=this.translationY=0,this.x=0,this.y=0,this._willKeepAspectRatio=!0}static initialize(t,e){kt.initialize(t,e)}static updateDefaultParams(t,e){switch(t){case d.INK_THICKNESS:os._defaultThickness=e;break;case d.INK_COLOR:os._defaultColor=e;break;case d.INK_OPACITY:os._defaultOpacity=e/100}}updateParams(t,e){switch(t){case d.INK_THICKNESS:this.#Ca(e);break;case d.INK_COLOR:this.#on(e);break;case d.INK_OPACITY:this.#qa(e)}}static get defaultPropertiesToUpdate(){return[[d.INK_THICKNESS,os._defaultThickness],[d.INK_COLOR,os._defaultColor||kt._defaultLineColor],[d.INK_OPACITY,Math.round(100*os._defaultOpacity)]]}get propertiesToUpdate(){return[[d.INK_THICKNESS,this.thickness||os._defaultThickness],[d.INK_COLOR,this.color||os._defaultColor||kt._defaultLineColor],[d.INK_OPACITY,Math.round(100*(this.opacity??os._defaultOpacity))]]}#Ca(t){const e=t=>{this.thickness=t,this.#Xa()},i=this.thickness;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:d.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0})}#on(t){const e=t=>{this.color=t,this.#Ka()},i=this.color;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:d.INK_COLOR,overwriteIfSameType:!0,keepUndo:!0})}#qa(t){const e=t=>{this.opacity=t,this.#Ka()};t/=100;const i=this.opacity;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:d.INK_OPACITY,overwriteIfSameType:!0,keepUndo:!0})}rebuild(){this.parent&&(super.rebuild(),null!==this.div&&(this.canvas||(this.#Ya(),this.#Qa()),this.isAttachedToDOM||(this.parent.add(this),this.#Ja()),this.#Xa()))}remove(){null!==this.canvas&&(this.isEmpty()||this.commit(),this.canvas.width=this.canvas.height=0,this.canvas.remove(),this.canvas=null,this.#Na&&(clearTimeout(this.#Na),this.#Na=null),this.#Ua?.disconnect(),this.#Ua=null,super.remove())}setParent(t){!this.parent&&t?this._uiManager.removeShouldRescale(this):this.parent&&null===t&&this._uiManager.addShouldRescale(this),super.setParent(t)}onScaleChanging(){const[t,e]=this.parentDimensions,i=this.width*t,s=this.height*e;this.setDimensions(i,s)}enableEditMode(){this.#Ba||null===this.canvas||(super.enableEditMode(),this._isDraggable=!1,this.#Za())}disableEditMode(){this.isInEditMode()&&null!==this.canvas&&(super.disableEditMode(),this._isDraggable=!this.isEmpty(),this.div.classList.remove("editing"),this.#tr())}onceAdded(){this._isDraggable=!this.isEmpty()}isEmpty(){return 0===this.paths.length||1===this.paths.length&&0===this.paths[0].length}#er(){const{parentRotation:t,parentDimensions:[e,i]}=this;switch(t){case 90:return[0,i,i,e];case 180:return[e,i,e,i];case 270:return[e,0,i,e];default:return[0,0,e,i]}}#ir(){const{ctx:t,color:e,opacity:i,thickness:s,parentScale:n,scaleFactor:a}=this;t.lineWidth=s*n/a,t.lineCap="round",t.lineJoin="round",t.miterLimit=10,t.strokeStyle=`${e}${function(t){return Math.round(Math.min(255,Math.max(1,255*t))).toString(16).padStart(2,"0")}(i)}`}#sr(t,e){this.canvas.addEventListener("contextmenu",ht,{signal:this._uiManager._signal}),this.#tr(),this.#za=new AbortController;const i=this._uiManager.combinedSignal(this.#za);this.canvas.addEventListener("pointerleave",this.canvasPointerleave.bind(this),{signal:i}),this.canvas.addEventListener("pointermove",this.canvasPointermove.bind(this),{signal:i}),this.canvas.addEventListener("pointerup",this.canvasPointerup.bind(this),{signal:i}),this.isEditing=!0,this.#ja||(this.#ja=!0,this.#Ja(),this.thickness||=os._defaultThickness,this.color||=os._defaultColor||kt._defaultLineColor,this.opacity??=os._defaultOpacity),this.currentPath.push([t,e]),this.#Ha=!1,this.#ir(),this.#Va=()=>{this.#nr(),this.#Va&&window.requestAnimationFrame(this.#Va)},window.requestAnimationFrame(this.#Va)}#ar(t,e){const[i,s]=this.currentPath.at(-1);if(this.currentPath.length>1&&t===i&&e===s)return;const n=this.currentPath;let a=this.#Oa;if(n.push([t,e]),this.#Ha=!0,n.length<=2)return a.moveTo(...n[0]),void a.lineTo(t,e);3===n.length&&(this.#Oa=a=new Path2D,a.moveTo(...n[0])),this.#rr(a,...n.at(-3),...n.at(-2),t,e)}#or(){if(0===this.currentPath.length)return;const t=this.currentPath.at(-1);this.#Oa.lineTo(...t)}#lr(t,e){let i;if(this.#Va=null,t=Math.min(Math.max(t,0),this.canvas.width),e=Math.min(Math.max(e,0),this.canvas.height),this.#ar(t,e),this.#or(),1!==this.currentPath.length)i=this.#hr();else{const s=[t,e];i=[[s,s.slice(),s.slice(),s]]}const s=this.#Oa,n=this.currentPath;this.currentPath=[],this.#Oa=new Path2D,this.addCommands({cmd:()=>{this.allRawPaths.push(n),this.paths.push(i),this.bezierPath2D.push(s),this._uiManager.rebuild(this)},undo:()=>{this.allRawPaths.pop(),this.paths.pop(),this.bezierPath2D.pop(),0===this.paths.length?this.remove():(this.canvas||(this.#Ya(),this.#Qa()),this.#Xa())},mustExec:!0})}#nr(){if(!this.#Ha)return;this.#Ha=!1;Math.ceil(this.thickness*this.parentScale);const t=this.currentPath.slice(-3),e=t.map((t=>t[0])),i=t.map((t=>t[1])),{ctx:s}=(Math.min(...e),Math.max(...e),Math.min(...i),Math.max(...i),this);s.save(),s.clearRect(0,0,this.canvas.width,this.canvas.height);for(const t of this.bezierPath2D)s.stroke(t);s.stroke(this.#Oa),s.restore()}#rr(t,e,i,s,n,a,r){const o=(e+s)/2,l=(i+n)/2,h=(s+a)/2,d=(n+r)/2;t.bezierCurveTo(o+2*(s-o)/3,l+2*(n-l)/3,h+2*(s-h)/3,d+2*(n-d)/3,h,d)}#hr(){const t=this.currentPath;if(t.length<=2)return[[t[0],t[0],t.at(-1),t.at(-1)]];const e=[];let i,[s,n]=t[0];for(i=1;i{this.#Na=null,this.canvas.removeEventListener("contextmenu",ht)}),10),this.#lr(t.offsetX,t.offsetY),this.addToAnnotationStorage(),this.setInBackground()}#Ya(){this.canvas=document.createElement("canvas"),this.canvas.width=this.canvas.height=0,this.canvas.className="inkEditorCanvas",this.canvas.setAttribute("data-l10n-id","pdfjs-ink-canvas"),this.div.append(this.canvas),this.ctx=this.canvas.getContext("2d")}#Qa(){this.#Ua=new ResizeObserver((t=>{const e=t[0].contentRect;e.width&&e.height&&this.setDimensions(e.width,e.height)})),this.#Ua.observe(this.div),this._uiManager._signal.addEventListener("abort",(()=>{this.#Ua?.disconnect(),this.#Ua=null}),{once:!0})}get isResizable(){return!this.isEmpty()&&this.#Ba}render(){if(this.div)return this.div;let t,e;this.width&&(t=this.x,e=this.y),super.render(),this.div.setAttribute("data-l10n-id","pdfjs-ink");const[i,s,n,a]=this.#er();if(this.setAt(i,s,0,0),this.setDims(n,a),this.#Ya(),this.width){const[i,s]=this.parentDimensions;this.setAspectRatio(this.width*i,this.height*s),this.setAt(t*i,e*s,this.width*i,this.height*s),this.#ja=!0,this.#Ja(),this.setDims(this.width*i,this.height*s),this.#Ka(),this.div.classList.add("disabled")}else this.div.classList.add("editing"),this.enableEditMode();return this.#Qa(),this.div}#Ja(){if(!this.#ja)return;const[t,e]=this.parentDimensions;this.canvas.width=Math.ceil(this.width*t),this.canvas.height=Math.ceil(this.height*e),this.#dr()}setDimensions(t,e){const i=Math.round(t),s=Math.round(e);if(this.#Wa===i&&this.#Ga===s)return;this.#Wa=i,this.#Ga=s,this.canvas.style.visibility="hidden";const[n,a]=this.parentDimensions;this.width=t/n,this.height=e/a,this.fixAndSetPosition(),this.#Ba&&this.#ur(t,e),this.#Ja(),this.#Ka(),this.canvas.style.visibility="visible",this.fixDims()}#ur(t,e){const i=this.#pr(),s=(t-i)/this.#Fa,n=(e-i)/this.#La;this.scaleFactor=Math.min(s,n)}#dr(){const t=this.#pr()/2;this.ctx.setTransform(this.scaleFactor,0,0,this.scaleFactor,this.translationX*this.scaleFactor+t,this.translationY*this.scaleFactor+t)}static#gr(t){const e=new Path2D;for(let i=0,s=t.length;i`image/${t}`)))}static get supportedTypesStr(){return E(this,"supportedTypesStr",this.supportedTypes.join(","))}static isHandlingMimeForPasting(t){return this.supportedTypes.includes(t)}static paste(t,e){e.pasteEditor(h.STAMP,{bitmapFile:t.getAsFile()})}altTextFinish(){this._uiManager.useNewAltTextFlow&&(this.div.hidden=!1),super.altTextFinish()}get telemetryFinalData(){return{type:"stamp",hasAltText:!!this.altTextData?.altText}}static computeTelemetryFinalData(t){const e=t.get("hasAltText");return{hasAltText:e.get(!0)??0,hasNoAltText:e.get(!1)??0}}#kr(t,e=!1){t?(this.#Ar=t.bitmap,e||(this.#yr=t.id,this.#Tr=t.isSvg),t.file&&(this.#Cr=t.file.name),this.#Ya()):this.remove()}#Ir(){if(this.#wr=null,this._uiManager.enableWaiting(!1),this.#Er){if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#Ar)return this._editToolbar.hide(),void this._uiManager.editAltText(this,!0);if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#Ar){this._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:!1,alt_text_type:"empty"}});try{this.mlGuessAltText()}catch{}}this.div.focus()}}async mlGuessAltText(t=null,e=!0){if(this.hasAltTextData())return null;const{mlManager:i}=this._uiManager;if(!i)throw new Error("No ML.");if(!await i.isEnabledFor("altText"))throw new Error("ML isn't enabled for alt text.");const{data:s,width:n,height:a}=t||this.copyCanvas(null,null,!0).imageData,r=await i.guess({name:"altText",request:{data:s,width:n,height:a,channels:s.length/(n*a)}});if(!r)throw new Error("No response from the AI service.");if(r.error)throw new Error("Error from the AI service.");if(r.cancel)return null;if(!r.output)throw new Error("No valid response from the AI service.");const o=r.output;return await this.setGuessedAltText(o),e&&!this.hasAltTextData()&&(this.altTextData={alt:o,decorative:!1}),o}#Pr(){if(this.#yr)return this._uiManager.enableWaiting(!0),void this._uiManager.imageManager.getFromId(this.#yr).then((t=>this.#kr(t,!0))).finally((()=>this.#Ir()));if(this.#_r){const t=this.#_r;return this.#_r=null,this._uiManager.enableWaiting(!0),void(this.#wr=this._uiManager.imageManager.getFromUrl(t).then((t=>this.#kr(t))).finally((()=>this.#Ir())))}if(this.#xr){const t=this.#xr;return this.#xr=null,this._uiManager.enableWaiting(!0),void(this.#wr=this._uiManager.imageManager.getFromFile(t).then((t=>this.#kr(t))).finally((()=>this.#Ir())))}const t=document.createElement("input");t.type="file",t.accept=ls.supportedTypesStr;const e=this._uiManager._signal;this.#wr=new Promise((i=>{t.addEventListener("change",(async()=>{if(t.files&&0!==t.files.length){this._uiManager.enableWaiting(!0);const e=await this._uiManager.imageManager.getFromFile(t.files[0]);this._reportTelemetry({action:"pdfjs.image.image_selected",data:{alt_text_modal:this._uiManager.useNewAltTextFlow}}),this.#kr(e)}else this.remove();i()}),{signal:e}),t.addEventListener("cancel",(()=>{this.remove(),i()}),{signal:e})})).finally((()=>this.#Ir())),t.click()}remove(){this.#yr&&(this.#Ar=null,this._uiManager.imageManager.deleteId(this.#yr),this.#Er?.remove(),this.#Er=null,this.#Ua?.disconnect(),this.#Ua=null,this.#Sr&&(clearTimeout(this.#Sr),this.#Sr=null)),super.remove()}rebuild(){this.parent?(super.rebuild(),null!==this.div&&(this.#yr&&null===this.#Er&&this.#Pr(),this.isAttachedToDOM||this.parent.add(this))):this.#yr&&this.#Pr()}onceAdded(){this._isDraggable=!0,this.div.focus()}isEmpty(){return!(this.#wr||this.#Ar||this.#_r||this.#xr||this.#yr)}get isResizable(){return!0}render(){if(this.div)return this.div;let t,e;if(this.width&&(t=this.x,e=this.y),super.render(),this.div.hidden=!0,this.div.setAttribute("role","figure"),this.addAltTextButton(),this.#Ar?this.#Ya():this.#Pr(),this.width&&!this.annotationElementId){const[i,s]=this.parentDimensions;this.setAt(t*i,e*s,this.width*i,this.height*s)}return this.div}#Ya(){const{div:t}=this;let{width:e,height:i}=this.#Ar;const[s,n]=this.pageDimensions,a=.75;if(this.width)e=this.width*s,i=this.height*n;else if(e>a*s||i>a*n){const t=Math.min(a*s/e,a*n/i);e*=t,i*=t}const[r,o]=this.parentDimensions;this.setDims(e*r/s,i*o/n),this._uiManager.enableWaiting(!1);const l=this.#Er=document.createElement("canvas");l.setAttribute("role","img"),this.addContainer(l),this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&!this.annotationElementId||(t.hidden=!1),this.#Rr(e,i),this.#Qa(),this.#Mr||(this.parent.addUndoableEditor(this),this.#Mr=!0),this._reportTelemetry({action:"inserted_image"}),this.#Cr&&l.setAttribute("aria-label",this.#Cr)}copyCanvas(t,e,i=!1){t||(t=224);const{width:s,height:n}=this.#Ar,a=new vt;let r=this.#Ar,o=s,l=n,h=null;if(e){if(s>e||n>e){const t=Math.min(e/s,e/n);o=Math.floor(s*t),l=Math.floor(n*t)}h=document.createElement("canvas");const t=h.width=Math.ceil(o*a.sx),i=h.height=Math.ceil(l*a.sy);this.#Tr||(r=this.#Dr(t,i));const d=h.getContext("2d");d.filter=this._uiManager.hcmFilter;let c="white",u="#cfcfd8";"none"!==this._uiManager.hcmFilter?u="black":window.matchMedia?.("(prefers-color-scheme: dark)").matches&&(c="#8f8f9d",u="#42414d");const p=15,g=p*a.sx,m=p*a.sy,f=new OffscreenCanvas(2*g,2*m),b=f.getContext("2d");b.fillStyle=c,b.fillRect(0,0,2*g,2*m),b.fillStyle=u,b.fillRect(0,0,g,m),b.fillRect(g,m,g,m),d.fillStyle=d.createPattern(f,"repeat"),d.fillRect(0,0,t,i),d.drawImage(r,0,0,r.width,r.height,0,0,t,i)}let d=null;if(i){let e,i;if(a.symmetric&&r.widtht||n>t){const a=Math.min(t/s,t/n);e=Math.floor(s*a),i=Math.floor(n*a),this.#Tr||(r=this.#Dr(e,i))}const o=new OffscreenCanvas(e,i).getContext("2d",{willReadFrequently:!0});o.drawImage(r,0,0,r.width,r.height,0,0,e,i),d={width:e,height:i,data:o.getImageData(0,0,e,i).data}}return{canvas:h,width:o,height:l,imageData:d}}#Lr(t,e){const[i,s]=this.parentDimensions;this.width=t/i,this.height=e/s,this._initialOptions?.isCentered?this.center():this.fixAndSetPosition(),this._initialOptions=null,null!==this.#Sr&&clearTimeout(this.#Sr),this.#Sr=setTimeout((()=>{this.#Sr=null,this.#Rr(t,e)}),200)}#Dr(t,e){const{width:i,height:s}=this.#Ar;let n=i,a=s,r=this.#Ar;for(;n>2*t||a>2*e;){const i=n,s=a;n>2*t&&(n=n>=16384?Math.floor(n/2)-1:Math.ceil(n/2)),a>2*e&&(a=a>=16384?Math.floor(a/2)-1:Math.ceil(a/2));const o=new OffscreenCanvas(n,a);o.getContext("2d").drawImage(r,0,0,i,s,0,0,n,a),r=o.transferToImageBitmap()}return r}#Rr(t,e){const i=new vt,s=Math.ceil(t*i.sx),n=Math.ceil(e*i.sy),a=this.#Er;if(!a||a.width===s&&a.height===n)return;a.width=s,a.height=n;const r=this.#Tr?this.#Ar:this.#Dr(s,n),o=a.getContext("2d");o.filter=this._uiManager.hcmFilter,o.drawImage(r,0,0,r.width,r.height,0,0,s,n)}getImageForAltText(){return this.#Er}#Fr(t){if(t){if(this.#Tr){const t=this._uiManager.imageManager.getSvgUrl(this.#yr);if(t)return t}const t=document.createElement("canvas");return({width:t.width,height:t.height}=this.#Ar),t.getContext("2d").drawImage(this.#Ar,0,0),t.toDataURL()}if(this.#Tr){const[t,e]=this.pageDimensions,i=Math.round(this.width*t*Y.PDF_TO_CSS_UNITS),s=Math.round(this.height*e*Y.PDF_TO_CSS_UNITS),n=new OffscreenCanvas(i,s);return n.getContext("2d").drawImage(this.#Ar,0,0,this.#Ar.width,this.#Ar.height,0,0,i,s),n.transferToImageBitmap()}return structuredClone(this.#Ar)}#Qa(){this._uiManager._signal&&(this.#Ua=new ResizeObserver((t=>{const e=t[0].contentRect;e.width&&e.height&&this.#Lr(e.width,e.height)})),this.#Ua.observe(this.div),this._uiManager._signal.addEventListener("abort",(()=>{this.#Ua?.disconnect(),this.#Ua=null}),{once:!0}))}static async deserialize(t,e,i){let s=null;if(t instanceof Ki){const{data:{rect:n,rotation:a,id:r,structParent:o,popupRef:l},container:d,parent:{page:{pageNumber:c}}}=t,u=d.querySelector("canvas"),p=i.imageManager.getFromCanvas(d.id,u);u.remove();const g=(await e._structTree.getAriaAttributes(`${$}${r}`))?.get("aria-label")||"";s=t={annotationType:h.STAMP,bitmapId:p.id,bitmap:p.bitmap,pageIndex:c-1,rect:n.slice(0),rotation:a,id:r,deleted:!1,accessibilityData:{decorative:!1,altText:g},isSvg:!1,structParent:o,popupRef:l}}const n=await super.deserialize(t,e,i),{rect:a,bitmap:r,bitmapUrl:o,bitmapId:l,isSvg:d,accessibilityData:c}=t;l&&i.imageManager.isValidId(l)?(n.#yr=l,r&&(n.#Ar=r)):n.#_r=o,n.#Tr=d;const[u,p]=n.pageDimensions;return n.width=(a[2]-a[0])/u,n.height=(a[3]-a[1])/p,n.annotationElementId=t.id||null,c&&(n.altTextData=c),n._initialData=s,n.#Mr=!!s,n}serialize(t=!1,e=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const i={annotationType:h.STAMP,bitmapId:this.#yr,pageIndex:this.pageIndex,rect:this.getRect(0,0),rotation:this.rotation,isSvg:this.#Tr,structTreeParentId:this._structTreeParentId};if(t)return i.bitmapUrl=this.#Fr(!0),i.accessibilityData=this.serializeAltText(!0),i;const{decorative:s,altText:n}=this.serializeAltText(!1);if(!s&&n&&(i.accessibilityData={type:"Figure",alt:n}),this.annotationElementId){const t=this.#gn(i);if(t.isSame)return null;t.isSameAltText?delete i.accessibilityData:i.accessibilityData.structParent=this._initialData.structParent??-1}if(i.id=this.annotationElementId,null===e)return i;e.stamps||=new Map;const a=this.#Tr?(i.rect[2]-i.rect[0])*(i.rect[3]-i.rect[1]):null;if(e.stamps.has(this.#yr)){if(this.#Tr){const t=e.stamps.get(this.#yr);a>t.area&&(t.area=a,t.serialized.bitmap.close(),t.serialized.bitmap=this.#Fr(!1))}}else e.stamps.set(this.#yr,{area:a,serialized:i}),i.bitmap=this.#Fr(!1);return i}#gn(t){const{rect:e,pageIndex:i,accessibilityData:{altText:s}}=this._initialData,n=t.rect.every(((t,i)=>Math.abs(t-e[i])<1)),a=t.pageIndex===i,r=(t.accessibilityData?.alt||"")===s;return{isSame:n&&a&&r,isSameAltText:r}}renderAnnotationElement(t){return t.updateEdited({rect:this.getRect(0,0)}),null}}class hs{#Qs;#Nr=!1;#Or=null;#Br=null;#zr=null;#Hr=new Map;#jr=!1;#Ur=!1;#$r=!1;#Wr=null;#Gr=null;#m;static _initialized=!1;static#H=new Map([Zi,os,ls,rs].map((t=>[t._editorType,t])));constructor({uiManager:t,pageIndex:e,div:i,structTreeLayer:s,accessibilityManager:n,annotationLayer:a,drawLayer:r,textLayer:o,viewport:l,l10n:h}){const d=[...hs.#H.values()];if(!hs._initialized){hs._initialized=!0;for(const e of d)e.initialize(h,t)}t.registerEditorTypes(d),this.#m=t,this.pageIndex=e,this.div=i,this.#Qs=n,this.#Or=a,this.viewport=l,this.#Wr=o,this.drawLayer=r,this._structTree=s,this.#m.addLayer(this)}get isEmpty(){return 0===this.#Hr.size}get isInvisible(){return this.isEmpty&&this.#m.getMode()===h.NONE}updateToolbar(t){this.#m.updateToolbar(t)}updateMode(t=this.#m.getMode()){switch(this.#Vr(),t){case h.NONE:return this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),void this.disableClick();case h.INK:this.addInkEditorIfNeeded(!1),this.disableTextSelection(),this.togglePointerEvents(!0),this.disableClick();break;case h.HIGHLIGHT:this.enableTextSelection(),this.togglePointerEvents(!1),this.disableClick();break;default:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick()}this.toggleAnnotationLayerPointerEvents(!1);const{classList:e}=this.div;for(const i of hs.#H.values())e.toggle(`${i._type}Editing`,t===i._editorType);this.div.hidden=!1}hasTextLayer(t){return t===this.#Wr?.div}addInkEditorIfNeeded(t){if(this.#m.getMode()===h.INK){if(!t)for(const t of this.#Hr.values())if(t.isEmpty())return void t.setInBackground();this.createAndAddNewEditor({offsetX:0,offsetY:0},!1).setInBackground()}}setEditingState(t){this.#m.setEditingState(t)}addCommands(t){this.#m.addCommands(t)}toggleDrawing(t=!1){this.div.classList.toggle("drawing",!t)}togglePointerEvents(t=!1){this.div.classList.toggle("disabled",!t)}toggleAnnotationLayerPointerEvents(t=!1){this.#Or?.div.classList.toggle("disabled",!t)}async enable(){this.div.tabIndex=0,this.togglePointerEvents(!0);const t=new Set;for(const e of this.#Hr.values())e.enableEditing(),e.show(!0),e.annotationElementId&&(this.#m.removeChangedExistingAnnotation(e),t.add(e.annotationElementId));if(!this.#Or)return;const e=this.#Or.getEditableAnnotations();for(const i of e){if(i.hide(),this.#m.isDeletedAnnotationElement(i.data.id))continue;if(t.has(i.data.id))continue;const e=await this.deserialize(i);e&&(this.addOrRebuild(e),e.enableEditing())}}disable(){this.#$r=!0,this.div.tabIndex=-1,this.togglePointerEvents(!1);const t=new Map,e=new Map;for(const i of this.#Hr.values())i.disableEditing(),i.annotationElementId&&(null===i.serialize()?(e.set(i.annotationElementId,i),this.getEditableAnnotation(i.annotationElementId)?.show(),i.remove()):t.set(i.annotationElementId,i));if(this.#Or){const i=this.#Or.getEditableAnnotations();for(const s of i){const{id:i}=s.data;if(this.#m.isDeletedAnnotationElement(i))continue;let n=e.get(i);n?(n.resetAnnotationElement(s),n.show(!1),s.show()):(n=t.get(i),n&&(this.#m.addChangedExistingAnnotation(n),n.renderAnnotationElement(s)&&n.show(!1)),s.show())}}this.#Vr(),this.isEmpty&&(this.div.hidden=!0);const{classList:i}=this.div;for(const t of hs.#H.values())i.remove(`${t._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),this.#$r=!1}getEditableAnnotation(t){return this.#Or?.getEditableAnnotation(t)||null}setActiveEditor(t){this.#m.getActive()!==t&&this.#m.setActiveEditor(t)}enableTextSelection(){if(this.div.tabIndex=-1,this.#Wr?.div&&!this.#Gr){this.#Gr=new AbortController;const t=this.#m.combinedSignal(this.#Gr);this.#Wr.div.addEventListener("pointerdown",this.#qr.bind(this),{signal:t}),this.#Wr.div.classList.add("highlighting")}}disableTextSelection(){this.div.tabIndex=0,this.#Wr?.div&&this.#Gr&&(this.#Gr.abort(),this.#Gr=null,this.#Wr.div.classList.remove("highlighting"))}#qr(t){this.#m.unselectAll();const{target:e}=t;if(e===this.#Wr.div||("img"===e.getAttribute("role")||e.classList.contains("endOfContent"))&&this.#Wr.div.contains(e)){const{isMac:e}=O.platform;if(0!==t.button||t.ctrlKey&&e)return;this.#m.showAllEditors("highlight",!0,!0),this.#Wr.div.classList.add("free"),this.toggleDrawing(),rs.startHighlighting(this,"ltr"===this.#m.direction,{target:this.#Wr.div,x:t.x,y:t.y}),this.#Wr.div.addEventListener("pointerup",(()=>{this.#Wr.div.classList.remove("free"),this.toggleDrawing(!0)}),{once:!0,signal:this.#m._signal}),t.preventDefault()}}enableClick(){if(this.#Br)return;this.#Br=new AbortController;const t=this.#m.combinedSignal(this.#Br);this.div.addEventListener("pointerdown",this.pointerdown.bind(this),{signal:t}),this.div.addEventListener("pointerup",this.pointerup.bind(this),{signal:t})}disableClick(){this.#Br?.abort(),this.#Br=null}attach(t){this.#Hr.set(t.id,t);const{annotationElementId:e}=t;e&&this.#m.isDeletedAnnotationElement(e)&&this.#m.removeDeletedAnnotationElement(t)}detach(t){this.#Hr.delete(t.id),this.#Qs?.removePointerInTextLayer(t.contentDiv),!this.#$r&&t.annotationElementId&&this.#m.addDeletedAnnotationElement(t)}remove(t){this.detach(t),this.#m.removeEditor(t),t.div.remove(),t.isAttachedToDOM=!1,this.#Ur||this.addInkEditorIfNeeded(!1)}changeParent(t){t.parent!==this&&(t.parent&&t.annotationElementId&&(this.#m.addDeletedAnnotationElement(t.annotationElementId),kt.deleteAnnotationElement(t),t.annotationElementId=null),this.attach(t),t.parent?.detach(t),t.setParent(this),t.div&&t.isAttachedToDOM&&(t.div.remove(),this.div.append(t.div)))}add(t){if(t.parent!==this||!t.isAttachedToDOM){if(this.changeParent(t),this.#m.addEditor(t),this.attach(t),!t.isAttachedToDOM){const e=t.render();this.div.append(e),t.isAttachedToDOM=!0}t.fixAndSetPosition(),t.onceAdded(),this.#m.addToAnnotationStorage(t),t._reportTelemetry(t.telemetryInitialData)}}moveEditorInDOM(t){if(!t.isAttachedToDOM)return;const{activeElement:e}=document;t.div.contains(e)&&!this.#zr&&(t._focusEventsAllowed=!1,this.#zr=setTimeout((()=>{this.#zr=null,t.div.contains(document.activeElement)?t._focusEventsAllowed=!0:(t.div.addEventListener("focusin",(()=>{t._focusEventsAllowed=!0}),{once:!0,signal:this.#m._signal}),e.focus())}),0)),t._structTreeParentId=this.#Qs?.moveElementInDOM(this.div,t.div,t.contentDiv,!0)}addOrRebuild(t){t.needsToBeRebuilt()?(t.parent||=this,t.rebuild(),t.show()):this.add(t)}addUndoableEditor(t){this.addCommands({cmd:()=>t._uiManager.rebuild(t),undo:()=>{t.remove()},mustExec:!1})}getNextId(){return this.#m.getId()}get#Xr(){return hs.#H.get(this.#m.getMode())}combinedSignal(t){return this.#m.combinedSignal(t)}#Kr(t){const e=this.#Xr;return e?new e.prototype.constructor(t):null}canCreateNewEmptyEditor(){return this.#Xr?.canCreateNewEmptyEditor()}pasteEditor(t,e){this.#m.updateToolbar(t),this.#m.updateMode(t);const{offsetX:i,offsetY:s}=this.#Yr(),n=this.getNextId(),a=this.#Kr({parent:this,id:n,x:i,y:s,uiManager:this.#m,isCentered:!0,...e});a&&this.add(a)}async deserialize(t){return await(hs.#H.get(t.annotationType??t.annotationEditorType)?.deserialize(t,this,this.#m))||null}createAndAddNewEditor(t,e,i={}){const s=this.getNextId(),n=this.#Kr({parent:this,id:s,x:t.offsetX,y:t.offsetY,uiManager:this.#m,isCentered:e,...i});return n&&this.add(n),n}#Yr(){const{x:t,y:e,width:i,height:s}=this.div.getBoundingClientRect(),n=Math.max(0,t),a=Math.max(0,e),r=(n+Math.min(window.innerWidth,t+i))/2-t,o=(a+Math.min(window.innerHeight,e+s))/2-e,[l,h]=this.viewport.rotation%180==0?[r,o]:[o,r];return{offsetX:l,offsetY:h}}addNewEditor(){this.createAndAddNewEditor(this.#Yr(),!0)}setSelected(t){this.#m.setSelected(t)}toggleSelected(t){this.#m.toggleSelected(t)}isSelected(t){return this.#m.isSelected(t)}unselect(t){this.#m.unselect(t)}pointerup(t){const{isMac:e}=O.platform;0!==t.button||t.ctrlKey&&e||t.target===this.div&&this.#jr&&(this.#jr=!1,this.#Nr?this.#m.getMode()!==h.STAMP?this.createAndAddNewEditor(t,!1):this.#m.unselectAll():this.#Nr=!0)}pointerdown(t){if(this.#m.getMode()===h.HIGHLIGHT&&this.enableTextSelection(),this.#jr)return void(this.#jr=!1);const{isMac:e}=O.platform;if(0!==t.button||t.ctrlKey&&e)return;if(t.target!==this.div)return;this.#jr=!0;const i=this.#m.getActive();this.#Nr=!i||i.isEmpty()}findNewParent(t,e,i){const s=this.#m.findParent(e,i);return null!==s&&s!==this&&(s.changeParent(t),!0)}destroy(){this.#m.getActive()?.parent===this&&(this.#m.commitOrRemove(),this.#m.setActiveEditor(null)),this.#zr&&(clearTimeout(this.#zr),this.#zr=null);for(const t of this.#Hr.values())this.#Qs?.removePointerInTextLayer(t.contentDiv),t.setParent(null),t.isAttachedToDOM=!1,t.div.remove();this.div=null,this.#Hr.clear(),this.#m.removeLayer(this)}#Vr(){this.#Ur=!0;for(const t of this.#Hr.values())t.isEmpty()&&t.remove();this.#Ur=!1}render({viewport:t}){this.viewport=t,bt(this.div,t);for(const t of this.#m.getEditors(this.pageIndex))this.add(t),t.rebuild();this.updateMode()}update({viewport:t}){this.#m.commitOrRemove(),this.#Vr();const e=this.viewport.rotation,i=t.rotation;if(this.viewport=t,bt(this.div,{rotation:i}),e!==i)for(const t of this.#Hr.values())t.rotate(i);this.addInkEditorIfNeeded(!1)}get pageDimensions(){const{pageWidth:t,pageHeight:e}=this.viewport.rawDims;return[t,e]}get scale(){return this.#m.viewParameters.realScale}}class ds{#Ps=null;#A=0;#Qr=new Map;#Jr=new Map;constructor({pageIndex:t}){this.pageIndex=t}setParent(t){if(this.#Ps){if(this.#Ps!==t){if(this.#Qr.size>0)for(const e of this.#Qr.values())e.remove(),t.append(e);this.#Ps=t}}else this.#Ps=t}static get _svgFactory(){return E(this,"_svgFactory",new tt)}static#Zr(t,{x:e=0,y:i=0,width:s=1,height:n=1}={}){const{style:a}=t;a.top=100*i+"%",a.left=100*e+"%",a.width=100*s+"%",a.height=100*n+"%"}#to(t){const e=ds._svgFactory.create(1,1,!0);return this.#Ps.append(e),e.setAttribute("aria-hidden",!0),ds.#Zr(e,t),e}#eo(t,e){const i=ds._svgFactory.createElement("clipPath");t.append(i);const s=`clip_${e}`;i.setAttribute("id",s),i.setAttribute("clipPathUnits","objectBoundingBox");const n=ds._svgFactory.createElement("use");return i.append(n),n.setAttribute("href",`#${e}`),n.classList.add("clip"),s}highlight(t,e,i,s=!1){const n=this.#A++,a=this.#to(t.box);a.classList.add("highlight"),t.free&&a.classList.add("free");const r=ds._svgFactory.createElement("defs");a.append(r);const o=ds._svgFactory.createElement("path");r.append(o);const l=`path_p${this.pageIndex}_${n}`;o.setAttribute("id",l),o.setAttribute("d",t.toSVGPath()),s&&this.#Jr.set(n,o);const h=this.#eo(r,l),d=ds._svgFactory.createElement("use");return a.append(d),a.setAttribute("fill",e),a.setAttribute("fill-opacity",i),d.setAttribute("href",`#${l}`),this.#Qr.set(n,a),{id:n,clipPathId:`url(#${h})`}}highlightOutline(t){const e=this.#A++,i=this.#to(t.box);i.classList.add("highlightOutline");const s=ds._svgFactory.createElement("defs");i.append(s);const n=ds._svgFactory.createElement("path");s.append(n);const a=`path_p${this.pageIndex}_${e}`;let r;if(n.setAttribute("id",a),n.setAttribute("d",t.toSVGPath()),n.setAttribute("vector-effect","non-scaling-stroke"),t.free){i.classList.add("free");const t=ds._svgFactory.createElement("mask");s.append(t),r=`mask_p${this.pageIndex}_${e}`,t.setAttribute("id",r),t.setAttribute("maskUnits","objectBoundingBox");const n=ds._svgFactory.createElement("rect");t.append(n),n.setAttribute("width","1"),n.setAttribute("height","1"),n.setAttribute("fill","white");const o=ds._svgFactory.createElement("use");t.append(o),o.setAttribute("href",`#${a}`),o.setAttribute("stroke","none"),o.setAttribute("fill","black"),o.setAttribute("fill-rule","nonzero"),o.classList.add("mask")}const o=ds._svgFactory.createElement("use");i.append(o),o.setAttribute("href",`#${a}`),r&&o.setAttribute("mask",`url(#${r})`);const l=o.cloneNode();return i.append(l),o.classList.add("mainOutline"),l.classList.add("secondaryOutline"),this.#Qr.set(e,i),e}finalizeLine(t,e){const i=this.#Jr.get(t);this.#Jr.delete(t),this.updateBox(t,e.box),i.setAttribute("d",e.toSVGPath())}updateLine(t,e){this.#Qr.get(t).firstChild.firstChild.setAttribute("d",e.toSVGPath())}removeFreeHighlight(t){this.remove(t),this.#Jr.delete(t)}updatePath(t,e){this.#Jr.get(t).setAttribute("d",e.toSVGPath())}updateBox(t,e){ds.#Zr(this.#Qr.get(t),e)}show(t,e){this.#Qr.get(t).classList.toggle("hidden",!e)}rotate(t,e){this.#Qr.get(t).setAttribute("data-main-rotation",e)}changeColor(t,e){this.#Qr.get(t).setAttribute("fill",e)}changeOpacity(t,e){this.#Qr.get(t).setAttribute("fill-opacity",e)}addClass(t,e){this.#Qr.get(t).classList.add(e)}removeClass(t,e){this.#Qr.get(t).classList.remove(e)}getSVGRoot(t){return this.#Qr.get(t)}remove(t){null!==this.#Ps&&(this.#Qr.get(t).remove(),this.#Qr.delete(t))}destroy(){this.#Ps=null;for(const t of this.#Qr.values())t.remove();this.#Qr.clear()}}var cs=e.AbortException,us=e.AnnotationEditorLayer,ps=e.AnnotationEditorParamsType,gs=e.AnnotationEditorType,ms=e.AnnotationEditorUIManager,fs=e.AnnotationLayer,bs=e.AnnotationMode,vs=e.CMapCompressionType,As=e.ColorPicker,ys=e.DOMSVGFactory,ws=e.DrawLayer,_s=e.FeatureTest,xs=e.GlobalWorkerOptions,Cs=e.ImageKind,Es=e.InvalidPDFException,Ss=e.MissingPDFException,Ts=e.OPS,Ms=e.OutputScale,ks=e.PDFDataRangeTransport,Is=e.PDFDateString,Ps=e.PDFWorker,Rs=e.PasswordResponses,Ds=e.PermissionFlag,Ls=e.PixelsPerInch,Fs=e.RenderingCancelledException,Ns=e.TextLayer,Os=e.UnexpectedResponseException,Bs=e.Util,zs=e.VerbosityLevel,Hs=e.XfaLayer,js=e.build,Us=e.createValidAbsoluteUrl,$s=e.fetchData,Ws=e.getDocument,Gs=e.getFilenameFromUrl,Vs=e.getPdfFilenameFromUrl,qs=e.getXfaPageViewport,Xs=e.isDataScheme,Ks=e.isPdfFile,Ys=e.noContextMenu,Qs=e.normalizeUnicode,Js=e.setLayerDimensions,Zs=e.shadow,tn=e.version;"undefined"!=typeof window&&"Worker"in window&&(xs.workerPort=new Worker(new URL(i.p+i.u(13),i.b),{type:void 0}))}}]); \ No newline at end of file diff --git a/dist/352.index.js.LICENSE.txt b/dist/840.index.js.LICENSE.txt similarity index 100% rename from dist/352.index.js.LICENSE.txt rename to dist/840.index.js.LICENSE.txt diff --git a/dist/index.html b/dist/index.html new file mode 100644 index 0000000..2f3d6af --- /dev/null +++ b/dist/index.html @@ -0,0 +1,18 @@ +Html Webpack Plugin: +
+  Error: The loader "/Users/cameron.jewell_cn/Projects/react-file-viewer/node_modules/html-webpack-plugin/lib/loader.js!/Users/cameron.jewell_cn/Projects/react-file-viewer/node_modules/html-webpack-plugin/default_index.ejs" didn't return html.
+  
+  - index.js:323 HtmlWebpackPlugin.evaluateCompilationResult
+    [react-file-viewer]/[html-webpack-plugin]/index.js:323:24
+  
+  - index.js:230 
+    [react-file-viewer]/[html-webpack-plugin]/index.js:230:22
+  
+  - task_queues:95 process.processTicksAndRejections
+    node:internal/process/task_queues:95:5
+  
+  - async Promise.all
+  
+  - async Promise.all
+  
+
\ No newline at end of file diff --git a/dist/index.js b/dist/index.js index f2d418b..2ec95cb 100644 --- a/dist/index.js +++ b/dist/index.js @@ -1,2 +1,2 @@ /*! For license information please see index.js.LICENSE.txt */ -!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e(require("react"),require("react-dom")):"function"==typeof define&&define.amd?define(["react","react-dom"],e):"object"==typeof exports?exports.FileViewer=e(require("react"),require("react-dom")):t.FileViewer=e(t.React,t.ReactDOM)}(self,((t,e)=>(()=>{var n,i,r={154:t=>{function e(){return t.exports=e=Object.assign||function(t){for(var e=1;e{t.exports=function(t){return t&&t.__esModule?t:{default:t}}},85:(t,e,n)=>{"use strict";var i=n(318);Object.defineProperty(e,"__esModule",{value:!0}),e.default=e.PDFPage=void 0;var r=i(n(787)),s=i(n(82));class a extends r.default.Component{constructor(t){super(t),this.state={},this.onChange=this.onChange.bind(this)}componentDidMount(){this.props.disableVisibilityCheck&&this.fetchAndRenderPage()}componentDidUpdate(t,e){this.props.disableVisibilityCheck?t.zoom!==this.props.zoom&&this.fetchAndRenderPage():e.isVisible===this.state.isVisible&&t.zoom===this.props.zoom||this.state.isVisible&&this.fetchAndRenderPage()}onChange(t){t&&this.setState({isVisible:t})}fetchAndRenderPage(){const{pdf:t,index:e}=this.props;t.getPage(e).then(this.renderPage.bind(this)).catch((t=>{console.error(`Error fetching page ${e}:`,t)}))}renderPage(t){try{const{containerWidth:e,zoom:n}=this.props,i=e/t.getViewport({scale:1.1}).width,r=(i>1.1?1.1:i)+.2*n,s=t.getViewport({scale:r}),{width:a,height:o}=s,l=this.canvas.getContext("2d");this.canvas.width=a,this.canvas.height=o,t.render({canvasContext:l,viewport:s})}catch(t){console.error(`Error rendering page ${this.props.index}:`,t)}}render(){const{index:t}=this.props;return r.default.createElement("div",{key:`page-${t}`,className:"pdf-canvas"},this.props.disableVisibilityCheck?r.default.createElement("canvas",{ref:t=>this.canvas=t,width:"670",height:"870"}):r.default.createElement(s.default,{onChange:this.onChange,partialVisibility:!0},r.default.createElement("canvas",{ref:t=>this.canvas=t,width:"670",height:"870"})))}}e.PDFPage=a;class o extends r.default.Component{constructor(t){super(t),this.state={pdf:null,zoom:0,percent:0},this.increaseZoom=this.increaseZoom.bind(this),this.reduceZoom=this.reduceZoom.bind(this),this.resetZoom=this.resetZoom.bind(this)}componentDidMount(){(async()=>{const t=await n.e(560).then(n.bind(n,560)),{filePath:e}=this.props,i=this.container.offsetWidth,r=t.getDocument(e);r.onProgress=t=>{this.progressCallback(t)},r.promise.then((t=>{this.setState({pdf:t,containerWidth:i})})).catch((t=>{null!=typeof this.props.onError&&null!=this.props.onError?this.props.onError(t):console.error("Error loading PDF:",t)}))})()}componentWillUnmount(){const{pdf:t}=this.state;t&&(t.destroy(),this.setState({pdf:null}))}setZoom(t){this.setState({zoom:t})}progressCallback(t){const e=(t.loaded/t.total*100).toFixed();this.setState({percent:e})}reduceZoom(){0!==this.state.zoom&&this.setZoom(this.state.zoom-1)}increaseZoom(){this.setZoom(this.state.zoom+1)}resetZoom(){this.setZoom(0)}renderPages(){const{pdf:t,containerWidth:e,zoom:n}=this.state;return t?[...Array(t.numPages).keys()].map((t=>t+1)).map(((i,s)=>r.default.createElement(a,{index:s+1,key:`pdfPage_${s}`,pdf:t,containerWidth:e,zoom:.2*n,disableVisibilityCheck:this.props.disableVisibilityCheck}))):null}renderLoading(){return this.state.pdf?null:r.default.createElement("div",{className:"pdf-loading"},"LOADING (",this.state.percent,"%)")}render(){const{renderControls:t}=this.props;return r.default.createElement("div",{className:"pdf-viewer-container"},t?t({handleZoomIn:this.increaseZoom,handleZoomOut:this.reduceZoom}):r.default.createElement("div",{className:"pdf-controls-container"},r.default.createElement("button",{type:"button",className:"view-control",onClick:this.increaseZoom},r.default.createElement("i",{className:"zoom-in"})),r.default.createElement("button",{type:"button",className:"view-control",onClick:this.resetZoom},r.default.createElement("i",{className:"zoom-reset"})),r.default.createElement("button",{type:"button",className:"view-control",onClick:this.reduceZoom},r.default.createElement("i",{className:"zoom-out"}))),r.default.createElement("div",{className:"pdf-viewer",ref:t=>this.container=t},this.renderLoading(),this.renderPages()))}}e.default=o,o.defaultProps={disableVisibilityCheck:!1}},229:(t,e,n)=>{"use strict";var i=n(318);Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var r=i(n(154)),s=u(n(787)),a=u(n(232)),o=i(n(679)),l=i(n(908)),c=i(n(886));function h(t){if("function"!=typeof WeakMap)return null;var e=new WeakMap,n=new WeakMap;return(h=function(t){return t?n:e})(t)}function u(t,e){if(!e&&t&&t.__esModule)return t;if(null===t||"object"!=typeof t&&"function"!=typeof t)return{default:t};var n=h(e);if(n&&n.has(t))return n.get(t);var i={__proto__:null},r=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in t)if("default"!==s&&{}.hasOwnProperty.call(t,s)){var a=r?Object.getOwnPropertyDescriptor(t,s):null;a&&(a.get||a.set)?Object.defineProperty(i,s,a):i[s]=t[s]}return i.default=t,n&&n.set(t,i),i}class d extends s.Component{constructor(t){super(t),this.state={originalWidth:0,originalHeight:0,imageLoaded:!1}}componentDidMount(){const t=new a.TextureLoader;t.crossOrigin="";var e=this.props.onError;void 0!==e&&null!=e||(e=t=>{console.log("An error happened",t)}),t.load(this.props.filePath,(t=>{this.setState({originalWidth:t.image.width,originalHeight:t.image.height,imageLoaded:!0,texture:t})}),(t=>{console.log(t.loaded/t.total*100+"% loaded")}),e)}render(){if(!this.state.imageLoaded)return s.default.createElement(c.default,null);const{originalWidth:t,originalHeight:e}=this.state,n=(i=t,a=e,"jpg"===this.props.fileType&&window.Math.abs(i/a-2)<=.01?l.default:o.default);var i,a;return s.default.createElement(n,(0,r.default)({},this.state,this.props))}}e.default=d},679:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=function(t,e){if(t&&t.__esModule)return t;if(null===t||"object"!=typeof t&&"function"!=typeof t)return{default:t};var n=r(e);if(n&&n.has(t))return n.get(t);var i={__proto__:null},s=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var a in t)if("default"!==a&&{}.hasOwnProperty.call(t,a)){var o=s?Object.getOwnPropertyDescriptor(t,a):null;o&&(o.get||o.set)?Object.defineProperty(i,a,o):i[a]=t[a]}return i.default=t,n&&n.set(t,i),i}(n(787));function r(t){if("function"!=typeof WeakMap)return null;var e=new WeakMap,n=new WeakMap;return(r=function(t){return t?n:e})(t)}n(266);class s extends i.Component{constructor(t){super(t),this.state={zoom:10},this.increaseZoom=this.increaseZoom.bind(this),this.reduceZoom=this.reduceZoom.bind(this),this.rotateLeft=this.rotateLeft.bind(this),this.rotateRight=this.rotateRight.bind(this)}setZoom(t){this.setState({zoom:t})}increaseZoom(){const{zoom:t}=this.state;this.setZoom(t+1)}reduceZoom(){const{zoom:t}=this.state;t>1&&this.setZoom(t-1)}updateRotation(t){t>=0&&t<=3&&this.props.setRotationValue(t)}rotateLeft(){const t=(this.props.rotationValue+3)%4;this.updateRotation(t)}rotateRight(){const t=(this.props.rotationValue+1)%4;this.updateRotation(t)}componentDidMount(){const{originalWidth:t,originalHeight:e}=this.props,n=this.getImageDimensions.call(this,t,e);this.props.texture.image.style.width=`${n.width}px`,this.props.texture.image.style.height=`${n.height}px`,this.props.texture.image.style.transformOrigin="center center",this.props.texture.image.setAttribute("class","photo"),this.props.texture.image.setAttribute("z-index","0"),document.getElementById("photo-viewer-image-container").appendChild(this.props.texture.image)}componentWillUnmount(){const{texture:t}=this.props,e=t.image;e.parentNode&&e.parentNode.removeChild(e)}getImageDimensions(t,e){let n,i;const{height:r,width:s}=this.props;if(e<=r&&t<=s)i=t,n=e;else{const a=r/e,o=s/t;a{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=a(n(787)),r=a(n(232));function s(t){if("function"!=typeof WeakMap)return null;var e=new WeakMap,n=new WeakMap;return(s=function(t){return t?n:e})(t)}function a(t,e){if(!e&&t&&t.__esModule)return t;if(null===t||"object"!=typeof t&&"function"!=typeof t)return{default:t};var n=s(e);if(n&&n.has(t))return n.get(t);var i={__proto__:null},r=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var a in t)if("default"!==a&&{}.hasOwnProperty.call(t,a)){var o=r?Object.getOwnPropertyDescriptor(t,a):null;o&&(o.get||o.set)?Object.defineProperty(i,a,o):i[a]=t[a]}return i.default=t,n&&n.set(t,i),i}n(193);class o extends i.Component{constructor(t){super(t),this.onMouseDown=this.onMouseDown.bind(this),this.onMouseMove=this.onMouseMove.bind(this),this.onMouseUp=this.onMouseUp.bind(this),this.state={manualControl:!1,longitude:0,latitude:0,savedX:void 0,savedY:void 0,savedLongitude:void 0,savedLatitude:void 0}}componentDidMount(){const t=document.getElementById("360-photo"),e=t.getBoundingClientRect(),n=e.height,i=e.width;this.renderer=new r.WebGLRenderer,this.renderer.setSize(i,n),t.appendChild(this.renderer.domElement),this.scene=new r.Scene,this.camera=new r.PerspectiveCamera(75,i/n,1,1e3),this.camera.target=new r.Vector3(0,0,0),this.sphere=new r.SphereGeometry(100,100,40),this.sphere.applyMatrix((new r.Matrix4).makeScale(-1,1,1)),this.sphereMaterial=new r.MeshBasicMaterial,this.sphereMaterial.map=this.props.texture;const s=new r.Mesh(this.sphere,this.sphereMaterial);this.scene.add(s),this.updateView()}UNSAFE_componentWillUpdate(){this.updateView()}onMouseMove(t){const{savedX:e,savedY:n,savedLongitude:i,savedLatitude:r}=this.state;if(this.state.manualControl){const s=.1*(e-t.clientX)+i,a=.1*(t.clientY-n)+r;this.setState({longitude:s,latitude:a})}}onMouseUp(){this.setState({manualControl:!1})}onMouseDown(t){t.preventDefault(),this.setState({savedLongitude:this.state.longitude,savedLatitude:this.state.latitude,savedX:t.clientX,savedY:t.clientY,manualControl:!0})}updateView(){const t=Math.max(-85,Math.min(85,this.state.latitude));this.camera.target.x=500*Math.sin(r.MathUtils.degToRad(90-t)),Math.cos(r.MathUtils.degToRad(this.state.longitude)),this.camera.target.y=500*Math.cos(r.MathUtils.degToRad(90-t)),this.camera.target.z=500*Math.sin(r.MathUtils.degToRad(90-t))*Math.sin(r.MathUtils.degToRad(this.state.longitude)),this.camera.lookAt(this.camera.target),this.renderer.render(this.scene,this.camera)}render(){return i.default.createElement("div",{id:"360-photo",className:"photo360",onMouseDown:this.onMouseDown,onMouseMove:this.onMouseMove,onMouseUp:this.onMouseUp,role:"img"})}}e.default=o},282:(t,e,n)=>{"use strict";var i=n(318);Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var r=i(n(787));n(380),e.default=t=>r.default.createElement("div",{className:"pg-driver-view"},r.default.createElement("div",{className:"unsupported-message"},t.unsupportedComponent?r.default.createElement(t.unsupportedComponent,t):r.default.createElement("p",null,"No preview available for this kind of file.",r.default.createElement("br",null),"Download file to see the contents.")))},255:(t,e,n)=>{"use strict";var i=n(318);Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var r=i(n(154)),s=function(t,e){if(t&&t.__esModule)return t;if(null===t||"object"!=typeof t&&"function"!=typeof t)return{default:t};var n=h(e);if(n&&n.has(t))return n.get(t);var i={__proto__:null},r=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in t)if("default"!==s&&{}.hasOwnProperty.call(t,s)){var a=r?Object.getOwnPropertyDescriptor(t,s):null;a&&(a.get||a.set)?Object.defineProperty(i,s,a):i[s]=t[s]}return i.default=t,n&&n.set(t,i),i}(n(787)),a=i(n(697));n(192);var o=i(n(282)),l=i(n(85)),c=i(n(229));function h(t){if("function"!=typeof WeakMap)return null;var e=new WeakMap,n=new WeakMap;return(h=function(t){return t?n:e})(t)}class u extends s.Component{constructor(t){super(t),this.state={loading:!0}}componentDidMount(){const t=document.getElementById("pg-viewer"),e=t?t.clientHeight:0,n=t?t.clientWidth:0;this.setState({height:e,width:n})}getDriver(){switch(this.props.fileType){case"pdf":return l.default;case"jpg":case"jpeg":case"gif":case"png":return c.default;default:return o.default}}render(){const t=this.getDriver(this.props);return s.default.createElement("div",{className:"pg-viewer-wrapper"},s.default.createElement("div",{className:"pg-viewer",id:"pg-viewer"},s.default.createElement(t,(0,r.default)({},this.props,{width:this.state.width,height:this.state.height}))))}}u.displayName="FileViewer",u.propTypes={fileType:a.default.string.isRequired,filePath:a.default.string.isRequired,onError:a.default.func,errorComponent:a.default.element,unsupportedComponent:a.default.element},u.defaultProps={onError:()=>null,errorComponent:null,unsupportedComponent:null},e.default=u},352:(t,e,n)=>{"use strict";t.exports=n(255)},886:(t,e,n)=>{"use strict";var i=n(318);Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var r=i(n(787));n(269),e.default=()=>r.default.createElement("div",{className:"loading-container"},r.default.createElement("span",{className:"loading"}))},355:(t,e,n)=>{"use strict";n.r(e),n.d(e,{default:()=>d});var i=n(81),r=n.n(i),s=n(645),a=n.n(s),o=n(667),l=n.n(o),c=new URL(n(57),n.b),h=a()(r()),u=l()(c);h.push([t.id,".pg-viewer-wrapper .loading-container{-webkit-box-align:center;-ms-flex-align:center;align-items:center;display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-orient:horizontal;-webkit-box-direction:normal;-ms-flex-direction:row;flex-direction:row;height:100%;-webkit-box-pack:center;-ms-flex-pack:center;justify-content:center;width:100%}.pg-viewer-wrapper .loading-container .loading{background-image:url("+u+");background-repeat:no-repeat;display:inline-block;height:96px;width:96px;-webkit-animation:rotating 2s linear infinite;animation:rotating 2s linear infinite}@-webkit-keyframes rotating{from{-webkit-transform:rotate(0deg);transform:rotate(0deg)}to{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}@keyframes rotating{from{-webkit-transform:rotate(0deg);transform:rotate(0deg)}to{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}",""]);const d=h},329:(t,e,n)=>{"use strict";n.r(e),n.d(e,{default:()=>o});var i=n(81),r=n.n(i),s=n(645),a=n.n(s)()(r());a.push([t.id,".pg-viewer-wrapper{height:100%;display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-orient:horizontal;-webkit-box-direction:normal;-ms-flex-direction:row;flex-direction:row}.pg-viewer-wrapper .pg-viewer{height:100%;position:relative;-webkit-box-flex:2;-ms-flex-positive:2;flex-grow:2}.pg-viewer-wrapper .pg-viewer .pg-driver-view{margin:auto;width:100%;height:100%}.pg-viewer-wrapper .pg-viewer .pg-driver-view .loading{position:relative}.pg-viewer-wrapper .pg-viewer .pg-driver-view canvas,.pg-viewer-wrapper .pg-viewer .pg-driver-view .react-grid-Container{width:100%}.pg-viewer-wrapper .pg-viewer-link{background:#9370db;height:100%;-webkit-box-flex:1;-ms-flex-positive:1;flex-grow:1}.react-grid-Container{margin:auto}#xbim-viewer{height:100%;width:100%}#app{background:pink}",""]);const o=a},238:(t,e,n)=>{"use strict";n.r(e),n.d(e,{default:()=>o});var i=n(81),r=n.n(i),s=n(645),a=n.n(s)()(r());a.push([t.id,".pg-viewer-wrapper .photo-viewer-container{-webkit-box-align:center;-ms-flex-align:center;align-items:center;display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-orient:horizontal;-webkit-box-direction:normal;-ms-flex-direction:row;flex-direction:row;height:100%;-webkit-box-pack:center;-ms-flex-pack:center;justify-content:center;width:100%}",""]);const o=a},811:(t,e,n)=>{"use strict";n.r(e),n.d(e,{default:()=>o});var i=n(81),r=n.n(i),s=n(645),a=n.n(s)()(r());a.push([t.id,".photo360{height:100%;width:100%}",""]);const o=a},427:(t,e,n)=>{"use strict";n.r(e),n.d(e,{default:()=>o});var i=n(81),r=n.n(i),s=n(645),a=n.n(s)()(r());a.push([t.id,".unsupported-message{padding:46px;background:#dcdee0;color:#3d4551;margin:auto;text-align:center;height:100%;display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-align:center;-ms-flex-align:center;align-items:center;-webkit-box-pack:center;-ms-flex-pack:center;justify-content:center}",""]);const o=a},645:t=>{"use strict";t.exports=function(t){var e=[];return e.toString=function(){return this.map((function(e){var n="",i=void 0!==e[5];return e[4]&&(n+="@supports (".concat(e[4],") {")),e[2]&&(n+="@media ".concat(e[2]," {")),i&&(n+="@layer".concat(e[5].length>0?" ".concat(e[5]):""," {")),n+=t(e),i&&(n+="}"),e[2]&&(n+="}"),e[4]&&(n+="}"),n})).join("")},e.i=function(t,n,i,r,s){"string"==typeof t&&(t=[[null,t,void 0]]);var a={};if(i)for(var o=0;o0?" ".concat(h[5]):""," {").concat(h[1],"}")),h[5]=s),n&&(h[2]?(h[1]="@media ".concat(h[2]," {").concat(h[1],"}"),h[2]=n):h[2]=n),r&&(h[4]?(h[1]="@supports (".concat(h[4],") {").concat(h[1],"}"),h[4]=r):h[4]="".concat(r)),e.push(h))}},e}},667:t=>{"use strict";t.exports=function(t,e){return e||(e={}),t?(t=String(t.__esModule?t.default:t),/^['"].*['"]$/.test(t)&&(t=t.slice(1,-1)),e.hash&&(t+=e.hash),/["'() \t\n]|(%20)/.test(t)||e.needQuotes?'"'.concat(t.replace(/"/g,'\\"').replace(/\n/g,"\\n"),'"'):t):t}},81:t=>{"use strict";t.exports=function(t){return t[1]}},703:(t,e,n)=>{"use strict";var i=n(414);function r(){}function s(){}s.resetWarningCache=r,t.exports=function(){function t(t,e,n,r,s,a){if(a!==i){var o=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw o.name="Invariant Violation",o}}function e(){return t}t.isRequired=t;var n={array:t,bool:t,func:t,number:t,object:t,string:t,symbol:t,any:t,arrayOf:e,element:t,elementType:t,instanceOf:e,node:t,objectOf:e,oneOf:e,oneOfType:e,shape:e,exact:e,checkPropTypes:s,resetWarningCache:r};return n.PropTypes=n,n}},697:(t,e,n)=>{t.exports=n(703)()},414:t=>{"use strict";t.exports="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"},82:function(t,e,n){var i;i=function(t,e){return function(t){var e={};function n(i){if(e[i])return e[i].exports;var r=e[i]={i,l:!1,exports:{}};return t[i].call(r.exports,r,r.exports,n),r.l=!0,r.exports}return n.m=t,n.c=e,n.d=function(t,e,i){n.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:i})},n.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},n.t=function(t,e){if(1&e&&(t=n(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var i=Object.create(null);if(n.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var r in t)n.d(i,r,function(e){return t[e]}.bind(null,r));return i},n.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return n.d(e,"a",e),e},n.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},n.p="",n(n.s=4)}([function(t,e,n){t.exports=n(5)()},function(e,n){e.exports=t},function(t,n){t.exports=e},function(t,e){t.exports=function(t,e,n){var i=t.direction,r=t.value;switch(i){case"top":return n.top+re.bottom&&n.lefte.right;case"left":return n.left+re.bottom&&n.tope.right;case"bottom":return n.bottom-r>e.bottom&&n.lefte.right&&n.tope.right&&n.lefte.bottom}}},function(t,e,n){"use strict";n.r(e),n.d(e,"default",(function(){return v}));var i=n(1),r=n.n(i),s=n(2),a=n.n(s),o=n(0),l=n.n(o),c=n(3),h=n.n(c);function u(t){return u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},u(t)}function d(t,e){for(var n=0;n-1?function(){s||(s=setTimeout(a,r||0))}:function(){clearTimeout(s),s=setTimeout(a,i||0)},getLastTimeout:function(){return s}};t.addEventListener(e,o.fn),n.debounceCheck[e]=o})),g(m(n),"startWatching",(function(){n.debounceCheck||n.interval||(n.props.intervalCheck&&(n.interval=setInterval(n.check,n.props.intervalDelay)),n.props.scrollCheck&&n.addEventListener(n.getContainer(),"scroll",n.props.scrollDelay,n.props.scrollThrottle),n.props.resizeCheck&&n.addEventListener(window,"resize",n.props.resizeDelay,n.props.resizeThrottle),!n.props.delayedCall&&n.check())})),g(m(n),"stopWatching",(function(){if(n.debounceCheck)for(var t in n.debounceCheck)if(n.debounceCheck.hasOwnProperty(t)){var e=n.debounceCheck[t];clearTimeout(e.getLastTimeout()),e.target.removeEventListener(t,e.fn),n.debounceCheck[t]=null}n.debounceCheck=null,n.interval&&(n.interval=clearInterval(n.interval))})),g(m(n),"check",(function(){var t,e,i=n.node;if(!i)return n.state;if(t=function(t){return void 0===t.width&&(t.width=t.right-t.left),void 0===t.height&&(t.height=t.bottom-t.top),t}(n.roundRectDown(i.getBoundingClientRect())),n.props.containment){var r=n.props.containment.getBoundingClientRect();e={top:r.top,left:r.left,bottom:r.bottom,right:r.right}}else e={top:0,left:0,bottom:window.innerHeight||document.documentElement.clientHeight,right:window.innerWidth||document.documentElement.clientWidth};var s=n.props.offset||{};"object"===u(s)&&(e.top+=s.top||0,e.left+=s.left||0,e.bottom-=s.bottom||0,e.right-=s.right||0);var a={top:t.top>=e.top,left:t.left>=e.left,bottom:t.bottom<=e.bottom,right:t.right<=e.right},o=t.height>0&&t.width>0,l=o&&a.top&&a.left&&a.bottom&&a.right;if(o&&n.props.partialVisibility){var c=t.top<=e.bottom&&t.bottom>=e.top&&t.left<=e.right&&t.right>=e.left;"string"==typeof n.props.partialVisibility&&(c=a[n.props.partialVisibility]),l=n.props.minTopValue?c&&t.top<=e.bottom-n.props.minTopValue:c}"string"==typeof s.direction&&"number"==typeof s.value&&(console.warn("[notice] offset.direction and offset.value have been deprecated. They still work for now, but will be removed in next major version. Please upgrade to the new syntax: { %s: %d }",s.direction,s.value),l=h()(s,t,e));var d=n.state;return n.state.isVisible!==l&&(d={isVisible:l,visibilityRect:a},n.setState(d),n.props.onChange&&n.props.onChange(l)),d})),n.state={isVisible:null,visibilityRect:{}},n}var n,i;return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&f(t,e)}(e,t),n=e,(i=[{key:"componentDidMount",value:function(){this.node=a.a.findDOMNode(this),this.props.active&&this.startWatching()}},{key:"componentWillUnmount",value:function(){this.stopWatching()}},{key:"componentDidUpdate",value:function(t){this.node=a.a.findDOMNode(this),this.props.active&&!t.active?(this.setState({isVisible:null,visibilityRect:{}}),this.startWatching()):this.props.active||this.stopWatching()}},{key:"roundRectDown",value:function(t){return{top:Math.floor(t.top),left:Math.floor(t.left),bottom:Math.floor(t.bottom),right:Math.floor(t.right)}}},{key:"render",value:function(){return this.props.children instanceof Function?this.props.children({isVisible:this.state.isVisible,visibilityRect:this.state.visibilityRect}):r.a.Children.only(this.props.children)}}])&&d(n.prototype,i),e}(r.a.Component);g(v,"defaultProps",{active:!0,partialVisibility:!1,minTopValue:0,scrollCheck:!1,scrollDelay:250,scrollThrottle:-1,resizeCheck:!1,resizeDelay:250,resizeThrottle:-1,intervalCheck:!0,intervalDelay:100,delayedCall:!1,offset:{},containment:null,children:r.a.createElement("span",null)}),g(v,"propTypes",{onChange:l.a.func,active:l.a.bool,partialVisibility:l.a.oneOfType([l.a.bool,l.a.oneOf(["top","right","bottom","left"])]),delayedCall:l.a.bool,offset:l.a.oneOfType([l.a.shape({top:l.a.number,left:l.a.number,bottom:l.a.number,right:l.a.number}),l.a.shape({direction:l.a.oneOf(["top","right","bottom","left"]),value:l.a.number})]),scrollCheck:l.a.bool,scrollDelay:l.a.number,scrollThrottle:l.a.number,resizeCheck:l.a.bool,resizeDelay:l.a.number,resizeThrottle:l.a.number,intervalCheck:l.a.bool,intervalDelay:l.a.number,containment:"undefined"!=typeof window?l.a.instanceOf(window.Element):l.a.any,children:l.a.oneOfType([l.a.element,l.a.func]),minTopValue:l.a.number})},function(t,e,n){"use strict";var i=n(6);function r(){}function s(){}s.resetWarningCache=r,t.exports=function(){function t(t,e,n,r,s,a){if(a!==i){var o=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw o.name="Invariant Violation",o}}function e(){return t}t.isRequired=t;var n={array:t,bool:t,func:t,number:t,object:t,string:t,symbol:t,any:t,arrayOf:e,element:t,elementType:t,instanceOf:e,node:t,objectOf:e,oneOf:e,oneOfType:e,shape:e,exact:e,checkPropTypes:s,resetWarningCache:r};return n.PropTypes=n,n}},function(t,e,n){"use strict";t.exports="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"}])},t.exports=i(n(787),n(156))},269:(t,e,n)=>{var i=n(379),r=n(355);"string"==typeof(r=r.__esModule?r.default:r)&&(r=[[t.id,r,""]]);i(r,{insert:"head",singleton:!1}),t.exports=r.locals||{}},192:(t,e,n)=>{var i=n(379),r=n(329);"string"==typeof(r=r.__esModule?r.default:r)&&(r=[[t.id,r,""]]);i(r,{insert:"head",singleton:!1}),t.exports=r.locals||{}},266:(t,e,n)=>{var i=n(379),r=n(238);"string"==typeof(r=r.__esModule?r.default:r)&&(r=[[t.id,r,""]]);i(r,{insert:"head",singleton:!1}),t.exports=r.locals||{}},193:(t,e,n)=>{var i=n(379),r=n(811);"string"==typeof(r=r.__esModule?r.default:r)&&(r=[[t.id,r,""]]);i(r,{insert:"head",singleton:!1}),t.exports=r.locals||{}},380:(t,e,n)=>{var i=n(379),r=n(427);"string"==typeof(r=r.__esModule?r.default:r)&&(r=[[t.id,r,""]]);i(r,{insert:"head",singleton:!1}),t.exports=r.locals||{}},379:(t,e,n)=>{"use strict";var i,r=function(){var t={};return function(e){if(void 0===t[e]){var n=document.querySelector(e);if(window.HTMLIFrameElement&&n instanceof window.HTMLIFrameElement)try{n=n.contentDocument.head}catch(t){n=null}t[e]=n}return t[e]}}(),s=[];function a(t){for(var e=-1,n=0;n{"use strict";t.exports=n.p+"28c58d40210ac28e2a3e.png"},787:e=>{"use strict";e.exports=t},156:t=>{"use strict";t.exports=e},232:(t,e)=>{"use strict";const n="169",i=100,r=204,s=205,a="attached",o="detached",l=300,c=301,h=302,u=303,d=304,p=306,m=1e3,f=1001,g=1002,v=1003,_=1004,y=1005,x=1006,M=1007,S=1008,b=1009,w=1010,T=1011,E=1012,A=1013,C=1014,R=1015,P=1016,I=1017,L=1018,U=1020,D=35902,N=1021,O=1022,F=1023,B=1024,z=1025,k=1026,V=1027,H=1028,G=1029,W=1030,X=1031,j=1033,q=33776,Y=33777,Z=33778,J=33779,K=35840,$=35841,Q=35842,tt=35843,et=36196,nt=37492,it=37496,rt=37808,st=37809,at=37810,ot=37811,lt=37812,ct=37813,ht=37814,ut=37815,dt=37816,pt=37817,mt=37818,ft=37819,gt=37820,vt=37821,_t=36492,yt=36494,xt=36495,Mt=36283,St=36284,bt=36285,wt=36286,Tt=2300,Et=2301,At=2302,Ct=2400,Rt=2401,Pt=2402,It=2501,Lt="",Ut="srgb",Dt="srgb-linear",Nt="display-p3",Ot="display-p3-linear",Ft="linear",Bt="srgb",zt="rec709",kt="p3",Vt=7680,Ht=35044,Gt="300 es",Wt=2e3,Xt=2001;class jt{addEventListener(t,e){void 0===this._listeners&&(this._listeners={});const n=this._listeners;void 0===n[t]&&(n[t]=[]),-1===n[t].indexOf(e)&&n[t].push(e)}hasEventListener(t,e){if(void 0===this._listeners)return!1;const n=this._listeners;return void 0!==n[t]&&-1!==n[t].indexOf(e)}removeEventListener(t,e){if(void 0===this._listeners)return;const n=this._listeners[t];if(void 0!==n){const t=n.indexOf(e);-1!==t&&n.splice(t,1)}}dispatchEvent(t){if(void 0===this._listeners)return;const e=this._listeners[t.type];if(void 0!==e){t.target=this;const n=e.slice(0);for(let e=0,i=n.length;e>8&255]+qt[t>>16&255]+qt[t>>24&255]+"-"+qt[255&e]+qt[e>>8&255]+"-"+qt[e>>16&15|64]+qt[e>>24&255]+"-"+qt[63&n|128]+qt[n>>8&255]+"-"+qt[n>>16&255]+qt[n>>24&255]+qt[255&i]+qt[i>>8&255]+qt[i>>16&255]+qt[i>>24&255]).toLowerCase()}function $t(t,e,n){return Math.max(e,Math.min(n,t))}function Qt(t,e){return(t%e+e)%e}function te(t,e,n){return(1-n)*t+n*e}function ee(t,e){switch(e.constructor){case Float32Array:return t;case Uint32Array:return t/4294967295;case Uint16Array:return t/65535;case Uint8Array:return t/255;case Int32Array:return Math.max(t/2147483647,-1);case Int16Array:return Math.max(t/32767,-1);case Int8Array:return Math.max(t/127,-1);default:throw new Error("Invalid component type.")}}function ne(t,e){switch(e.constructor){case Float32Array:return t;case Uint32Array:return Math.round(4294967295*t);case Uint16Array:return Math.round(65535*t);case Uint8Array:return Math.round(255*t);case Int32Array:return Math.round(2147483647*t);case Int16Array:return Math.round(32767*t);case Int8Array:return Math.round(127*t);default:throw new Error("Invalid component type.")}}const ie={DEG2RAD:Zt,RAD2DEG:Jt,generateUUID:Kt,clamp:$t,euclideanModulo:Qt,mapLinear:function(t,e,n,i,r){return i+(t-e)*(r-i)/(n-e)},inverseLerp:function(t,e,n){return t!==e?(n-t)/(e-t):0},lerp:te,damp:function(t,e,n,i){return te(t,e,1-Math.exp(-n*i))},pingpong:function(t,e=1){return e-Math.abs(Qt(t,2*e)-e)},smoothstep:function(t,e,n){return t<=e?0:t>=n?1:(t=(t-e)/(n-e))*t*(3-2*t)},smootherstep:function(t,e,n){return t<=e?0:t>=n?1:(t=(t-e)/(n-e))*t*t*(t*(6*t-15)+10)},randInt:function(t,e){return t+Math.floor(Math.random()*(e-t+1))},randFloat:function(t,e){return t+Math.random()*(e-t)},randFloatSpread:function(t){return t*(.5-Math.random())},seededRandom:function(t){void 0!==t&&(Yt=t);let e=Yt+=1831565813;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296},degToRad:function(t){return t*Zt},radToDeg:function(t){return t*Jt},isPowerOfTwo:function(t){return 0==(t&t-1)&&0!==t},ceilPowerOfTwo:function(t){return Math.pow(2,Math.ceil(Math.log(t)/Math.LN2))},floorPowerOfTwo:function(t){return Math.pow(2,Math.floor(Math.log(t)/Math.LN2))},setQuaternionFromProperEuler:function(t,e,n,i,r){const s=Math.cos,a=Math.sin,o=s(n/2),l=a(n/2),c=s((e+i)/2),h=a((e+i)/2),u=s((e-i)/2),d=a((e-i)/2),p=s((i-e)/2),m=a((i-e)/2);switch(r){case"XYX":t.set(o*h,l*u,l*d,o*c);break;case"YZY":t.set(l*d,o*h,l*u,o*c);break;case"ZXZ":t.set(l*u,l*d,o*h,o*c);break;case"XZX":t.set(o*h,l*m,l*p,o*c);break;case"YXY":t.set(l*p,o*h,l*m,o*c);break;case"ZYZ":t.set(l*m,l*p,o*h,o*c);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+r)}},normalize:ne,denormalize:ee};class re{constructor(t=0,e=0){re.prototype.isVector2=!0,this.x=t,this.y=e}get width(){return this.x}set width(t){this.x=t}get height(){return this.y}set height(t){this.y=t}set(t,e){return this.x=t,this.y=e,this}setScalar(t){return this.x=t,this.y=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y)}copy(t){return this.x=t.x,this.y=t.y,this}add(t){return this.x+=t.x,this.y+=t.y,this}addScalar(t){return this.x+=t,this.y+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this}subScalar(t){return this.x-=t,this.y-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this}multiply(t){return this.x*=t.x,this.y*=t.y,this}multiplyScalar(t){return this.x*=t,this.y*=t,this}divide(t){return this.x/=t.x,this.y/=t.y,this}divideScalar(t){return this.multiplyScalar(1/t)}applyMatrix3(t){const e=this.x,n=this.y,i=t.elements;return this.x=i[0]*e+i[3]*n+i[6],this.y=i[1]*e+i[4]*n+i[7],this}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this}clamp(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this}clampScalar(t,e){return this.x=Math.max(t,Math.min(e,this.x)),this.y=Math.max(t,Math.min(e,this.y)),this}clampLength(t,e){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Math.max(t,Math.min(e,n)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(t){return this.x*t.x+this.y*t.y}cross(t){return this.x*t.y-this.y*t.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(t){const e=Math.sqrt(this.lengthSq()*t.lengthSq());if(0===e)return Math.PI/2;const n=this.dot(t)/e;return Math.acos($t(n,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){const e=this.x-t.x,n=this.y-t.y;return e*e+n*n}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this}lerpVectors(t,e,n){return this.x=t.x+(e.x-t.x)*n,this.y=t.y+(e.y-t.y)*n,this}equals(t){return t.x===this.x&&t.y===this.y}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t}fromBufferAttribute(t,e){return this.x=t.getX(e),this.y=t.getY(e),this}rotateAround(t,e){const n=Math.cos(e),i=Math.sin(e),r=this.x-t.x,s=this.y-t.y;return this.x=r*n-s*i+t.x,this.y=r*i+s*n+t.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class se{constructor(t,e,n,i,r,s,a,o,l){se.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],void 0!==t&&this.set(t,e,n,i,r,s,a,o,l)}set(t,e,n,i,r,s,a,o,l){const c=this.elements;return c[0]=t,c[1]=i,c[2]=a,c[3]=e,c[4]=r,c[5]=o,c[6]=n,c[7]=s,c[8]=l,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(t){const e=this.elements,n=t.elements;return e[0]=n[0],e[1]=n[1],e[2]=n[2],e[3]=n[3],e[4]=n[4],e[5]=n[5],e[6]=n[6],e[7]=n[7],e[8]=n[8],this}extractBasis(t,e,n){return t.setFromMatrix3Column(this,0),e.setFromMatrix3Column(this,1),n.setFromMatrix3Column(this,2),this}setFromMatrix4(t){const e=t.elements;return this.set(e[0],e[4],e[8],e[1],e[5],e[9],e[2],e[6],e[10]),this}multiply(t){return this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){const n=t.elements,i=e.elements,r=this.elements,s=n[0],a=n[3],o=n[6],l=n[1],c=n[4],h=n[7],u=n[2],d=n[5],p=n[8],m=i[0],f=i[3],g=i[6],v=i[1],_=i[4],y=i[7],x=i[2],M=i[5],S=i[8];return r[0]=s*m+a*v+o*x,r[3]=s*f+a*_+o*M,r[6]=s*g+a*y+o*S,r[1]=l*m+c*v+h*x,r[4]=l*f+c*_+h*M,r[7]=l*g+c*y+h*S,r[2]=u*m+d*v+p*x,r[5]=u*f+d*_+p*M,r[8]=u*g+d*y+p*S,this}multiplyScalar(t){const e=this.elements;return e[0]*=t,e[3]*=t,e[6]*=t,e[1]*=t,e[4]*=t,e[7]*=t,e[2]*=t,e[5]*=t,e[8]*=t,this}determinant(){const t=this.elements,e=t[0],n=t[1],i=t[2],r=t[3],s=t[4],a=t[5],o=t[6],l=t[7],c=t[8];return e*s*c-e*a*l-n*r*c+n*a*o+i*r*l-i*s*o}invert(){const t=this.elements,e=t[0],n=t[1],i=t[2],r=t[3],s=t[4],a=t[5],o=t[6],l=t[7],c=t[8],h=c*s-a*l,u=a*o-c*r,d=l*r-s*o,p=e*h+n*u+i*d;if(0===p)return this.set(0,0,0,0,0,0,0,0,0);const m=1/p;return t[0]=h*m,t[1]=(i*l-c*n)*m,t[2]=(a*n-i*s)*m,t[3]=u*m,t[4]=(c*e-i*o)*m,t[5]=(i*r-a*e)*m,t[6]=d*m,t[7]=(n*o-l*e)*m,t[8]=(s*e-n*r)*m,this}transpose(){let t;const e=this.elements;return t=e[1],e[1]=e[3],e[3]=t,t=e[2],e[2]=e[6],e[6]=t,t=e[5],e[5]=e[7],e[7]=t,this}getNormalMatrix(t){return this.setFromMatrix4(t).invert().transpose()}transposeIntoArray(t){const e=this.elements;return t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8],this}setUvTransform(t,e,n,i,r,s,a){const o=Math.cos(r),l=Math.sin(r);return this.set(n*o,n*l,-n*(o*s+l*a)+s+t,-i*l,i*o,-i*(-l*s+o*a)+a+e,0,0,1),this}scale(t,e){return this.premultiply(ae.makeScale(t,e)),this}rotate(t){return this.premultiply(ae.makeRotation(-t)),this}translate(t,e){return this.premultiply(ae.makeTranslation(t,e)),this}makeTranslation(t,e){return t.isVector2?this.set(1,0,t.x,0,1,t.y,0,0,1):this.set(1,0,t,0,1,e,0,0,1),this}makeRotation(t){const e=Math.cos(t),n=Math.sin(t);return this.set(e,-n,0,n,e,0,0,0,1),this}makeScale(t,e){return this.set(t,0,0,0,e,0,0,0,1),this}equals(t){const e=this.elements,n=t.elements;for(let t=0;t<9;t++)if(e[t]!==n[t])return!1;return!0}fromArray(t,e=0){for(let n=0;n<9;n++)this.elements[n]=t[n+e];return this}toArray(t=[],e=0){const n=this.elements;return t[e]=n[0],t[e+1]=n[1],t[e+2]=n[2],t[e+3]=n[3],t[e+4]=n[4],t[e+5]=n[5],t[e+6]=n[6],t[e+7]=n[7],t[e+8]=n[8],t}clone(){return(new this.constructor).fromArray(this.elements)}}const ae=new se;function oe(t){for(let e=t.length-1;e>=0;--e)if(t[e]>=65535)return!0;return!1}const le={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array};function ce(t,e){return new le[t](e)}function he(t){return document.createElementNS("http://www.w3.org/1999/xhtml",t)}function ue(){const t=he("canvas");return t.style.display="block",t}const de={};function pe(t){t in de||(de[t]=!0,console.warn(t))}const me=(new se).set(.8224621,.177538,0,.0331941,.9668058,0,.0170827,.0723974,.9105199),fe=(new se).set(1.2249401,-.2249404,0,-.0420569,1.0420571,0,-.0196376,-.0786361,1.0982735),ge={[Dt]:{transfer:Ft,primaries:zt,luminanceCoefficients:[.2126,.7152,.0722],toReference:t=>t,fromReference:t=>t},[Ut]:{transfer:Bt,primaries:zt,luminanceCoefficients:[.2126,.7152,.0722],toReference:t=>t.convertSRGBToLinear(),fromReference:t=>t.convertLinearToSRGB()},[Ot]:{transfer:Ft,primaries:kt,luminanceCoefficients:[.2289,.6917,.0793],toReference:t=>t.applyMatrix3(fe),fromReference:t=>t.applyMatrix3(me)},[Nt]:{transfer:Bt,primaries:kt,luminanceCoefficients:[.2289,.6917,.0793],toReference:t=>t.convertSRGBToLinear().applyMatrix3(fe),fromReference:t=>t.applyMatrix3(me).convertLinearToSRGB()}},ve=new Set([Dt,Ot]),_e={enabled:!0,_workingColorSpace:Dt,get workingColorSpace(){return this._workingColorSpace},set workingColorSpace(t){if(!ve.has(t))throw new Error(`Unsupported working color space, "${t}".`);this._workingColorSpace=t},convert:function(t,e,n){if(!1===this.enabled||e===n||!e||!n)return t;const i=ge[e].toReference;return(0,ge[n].fromReference)(i(t))},fromWorkingColorSpace:function(t,e){return this.convert(t,this._workingColorSpace,e)},toWorkingColorSpace:function(t,e){return this.convert(t,e,this._workingColorSpace)},getPrimaries:function(t){return ge[t].primaries},getTransfer:function(t){return t===Lt?Ft:ge[t].transfer},getLuminanceCoefficients:function(t,e=this._workingColorSpace){return t.fromArray(ge[e].luminanceCoefficients)}};function ye(t){return t<.04045?.0773993808*t:Math.pow(.9478672986*t+.0521327014,2.4)}function xe(t){return t<.0031308?12.92*t:1.055*Math.pow(t,.41666)-.055}let Me;class Se{static getDataURL(t){if(/^data:/i.test(t.src))return t.src;if("undefined"==typeof HTMLCanvasElement)return t.src;let e;if(t instanceof HTMLCanvasElement)e=t;else{void 0===Me&&(Me=he("canvas")),Me.width=t.width,Me.height=t.height;const n=Me.getContext("2d");t instanceof ImageData?n.putImageData(t,0,0):n.drawImage(t,0,0,t.width,t.height),e=Me}return e.width>2048||e.height>2048?(console.warn("THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons",t),e.toDataURL("image/jpeg",.6)):e.toDataURL("image/png")}static sRGBToLinear(t){if("undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&t instanceof ImageBitmap){const e=he("canvas");e.width=t.width,e.height=t.height;const n=e.getContext("2d");n.drawImage(t,0,0,t.width,t.height);const i=n.getImageData(0,0,t.width,t.height),r=i.data;for(let t=0;t0&&(n.userData=this.userData),e||(t.textures[this.uuid]=n),n}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(t){if(this.mapping!==l)return t;if(t.applyMatrix3(this.matrix),t.x<0||t.x>1)switch(this.wrapS){case m:t.x=t.x-Math.floor(t.x);break;case f:t.x=t.x<0?0:1;break;case g:1===Math.abs(Math.floor(t.x)%2)?t.x=Math.ceil(t.x)-t.x:t.x=t.x-Math.floor(t.x)}if(t.y<0||t.y>1)switch(this.wrapT){case m:t.y=t.y-Math.floor(t.y);break;case f:t.y=t.y<0?0:1;break;case g:1===Math.abs(Math.floor(t.y)%2)?t.y=Math.ceil(t.y)-t.y:t.y=t.y-Math.floor(t.y)}return this.flipY&&(t.y=1-t.y),t}set needsUpdate(t){!0===t&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(t){!0===t&&this.pmremVersion++}}Ae.DEFAULT_IMAGE=null,Ae.DEFAULT_MAPPING=l,Ae.DEFAULT_ANISOTROPY=1;class Ce{constructor(t=0,e=0,n=0,i=1){Ce.prototype.isVector4=!0,this.x=t,this.y=e,this.z=n,this.w=i}get width(){return this.z}set width(t){this.z=t}get height(){return this.w}set height(t){this.w=t}set(t,e,n,i){return this.x=t,this.y=e,this.z=n,this.w=i,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this.w=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setW(t){return this.w=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;case 3:this.w=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=void 0!==t.w?t.w:1,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this.w+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this.w=t.w+e.w,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this.w+=t.w*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this.w-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this.w=t.w-e.w,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this}applyMatrix4(t){const e=this.x,n=this.y,i=this.z,r=this.w,s=t.elements;return this.x=s[0]*e+s[4]*n+s[8]*i+s[12]*r,this.y=s[1]*e+s[5]*n+s[9]*i+s[13]*r,this.z=s[2]*e+s[6]*n+s[10]*i+s[14]*r,this.w=s[3]*e+s[7]*n+s[11]*i+s[15]*r,this}divideScalar(t){return this.multiplyScalar(1/t)}setAxisAngleFromQuaternion(t){this.w=2*Math.acos(t.w);const e=Math.sqrt(1-t.w*t.w);return e<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=t.x/e,this.y=t.y/e,this.z=t.z/e),this}setAxisAngleFromRotationMatrix(t){let e,n,i,r;const s=.01,a=.1,o=t.elements,l=o[0],c=o[4],h=o[8],u=o[1],d=o[5],p=o[9],m=o[2],f=o[6],g=o[10];if(Math.abs(c-u)o&&t>v?tv?o=0?1:-1,i=1-e*e;if(i>Number.EPSILON){const r=Math.sqrt(i),s=Math.atan2(r,e*n);t=Math.sin(t*s)/r,a=Math.sin(a*s)/r}const r=a*n;if(o=o*t+u*r,l=l*t+d*r,c=c*t+p*r,h=h*t+m*r,t===1-a){const t=1/Math.sqrt(o*o+l*l+c*c+h*h);o*=t,l*=t,c*=t,h*=t}}t[e]=o,t[e+1]=l,t[e+2]=c,t[e+3]=h}static multiplyQuaternionsFlat(t,e,n,i,r,s){const a=n[i],o=n[i+1],l=n[i+2],c=n[i+3],h=r[s],u=r[s+1],d=r[s+2],p=r[s+3];return t[e]=a*p+c*h+o*d-l*u,t[e+1]=o*p+c*u+l*h-a*d,t[e+2]=l*p+c*d+a*u-o*h,t[e+3]=c*p-a*h-o*u-l*d,t}get x(){return this._x}set x(t){this._x=t,this._onChangeCallback()}get y(){return this._y}set y(t){this._y=t,this._onChangeCallback()}get z(){return this._z}set z(t){this._z=t,this._onChangeCallback()}get w(){return this._w}set w(t){this._w=t,this._onChangeCallback()}set(t,e,n,i){return this._x=t,this._y=e,this._z=n,this._w=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(t){return this._x=t.x,this._y=t.y,this._z=t.z,this._w=t.w,this._onChangeCallback(),this}setFromEuler(t,e=!0){const n=t._x,i=t._y,r=t._z,s=t._order,a=Math.cos,o=Math.sin,l=a(n/2),c=a(i/2),h=a(r/2),u=o(n/2),d=o(i/2),p=o(r/2);switch(s){case"XYZ":this._x=u*c*h+l*d*p,this._y=l*d*h-u*c*p,this._z=l*c*p+u*d*h,this._w=l*c*h-u*d*p;break;case"YXZ":this._x=u*c*h+l*d*p,this._y=l*d*h-u*c*p,this._z=l*c*p-u*d*h,this._w=l*c*h+u*d*p;break;case"ZXY":this._x=u*c*h-l*d*p,this._y=l*d*h+u*c*p,this._z=l*c*p+u*d*h,this._w=l*c*h-u*d*p;break;case"ZYX":this._x=u*c*h-l*d*p,this._y=l*d*h+u*c*p,this._z=l*c*p-u*d*h,this._w=l*c*h+u*d*p;break;case"YZX":this._x=u*c*h+l*d*p,this._y=l*d*h+u*c*p,this._z=l*c*p-u*d*h,this._w=l*c*h-u*d*p;break;case"XZY":this._x=u*c*h-l*d*p,this._y=l*d*h-u*c*p,this._z=l*c*p+u*d*h,this._w=l*c*h+u*d*p;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+s)}return!0===e&&this._onChangeCallback(),this}setFromAxisAngle(t,e){const n=e/2,i=Math.sin(n);return this._x=t.x*i,this._y=t.y*i,this._z=t.z*i,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(t){const e=t.elements,n=e[0],i=e[4],r=e[8],s=e[1],a=e[5],o=e[9],l=e[2],c=e[6],h=e[10],u=n+a+h;if(u>0){const t=.5/Math.sqrt(u+1);this._w=.25/t,this._x=(c-o)*t,this._y=(r-l)*t,this._z=(s-i)*t}else if(n>a&&n>h){const t=2*Math.sqrt(1+n-a-h);this._w=(c-o)/t,this._x=.25*t,this._y=(i+s)/t,this._z=(r+l)/t}else if(a>h){const t=2*Math.sqrt(1+a-n-h);this._w=(r-l)/t,this._x=(i+s)/t,this._y=.25*t,this._z=(o+c)/t}else{const t=2*Math.sqrt(1+h-n-a);this._w=(s-i)/t,this._x=(r+l)/t,this._y=(o+c)/t,this._z=.25*t}return this._onChangeCallback(),this}setFromUnitVectors(t,e){let n=t.dot(e)+1;return nMath.abs(t.z)?(this._x=-t.y,this._y=t.x,this._z=0,this._w=n):(this._x=0,this._y=-t.z,this._z=t.y,this._w=n)):(this._x=t.y*e.z-t.z*e.y,this._y=t.z*e.x-t.x*e.z,this._z=t.x*e.y-t.y*e.x,this._w=n),this.normalize()}angleTo(t){return 2*Math.acos(Math.abs($t(this.dot(t),-1,1)))}rotateTowards(t,e){const n=this.angleTo(t);if(0===n)return this;const i=Math.min(1,e/n);return this.slerp(t,i),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(t){return this._x*t._x+this._y*t._y+this._z*t._z+this._w*t._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let t=this.length();return 0===t?(this._x=0,this._y=0,this._z=0,this._w=1):(t=1/t,this._x=this._x*t,this._y=this._y*t,this._z=this._z*t,this._w=this._w*t),this._onChangeCallback(),this}multiply(t){return this.multiplyQuaternions(this,t)}premultiply(t){return this.multiplyQuaternions(t,this)}multiplyQuaternions(t,e){const n=t._x,i=t._y,r=t._z,s=t._w,a=e._x,o=e._y,l=e._z,c=e._w;return this._x=n*c+s*a+i*l-r*o,this._y=i*c+s*o+r*a-n*l,this._z=r*c+s*l+n*o-i*a,this._w=s*c-n*a-i*o-r*l,this._onChangeCallback(),this}slerp(t,e){if(0===e)return this;if(1===e)return this.copy(t);const n=this._x,i=this._y,r=this._z,s=this._w;let a=s*t._w+n*t._x+i*t._y+r*t._z;if(a<0?(this._w=-t._w,this._x=-t._x,this._y=-t._y,this._z=-t._z,a=-a):this.copy(t),a>=1)return this._w=s,this._x=n,this._y=i,this._z=r,this;const o=1-a*a;if(o<=Number.EPSILON){const t=1-e;return this._w=t*s+e*this._w,this._x=t*n+e*this._x,this._y=t*i+e*this._y,this._z=t*r+e*this._z,this.normalize(),this}const l=Math.sqrt(o),c=Math.atan2(l,a),h=Math.sin((1-e)*c)/l,u=Math.sin(e*c)/l;return this._w=s*h+this._w*u,this._x=n*h+this._x*u,this._y=i*h+this._y*u,this._z=r*h+this._z*u,this._onChangeCallback(),this}slerpQuaternions(t,e,n){return this.copy(t).slerp(e,n)}random(){const t=2*Math.PI*Math.random(),e=2*Math.PI*Math.random(),n=Math.random(),i=Math.sqrt(1-n),r=Math.sqrt(n);return this.set(i*Math.sin(t),i*Math.cos(t),r*Math.sin(e),r*Math.cos(e))}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._w===this._w}fromArray(t,e=0){return this._x=t[e],this._y=t[e+1],this._z=t[e+2],this._w=t[e+3],this._onChangeCallback(),this}toArray(t=[],e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._w,t}fromBufferAttribute(t,e){return this._x=t.getX(e),this._y=t.getY(e),this._z=t.getZ(e),this._w=t.getW(e),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class De{constructor(t=0,e=0,n=0){De.prototype.isVector3=!0,this.x=t,this.y=e,this.z=n}set(t,e,n){return void 0===n&&(n=this.z),this.x=t,this.y=e,this.z=n,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this}multiplyVectors(t,e){return this.x=t.x*e.x,this.y=t.y*e.y,this.z=t.z*e.z,this}applyEuler(t){return this.applyQuaternion(Oe.setFromEuler(t))}applyAxisAngle(t,e){return this.applyQuaternion(Oe.setFromAxisAngle(t,e))}applyMatrix3(t){const e=this.x,n=this.y,i=this.z,r=t.elements;return this.x=r[0]*e+r[3]*n+r[6]*i,this.y=r[1]*e+r[4]*n+r[7]*i,this.z=r[2]*e+r[5]*n+r[8]*i,this}applyNormalMatrix(t){return this.applyMatrix3(t).normalize()}applyMatrix4(t){const e=this.x,n=this.y,i=this.z,r=t.elements,s=1/(r[3]*e+r[7]*n+r[11]*i+r[15]);return this.x=(r[0]*e+r[4]*n+r[8]*i+r[12])*s,this.y=(r[1]*e+r[5]*n+r[9]*i+r[13])*s,this.z=(r[2]*e+r[6]*n+r[10]*i+r[14])*s,this}applyQuaternion(t){const e=this.x,n=this.y,i=this.z,r=t.x,s=t.y,a=t.z,o=t.w,l=2*(s*i-a*n),c=2*(a*e-r*i),h=2*(r*n-s*e);return this.x=e+o*l+s*h-a*c,this.y=n+o*c+a*l-r*h,this.z=i+o*h+r*c-s*l,this}project(t){return this.applyMatrix4(t.matrixWorldInverse).applyMatrix4(t.projectionMatrix)}unproject(t){return this.applyMatrix4(t.projectionMatrixInverse).applyMatrix4(t.matrixWorld)}transformDirection(t){const e=this.x,n=this.y,i=this.z,r=t.elements;return this.x=r[0]*e+r[4]*n+r[8]*i,this.y=r[1]*e+r[5]*n+r[9]*i,this.z=r[2]*e+r[6]*n+r[10]*i,this.normalize()}divide(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this}divideScalar(t){return this.multiplyScalar(1/t)}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this}clamp(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this.z=Math.max(t.z,Math.min(e.z,this.z)),this}clampScalar(t,e){return this.x=Math.max(t,Math.min(e,this.x)),this.y=Math.max(t,Math.min(e,this.y)),this.z=Math.max(t,Math.min(e,this.z)),this}clampLength(t,e){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Math.max(t,Math.min(e,n)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this}lerpVectors(t,e,n){return this.x=t.x+(e.x-t.x)*n,this.y=t.y+(e.y-t.y)*n,this.z=t.z+(e.z-t.z)*n,this}cross(t){return this.crossVectors(this,t)}crossVectors(t,e){const n=t.x,i=t.y,r=t.z,s=e.x,a=e.y,o=e.z;return this.x=i*o-r*a,this.y=r*s-n*o,this.z=n*a-i*s,this}projectOnVector(t){const e=t.lengthSq();if(0===e)return this.set(0,0,0);const n=t.dot(this)/e;return this.copy(t).multiplyScalar(n)}projectOnPlane(t){return Ne.copy(this).projectOnVector(t),this.sub(Ne)}reflect(t){return this.sub(Ne.copy(t).multiplyScalar(2*this.dot(t)))}angleTo(t){const e=Math.sqrt(this.lengthSq()*t.lengthSq());if(0===e)return Math.PI/2;const n=this.dot(t)/e;return Math.acos($t(n,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){const e=this.x-t.x,n=this.y-t.y,i=this.z-t.z;return e*e+n*n+i*i}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)+Math.abs(this.z-t.z)}setFromSpherical(t){return this.setFromSphericalCoords(t.radius,t.phi,t.theta)}setFromSphericalCoords(t,e,n){const i=Math.sin(e)*t;return this.x=i*Math.sin(n),this.y=Math.cos(e)*t,this.z=i*Math.cos(n),this}setFromCylindrical(t){return this.setFromCylindricalCoords(t.radius,t.theta,t.y)}setFromCylindricalCoords(t,e,n){return this.x=t*Math.sin(e),this.y=n,this.z=t*Math.cos(e),this}setFromMatrixPosition(t){const e=t.elements;return this.x=e[12],this.y=e[13],this.z=e[14],this}setFromMatrixScale(t){const e=this.setFromMatrixColumn(t,0).length(),n=this.setFromMatrixColumn(t,1).length(),i=this.setFromMatrixColumn(t,2).length();return this.x=e,this.y=n,this.z=i,this}setFromMatrixColumn(t,e){return this.fromArray(t.elements,4*e)}setFromMatrix3Column(t,e){return this.fromArray(t.elements,3*e)}setFromEuler(t){return this.x=t._x,this.y=t._y,this.z=t._z,this}setFromColor(t){return this.x=t.r,this.y=t.g,this.z=t.b,this}equals(t){return t.x===this.x&&t.y===this.y&&t.z===this.z}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this.z=t[e+2],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t}fromBufferAttribute(t,e){return this.x=t.getX(e),this.y=t.getY(e),this.z=t.getZ(e),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const t=Math.random()*Math.PI*2,e=2*Math.random()-1,n=Math.sqrt(1-e*e);return this.x=n*Math.cos(t),this.y=e,this.z=n*Math.sin(t),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const Ne=new De,Oe=new Ue;class Fe{constructor(t=new De(1/0,1/0,1/0),e=new De(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=t,this.max=e}set(t,e){return this.min.copy(t),this.max.copy(e),this}setFromArray(t){this.makeEmpty();for(let e=0,n=t.length;e=this.min.x&&t.x<=this.max.x&&t.y>=this.min.y&&t.y<=this.max.y&&t.z>=this.min.z&&t.z<=this.max.z}containsBox(t){return this.min.x<=t.min.x&&t.max.x<=this.max.x&&this.min.y<=t.min.y&&t.max.y<=this.max.y&&this.min.z<=t.min.z&&t.max.z<=this.max.z}getParameter(t,e){return e.set((t.x-this.min.x)/(this.max.x-this.min.x),(t.y-this.min.y)/(this.max.y-this.min.y),(t.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(t){return t.max.x>=this.min.x&&t.min.x<=this.max.x&&t.max.y>=this.min.y&&t.min.y<=this.max.y&&t.max.z>=this.min.z&&t.min.z<=this.max.z}intersectsSphere(t){return this.clampPoint(t.center,ze),ze.distanceToSquared(t.center)<=t.radius*t.radius}intersectsPlane(t){let e,n;return t.normal.x>0?(e=t.normal.x*this.min.x,n=t.normal.x*this.max.x):(e=t.normal.x*this.max.x,n=t.normal.x*this.min.x),t.normal.y>0?(e+=t.normal.y*this.min.y,n+=t.normal.y*this.max.y):(e+=t.normal.y*this.max.y,n+=t.normal.y*this.min.y),t.normal.z>0?(e+=t.normal.z*this.min.z,n+=t.normal.z*this.max.z):(e+=t.normal.z*this.max.z,n+=t.normal.z*this.min.z),e<=-t.constant&&n>=-t.constant}intersectsTriangle(t){if(this.isEmpty())return!1;this.getCenter(qe),Ye.subVectors(this.max,qe),Ve.subVectors(t.a,qe),He.subVectors(t.b,qe),Ge.subVectors(t.c,qe),We.subVectors(He,Ve),Xe.subVectors(Ge,He),je.subVectors(Ve,Ge);let e=[0,-We.z,We.y,0,-Xe.z,Xe.y,0,-je.z,je.y,We.z,0,-We.x,Xe.z,0,-Xe.x,je.z,0,-je.x,-We.y,We.x,0,-Xe.y,Xe.x,0,-je.y,je.x,0];return!!Ke(e,Ve,He,Ge,Ye)&&(e=[1,0,0,0,1,0,0,0,1],!!Ke(e,Ve,He,Ge,Ye)&&(Ze.crossVectors(We,Xe),e=[Ze.x,Ze.y,Ze.z],Ke(e,Ve,He,Ge,Ye)))}clampPoint(t,e){return e.copy(t).clamp(this.min,this.max)}distanceToPoint(t){return this.clampPoint(t,ze).distanceTo(t)}getBoundingSphere(t){return this.isEmpty()?t.makeEmpty():(this.getCenter(t.center),t.radius=.5*this.getSize(ze).length()),t}intersect(t){return this.min.max(t.min),this.max.min(t.max),this.isEmpty()&&this.makeEmpty(),this}union(t){return this.min.min(t.min),this.max.max(t.max),this}applyMatrix4(t){return this.isEmpty()||(Be[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(t),Be[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(t),Be[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(t),Be[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(t),Be[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(t),Be[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(t),Be[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(t),Be[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(t),this.setFromPoints(Be)),this}translate(t){return this.min.add(t),this.max.add(t),this}equals(t){return t.min.equals(this.min)&&t.max.equals(this.max)}}const Be=[new De,new De,new De,new De,new De,new De,new De,new De],ze=new De,ke=new Fe,Ve=new De,He=new De,Ge=new De,We=new De,Xe=new De,je=new De,qe=new De,Ye=new De,Ze=new De,Je=new De;function Ke(t,e,n,i,r){for(let s=0,a=t.length-3;s<=a;s+=3){Je.fromArray(t,s);const a=r.x*Math.abs(Je.x)+r.y*Math.abs(Je.y)+r.z*Math.abs(Je.z),o=e.dot(Je),l=n.dot(Je),c=i.dot(Je);if(Math.max(-Math.max(o,l,c),Math.min(o,l,c))>a)return!1}return!0}const $e=new Fe,Qe=new De,tn=new De;class en{constructor(t=new De,e=-1){this.isSphere=!0,this.center=t,this.radius=e}set(t,e){return this.center.copy(t),this.radius=e,this}setFromPoints(t,e){const n=this.center;void 0!==e?n.copy(e):$e.setFromPoints(t).getCenter(n);let i=0;for(let e=0,r=t.length;ethis.radius*this.radius&&(e.sub(this.center).normalize(),e.multiplyScalar(this.radius).add(this.center)),e}getBoundingBox(t){return this.isEmpty()?(t.makeEmpty(),t):(t.set(this.center,this.center),t.expandByScalar(this.radius),t)}applyMatrix4(t){return this.center.applyMatrix4(t),this.radius=this.radius*t.getMaxScaleOnAxis(),this}translate(t){return this.center.add(t),this}expandByPoint(t){if(this.isEmpty())return this.center.copy(t),this.radius=0,this;Qe.subVectors(t,this.center);const e=Qe.lengthSq();if(e>this.radius*this.radius){const t=Math.sqrt(e),n=.5*(t-this.radius);this.center.addScaledVector(Qe,n/t),this.radius+=n}return this}union(t){return t.isEmpty()?this:this.isEmpty()?(this.copy(t),this):(!0===this.center.equals(t.center)?this.radius=Math.max(this.radius,t.radius):(tn.subVectors(t.center,this.center).setLength(t.radius),this.expandByPoint(Qe.copy(t.center).add(tn)),this.expandByPoint(Qe.copy(t.center).sub(tn))),this)}equals(t){return t.center.equals(this.center)&&t.radius===this.radius}clone(){return(new this.constructor).copy(this)}}const nn=new De,rn=new De,sn=new De,an=new De,on=new De,ln=new De,cn=new De;class hn{constructor(t=new De,e=new De(0,0,-1)){this.origin=t,this.direction=e}set(t,e){return this.origin.copy(t),this.direction.copy(e),this}copy(t){return this.origin.copy(t.origin),this.direction.copy(t.direction),this}at(t,e){return e.copy(this.origin).addScaledVector(this.direction,t)}lookAt(t){return this.direction.copy(t).sub(this.origin).normalize(),this}recast(t){return this.origin.copy(this.at(t,nn)),this}closestPointToPoint(t,e){e.subVectors(t,this.origin);const n=e.dot(this.direction);return n<0?e.copy(this.origin):e.copy(this.origin).addScaledVector(this.direction,n)}distanceToPoint(t){return Math.sqrt(this.distanceSqToPoint(t))}distanceSqToPoint(t){const e=nn.subVectors(t,this.origin).dot(this.direction);return e<0?this.origin.distanceToSquared(t):(nn.copy(this.origin).addScaledVector(this.direction,e),nn.distanceToSquared(t))}distanceSqToSegment(t,e,n,i){rn.copy(t).add(e).multiplyScalar(.5),sn.copy(e).sub(t).normalize(),an.copy(this.origin).sub(rn);const r=.5*t.distanceTo(e),s=-this.direction.dot(sn),a=an.dot(this.direction),o=-an.dot(sn),l=an.lengthSq(),c=Math.abs(1-s*s);let h,u,d,p;if(c>0)if(h=s*o-a,u=s*a-o,p=r*c,h>=0)if(u>=-p)if(u<=p){const t=1/c;h*=t,u*=t,d=h*(h+s*u+2*a)+u*(s*h+u+2*o)+l}else u=r,h=Math.max(0,-(s*u+a)),d=-h*h+u*(u+2*o)+l;else u=-r,h=Math.max(0,-(s*u+a)),d=-h*h+u*(u+2*o)+l;else u<=-p?(h=Math.max(0,-(-s*r+a)),u=h>0?-r:Math.min(Math.max(-r,-o),r),d=-h*h+u*(u+2*o)+l):u<=p?(h=0,u=Math.min(Math.max(-r,-o),r),d=u*(u+2*o)+l):(h=Math.max(0,-(s*r+a)),u=h>0?r:Math.min(Math.max(-r,-o),r),d=-h*h+u*(u+2*o)+l);else u=s>0?-r:r,h=Math.max(0,-(s*u+a)),d=-h*h+u*(u+2*o)+l;return n&&n.copy(this.origin).addScaledVector(this.direction,h),i&&i.copy(rn).addScaledVector(sn,u),d}intersectSphere(t,e){nn.subVectors(t.center,this.origin);const n=nn.dot(this.direction),i=nn.dot(nn)-n*n,r=t.radius*t.radius;if(i>r)return null;const s=Math.sqrt(r-i),a=n-s,o=n+s;return o<0?null:a<0?this.at(o,e):this.at(a,e)}intersectsSphere(t){return this.distanceSqToPoint(t.center)<=t.radius*t.radius}distanceToPlane(t){const e=t.normal.dot(this.direction);if(0===e)return 0===t.distanceToPoint(this.origin)?0:null;const n=-(this.origin.dot(t.normal)+t.constant)/e;return n>=0?n:null}intersectPlane(t,e){const n=this.distanceToPlane(t);return null===n?null:this.at(n,e)}intersectsPlane(t){const e=t.distanceToPoint(this.origin);return 0===e||t.normal.dot(this.direction)*e<0}intersectBox(t,e){let n,i,r,s,a,o;const l=1/this.direction.x,c=1/this.direction.y,h=1/this.direction.z,u=this.origin;return l>=0?(n=(t.min.x-u.x)*l,i=(t.max.x-u.x)*l):(n=(t.max.x-u.x)*l,i=(t.min.x-u.x)*l),c>=0?(r=(t.min.y-u.y)*c,s=(t.max.y-u.y)*c):(r=(t.max.y-u.y)*c,s=(t.min.y-u.y)*c),n>s||r>i?null:((r>n||isNaN(n))&&(n=r),(s=0?(a=(t.min.z-u.z)*h,o=(t.max.z-u.z)*h):(a=(t.max.z-u.z)*h,o=(t.min.z-u.z)*h),n>o||a>i?null:((a>n||n!=n)&&(n=a),(o=0?n:i,e)))}intersectsBox(t){return null!==this.intersectBox(t,nn)}intersectTriangle(t,e,n,i,r){on.subVectors(e,t),ln.subVectors(n,t),cn.crossVectors(on,ln);let s,a=this.direction.dot(cn);if(a>0){if(i)return null;s=1}else{if(!(a<0))return null;s=-1,a=-a}an.subVectors(this.origin,t);const o=s*this.direction.dot(ln.crossVectors(an,ln));if(o<0)return null;const l=s*this.direction.dot(on.cross(an));if(l<0)return null;if(o+l>a)return null;const c=-s*an.dot(cn);return c<0?null:this.at(c/a,r)}applyMatrix4(t){return this.origin.applyMatrix4(t),this.direction.transformDirection(t),this}equals(t){return t.origin.equals(this.origin)&&t.direction.equals(this.direction)}clone(){return(new this.constructor).copy(this)}}class un{constructor(t,e,n,i,r,s,a,o,l,c,h,u,d,p,m,f){un.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],void 0!==t&&this.set(t,e,n,i,r,s,a,o,l,c,h,u,d,p,m,f)}set(t,e,n,i,r,s,a,o,l,c,h,u,d,p,m,f){const g=this.elements;return g[0]=t,g[4]=e,g[8]=n,g[12]=i,g[1]=r,g[5]=s,g[9]=a,g[13]=o,g[2]=l,g[6]=c,g[10]=h,g[14]=u,g[3]=d,g[7]=p,g[11]=m,g[15]=f,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return(new un).fromArray(this.elements)}copy(t){const e=this.elements,n=t.elements;return e[0]=n[0],e[1]=n[1],e[2]=n[2],e[3]=n[3],e[4]=n[4],e[5]=n[5],e[6]=n[6],e[7]=n[7],e[8]=n[8],e[9]=n[9],e[10]=n[10],e[11]=n[11],e[12]=n[12],e[13]=n[13],e[14]=n[14],e[15]=n[15],this}copyPosition(t){const e=this.elements,n=t.elements;return e[12]=n[12],e[13]=n[13],e[14]=n[14],this}setFromMatrix3(t){const e=t.elements;return this.set(e[0],e[3],e[6],0,e[1],e[4],e[7],0,e[2],e[5],e[8],0,0,0,0,1),this}extractBasis(t,e,n){return t.setFromMatrixColumn(this,0),e.setFromMatrixColumn(this,1),n.setFromMatrixColumn(this,2),this}makeBasis(t,e,n){return this.set(t.x,e.x,n.x,0,t.y,e.y,n.y,0,t.z,e.z,n.z,0,0,0,0,1),this}extractRotation(t){const e=this.elements,n=t.elements,i=1/dn.setFromMatrixColumn(t,0).length(),r=1/dn.setFromMatrixColumn(t,1).length(),s=1/dn.setFromMatrixColumn(t,2).length();return e[0]=n[0]*i,e[1]=n[1]*i,e[2]=n[2]*i,e[3]=0,e[4]=n[4]*r,e[5]=n[5]*r,e[6]=n[6]*r,e[7]=0,e[8]=n[8]*s,e[9]=n[9]*s,e[10]=n[10]*s,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromEuler(t){const e=this.elements,n=t.x,i=t.y,r=t.z,s=Math.cos(n),a=Math.sin(n),o=Math.cos(i),l=Math.sin(i),c=Math.cos(r),h=Math.sin(r);if("XYZ"===t.order){const t=s*c,n=s*h,i=a*c,r=a*h;e[0]=o*c,e[4]=-o*h,e[8]=l,e[1]=n+i*l,e[5]=t-r*l,e[9]=-a*o,e[2]=r-t*l,e[6]=i+n*l,e[10]=s*o}else if("YXZ"===t.order){const t=o*c,n=o*h,i=l*c,r=l*h;e[0]=t+r*a,e[4]=i*a-n,e[8]=s*l,e[1]=s*h,e[5]=s*c,e[9]=-a,e[2]=n*a-i,e[6]=r+t*a,e[10]=s*o}else if("ZXY"===t.order){const t=o*c,n=o*h,i=l*c,r=l*h;e[0]=t-r*a,e[4]=-s*h,e[8]=i+n*a,e[1]=n+i*a,e[5]=s*c,e[9]=r-t*a,e[2]=-s*l,e[6]=a,e[10]=s*o}else if("ZYX"===t.order){const t=s*c,n=s*h,i=a*c,r=a*h;e[0]=o*c,e[4]=i*l-n,e[8]=t*l+r,e[1]=o*h,e[5]=r*l+t,e[9]=n*l-i,e[2]=-l,e[6]=a*o,e[10]=s*o}else if("YZX"===t.order){const t=s*o,n=s*l,i=a*o,r=a*l;e[0]=o*c,e[4]=r-t*h,e[8]=i*h+n,e[1]=h,e[5]=s*c,e[9]=-a*c,e[2]=-l*c,e[6]=n*h+i,e[10]=t-r*h}else if("XZY"===t.order){const t=s*o,n=s*l,i=a*o,r=a*l;e[0]=o*c,e[4]=-h,e[8]=l*c,e[1]=t*h+r,e[5]=s*c,e[9]=n*h-i,e[2]=i*h-n,e[6]=a*c,e[10]=r*h+t}return e[3]=0,e[7]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromQuaternion(t){return this.compose(mn,t,fn)}lookAt(t,e,n){const i=this.elements;return _n.subVectors(t,e),0===_n.lengthSq()&&(_n.z=1),_n.normalize(),gn.crossVectors(n,_n),0===gn.lengthSq()&&(1===Math.abs(n.z)?_n.x+=1e-4:_n.z+=1e-4,_n.normalize(),gn.crossVectors(n,_n)),gn.normalize(),vn.crossVectors(_n,gn),i[0]=gn.x,i[4]=vn.x,i[8]=_n.x,i[1]=gn.y,i[5]=vn.y,i[9]=_n.y,i[2]=gn.z,i[6]=vn.z,i[10]=_n.z,this}multiply(t){return this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){const n=t.elements,i=e.elements,r=this.elements,s=n[0],a=n[4],o=n[8],l=n[12],c=n[1],h=n[5],u=n[9],d=n[13],p=n[2],m=n[6],f=n[10],g=n[14],v=n[3],_=n[7],y=n[11],x=n[15],M=i[0],S=i[4],b=i[8],w=i[12],T=i[1],E=i[5],A=i[9],C=i[13],R=i[2],P=i[6],I=i[10],L=i[14],U=i[3],D=i[7],N=i[11],O=i[15];return r[0]=s*M+a*T+o*R+l*U,r[4]=s*S+a*E+o*P+l*D,r[8]=s*b+a*A+o*I+l*N,r[12]=s*w+a*C+o*L+l*O,r[1]=c*M+h*T+u*R+d*U,r[5]=c*S+h*E+u*P+d*D,r[9]=c*b+h*A+u*I+d*N,r[13]=c*w+h*C+u*L+d*O,r[2]=p*M+m*T+f*R+g*U,r[6]=p*S+m*E+f*P+g*D,r[10]=p*b+m*A+f*I+g*N,r[14]=p*w+m*C+f*L+g*O,r[3]=v*M+_*T+y*R+x*U,r[7]=v*S+_*E+y*P+x*D,r[11]=v*b+_*A+y*I+x*N,r[15]=v*w+_*C+y*L+x*O,this}multiplyScalar(t){const e=this.elements;return e[0]*=t,e[4]*=t,e[8]*=t,e[12]*=t,e[1]*=t,e[5]*=t,e[9]*=t,e[13]*=t,e[2]*=t,e[6]*=t,e[10]*=t,e[14]*=t,e[3]*=t,e[7]*=t,e[11]*=t,e[15]*=t,this}determinant(){const t=this.elements,e=t[0],n=t[4],i=t[8],r=t[12],s=t[1],a=t[5],o=t[9],l=t[13],c=t[2],h=t[6],u=t[10],d=t[14];return t[3]*(+r*o*h-i*l*h-r*a*u+n*l*u+i*a*d-n*o*d)+t[7]*(+e*o*d-e*l*u+r*s*u-i*s*d+i*l*c-r*o*c)+t[11]*(+e*l*h-e*a*d-r*s*h+n*s*d+r*a*c-n*l*c)+t[15]*(-i*a*c-e*o*h+e*a*u+i*s*h-n*s*u+n*o*c)}transpose(){const t=this.elements;let e;return e=t[1],t[1]=t[4],t[4]=e,e=t[2],t[2]=t[8],t[8]=e,e=t[6],t[6]=t[9],t[9]=e,e=t[3],t[3]=t[12],t[12]=e,e=t[7],t[7]=t[13],t[13]=e,e=t[11],t[11]=t[14],t[14]=e,this}setPosition(t,e,n){const i=this.elements;return t.isVector3?(i[12]=t.x,i[13]=t.y,i[14]=t.z):(i[12]=t,i[13]=e,i[14]=n),this}invert(){const t=this.elements,e=t[0],n=t[1],i=t[2],r=t[3],s=t[4],a=t[5],o=t[6],l=t[7],c=t[8],h=t[9],u=t[10],d=t[11],p=t[12],m=t[13],f=t[14],g=t[15],v=h*f*l-m*u*l+m*o*d-a*f*d-h*o*g+a*u*g,_=p*u*l-c*f*l-p*o*d+s*f*d+c*o*g-s*u*g,y=c*m*l-p*h*l+p*a*d-s*m*d-c*a*g+s*h*g,x=p*h*o-c*m*o-p*a*u+s*m*u+c*a*f-s*h*f,M=e*v+n*_+i*y+r*x;if(0===M)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const S=1/M;return t[0]=v*S,t[1]=(m*u*r-h*f*r-m*i*d+n*f*d+h*i*g-n*u*g)*S,t[2]=(a*f*r-m*o*r+m*i*l-n*f*l-a*i*g+n*o*g)*S,t[3]=(h*o*r-a*u*r-h*i*l+n*u*l+a*i*d-n*o*d)*S,t[4]=_*S,t[5]=(c*f*r-p*u*r+p*i*d-e*f*d-c*i*g+e*u*g)*S,t[6]=(p*o*r-s*f*r-p*i*l+e*f*l+s*i*g-e*o*g)*S,t[7]=(s*u*r-c*o*r+c*i*l-e*u*l-s*i*d+e*o*d)*S,t[8]=y*S,t[9]=(p*h*r-c*m*r-p*n*d+e*m*d+c*n*g-e*h*g)*S,t[10]=(s*m*r-p*a*r+p*n*l-e*m*l-s*n*g+e*a*g)*S,t[11]=(c*a*r-s*h*r-c*n*l+e*h*l+s*n*d-e*a*d)*S,t[12]=x*S,t[13]=(c*m*i-p*h*i+p*n*u-e*m*u-c*n*f+e*h*f)*S,t[14]=(p*a*i-s*m*i-p*n*o+e*m*o+s*n*f-e*a*f)*S,t[15]=(s*h*i-c*a*i+c*n*o-e*h*o-s*n*u+e*a*u)*S,this}scale(t){const e=this.elements,n=t.x,i=t.y,r=t.z;return e[0]*=n,e[4]*=i,e[8]*=r,e[1]*=n,e[5]*=i,e[9]*=r,e[2]*=n,e[6]*=i,e[10]*=r,e[3]*=n,e[7]*=i,e[11]*=r,this}getMaxScaleOnAxis(){const t=this.elements,e=t[0]*t[0]+t[1]*t[1]+t[2]*t[2],n=t[4]*t[4]+t[5]*t[5]+t[6]*t[6],i=t[8]*t[8]+t[9]*t[9]+t[10]*t[10];return Math.sqrt(Math.max(e,n,i))}makeTranslation(t,e,n){return t.isVector3?this.set(1,0,0,t.x,0,1,0,t.y,0,0,1,t.z,0,0,0,1):this.set(1,0,0,t,0,1,0,e,0,0,1,n,0,0,0,1),this}makeRotationX(t){const e=Math.cos(t),n=Math.sin(t);return this.set(1,0,0,0,0,e,-n,0,0,n,e,0,0,0,0,1),this}makeRotationY(t){const e=Math.cos(t),n=Math.sin(t);return this.set(e,0,n,0,0,1,0,0,-n,0,e,0,0,0,0,1),this}makeRotationZ(t){const e=Math.cos(t),n=Math.sin(t);return this.set(e,-n,0,0,n,e,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(t,e){const n=Math.cos(e),i=Math.sin(e),r=1-n,s=t.x,a=t.y,o=t.z,l=r*s,c=r*a;return this.set(l*s+n,l*a-i*o,l*o+i*a,0,l*a+i*o,c*a+n,c*o-i*s,0,l*o-i*a,c*o+i*s,r*o*o+n,0,0,0,0,1),this}makeScale(t,e,n){return this.set(t,0,0,0,0,e,0,0,0,0,n,0,0,0,0,1),this}makeShear(t,e,n,i,r,s){return this.set(1,n,r,0,t,1,s,0,e,i,1,0,0,0,0,1),this}compose(t,e,n){const i=this.elements,r=e._x,s=e._y,a=e._z,o=e._w,l=r+r,c=s+s,h=a+a,u=r*l,d=r*c,p=r*h,m=s*c,f=s*h,g=a*h,v=o*l,_=o*c,y=o*h,x=n.x,M=n.y,S=n.z;return i[0]=(1-(m+g))*x,i[1]=(d+y)*x,i[2]=(p-_)*x,i[3]=0,i[4]=(d-y)*M,i[5]=(1-(u+g))*M,i[6]=(f+v)*M,i[7]=0,i[8]=(p+_)*S,i[9]=(f-v)*S,i[10]=(1-(u+m))*S,i[11]=0,i[12]=t.x,i[13]=t.y,i[14]=t.z,i[15]=1,this}decompose(t,e,n){const i=this.elements;let r=dn.set(i[0],i[1],i[2]).length();const s=dn.set(i[4],i[5],i[6]).length(),a=dn.set(i[8],i[9],i[10]).length();this.determinant()<0&&(r=-r),t.x=i[12],t.y=i[13],t.z=i[14],pn.copy(this);const o=1/r,l=1/s,c=1/a;return pn.elements[0]*=o,pn.elements[1]*=o,pn.elements[2]*=o,pn.elements[4]*=l,pn.elements[5]*=l,pn.elements[6]*=l,pn.elements[8]*=c,pn.elements[9]*=c,pn.elements[10]*=c,e.setFromRotationMatrix(pn),n.x=r,n.y=s,n.z=a,this}makePerspective(t,e,n,i,r,s,a=2e3){const o=this.elements,l=2*r/(e-t),c=2*r/(n-i),h=(e+t)/(e-t),u=(n+i)/(n-i);let d,p;if(a===Wt)d=-(s+r)/(s-r),p=-2*s*r/(s-r);else{if(a!==Xt)throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+a);d=-s/(s-r),p=-s*r/(s-r)}return o[0]=l,o[4]=0,o[8]=h,o[12]=0,o[1]=0,o[5]=c,o[9]=u,o[13]=0,o[2]=0,o[6]=0,o[10]=d,o[14]=p,o[3]=0,o[7]=0,o[11]=-1,o[15]=0,this}makeOrthographic(t,e,n,i,r,s,a=2e3){const o=this.elements,l=1/(e-t),c=1/(n-i),h=1/(s-r),u=(e+t)*l,d=(n+i)*c;let p,m;if(a===Wt)p=(s+r)*h,m=-2*h;else{if(a!==Xt)throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+a);p=r*h,m=-1*h}return o[0]=2*l,o[4]=0,o[8]=0,o[12]=-u,o[1]=0,o[5]=2*c,o[9]=0,o[13]=-d,o[2]=0,o[6]=0,o[10]=m,o[14]=-p,o[3]=0,o[7]=0,o[11]=0,o[15]=1,this}equals(t){const e=this.elements,n=t.elements;for(let t=0;t<16;t++)if(e[t]!==n[t])return!1;return!0}fromArray(t,e=0){for(let n=0;n<16;n++)this.elements[n]=t[n+e];return this}toArray(t=[],e=0){const n=this.elements;return t[e]=n[0],t[e+1]=n[1],t[e+2]=n[2],t[e+3]=n[3],t[e+4]=n[4],t[e+5]=n[5],t[e+6]=n[6],t[e+7]=n[7],t[e+8]=n[8],t[e+9]=n[9],t[e+10]=n[10],t[e+11]=n[11],t[e+12]=n[12],t[e+13]=n[13],t[e+14]=n[14],t[e+15]=n[15],t}}const dn=new De,pn=new un,mn=new De(0,0,0),fn=new De(1,1,1),gn=new De,vn=new De,_n=new De,yn=new un,xn=new Ue;class Mn{constructor(t=0,e=0,n=0,i=Mn.DEFAULT_ORDER){this.isEuler=!0,this._x=t,this._y=e,this._z=n,this._order=i}get x(){return this._x}set x(t){this._x=t,this._onChangeCallback()}get y(){return this._y}set y(t){this._y=t,this._onChangeCallback()}get z(){return this._z}set z(t){this._z=t,this._onChangeCallback()}get order(){return this._order}set order(t){this._order=t,this._onChangeCallback()}set(t,e,n,i=this._order){return this._x=t,this._y=e,this._z=n,this._order=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(t){return this._x=t._x,this._y=t._y,this._z=t._z,this._order=t._order,this._onChangeCallback(),this}setFromRotationMatrix(t,e=this._order,n=!0){const i=t.elements,r=i[0],s=i[4],a=i[8],o=i[1],l=i[5],c=i[9],h=i[2],u=i[6],d=i[10];switch(e){case"XYZ":this._y=Math.asin($t(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-c,d),this._z=Math.atan2(-s,r)):(this._x=Math.atan2(u,l),this._z=0);break;case"YXZ":this._x=Math.asin(-$t(c,-1,1)),Math.abs(c)<.9999999?(this._y=Math.atan2(a,d),this._z=Math.atan2(o,l)):(this._y=Math.atan2(-h,r),this._z=0);break;case"ZXY":this._x=Math.asin($t(u,-1,1)),Math.abs(u)<.9999999?(this._y=Math.atan2(-h,d),this._z=Math.atan2(-s,l)):(this._y=0,this._z=Math.atan2(o,r));break;case"ZYX":this._y=Math.asin(-$t(h,-1,1)),Math.abs(h)<.9999999?(this._x=Math.atan2(u,d),this._z=Math.atan2(o,r)):(this._x=0,this._z=Math.atan2(-s,l));break;case"YZX":this._z=Math.asin($t(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-c,l),this._y=Math.atan2(-h,r)):(this._x=0,this._y=Math.atan2(a,d));break;case"XZY":this._z=Math.asin(-$t(s,-1,1)),Math.abs(s)<.9999999?(this._x=Math.atan2(u,l),this._y=Math.atan2(a,r)):(this._x=Math.atan2(-c,d),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+e)}return this._order=e,!0===n&&this._onChangeCallback(),this}setFromQuaternion(t,e,n){return yn.makeRotationFromQuaternion(t),this.setFromRotationMatrix(yn,e,n)}setFromVector3(t,e=this._order){return this.set(t.x,t.y,t.z,e)}reorder(t){return xn.setFromEuler(this),this.setFromQuaternion(xn,t)}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._order===this._order}fromArray(t){return this._x=t[0],this._y=t[1],this._z=t[2],void 0!==t[3]&&(this._order=t[3]),this._onChangeCallback(),this}toArray(t=[],e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._order,t}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}Mn.DEFAULT_ORDER="XYZ";class Sn{constructor(){this.mask=1}set(t){this.mask=(1<>>0}enable(t){this.mask|=1<1){for(let t=0;t1){for(let t=0;t0&&(i.userData=this.userData),i.layers=this.layers.mask,i.matrix=this.matrix.toArray(),i.up=this.up.toArray(),!1===this.matrixAutoUpdate&&(i.matrixAutoUpdate=!1),this.isInstancedMesh&&(i.type="InstancedMesh",i.count=this.count,i.instanceMatrix=this.instanceMatrix.toJSON(),null!==this.instanceColor&&(i.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(i.type="BatchedMesh",i.perObjectFrustumCulled=this.perObjectFrustumCulled,i.sortObjects=this.sortObjects,i.drawRanges=this._drawRanges,i.reservedRanges=this._reservedRanges,i.visibility=this._visibility,i.active=this._active,i.bounds=this._bounds.map((t=>({boxInitialized:t.boxInitialized,boxMin:t.box.min.toArray(),boxMax:t.box.max.toArray(),sphereInitialized:t.sphereInitialized,sphereRadius:t.sphere.radius,sphereCenter:t.sphere.center.toArray()}))),i.maxInstanceCount=this._maxInstanceCount,i.maxVertexCount=this._maxVertexCount,i.maxIndexCount=this._maxIndexCount,i.geometryInitialized=this._geometryInitialized,i.geometryCount=this._geometryCount,i.matricesTexture=this._matricesTexture.toJSON(t),null!==this._colorsTexture&&(i.colorsTexture=this._colorsTexture.toJSON(t)),null!==this.boundingSphere&&(i.boundingSphere={center:i.boundingSphere.center.toArray(),radius:i.boundingSphere.radius}),null!==this.boundingBox&&(i.boundingBox={min:i.boundingBox.min.toArray(),max:i.boundingBox.max.toArray()})),this.isScene)this.background&&(this.background.isColor?i.background=this.background.toJSON():this.background.isTexture&&(i.background=this.background.toJSON(t).uuid)),this.environment&&this.environment.isTexture&&!0!==this.environment.isRenderTargetTexture&&(i.environment=this.environment.toJSON(t).uuid);else if(this.isMesh||this.isLine||this.isPoints){i.geometry=r(t.geometries,this.geometry);const e=this.geometry.parameters;if(void 0!==e&&void 0!==e.shapes){const n=e.shapes;if(Array.isArray(n))for(let e=0,i=n.length;e0){i.children=[];for(let e=0;e0){i.animations=[];for(let e=0;e0&&(n.geometries=e),i.length>0&&(n.materials=i),r.length>0&&(n.textures=r),a.length>0&&(n.images=a),o.length>0&&(n.shapes=o),l.length>0&&(n.skeletons=l),c.length>0&&(n.animations=c),h.length>0&&(n.nodes=h)}return n.object=i,n;function s(t){const e=[];for(const n in t){const i=t[n];delete i.metadata,e.push(i)}return e}}clone(t){return(new this.constructor).copy(this,t)}copy(t,e=!0){if(this.name=t.name,this.up.copy(t.up),this.position.copy(t.position),this.rotation.order=t.rotation.order,this.quaternion.copy(t.quaternion),this.scale.copy(t.scale),this.matrix.copy(t.matrix),this.matrixWorld.copy(t.matrixWorld),this.matrixAutoUpdate=t.matrixAutoUpdate,this.matrixWorldAutoUpdate=t.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=t.matrixWorldNeedsUpdate,this.layers.mask=t.layers.mask,this.visible=t.visible,this.castShadow=t.castShadow,this.receiveShadow=t.receiveShadow,this.frustumCulled=t.frustumCulled,this.renderOrder=t.renderOrder,this.animations=t.animations.slice(),this.userData=JSON.parse(JSON.stringify(t.userData)),!0===e)for(let e=0;e0?i.multiplyScalar(1/Math.sqrt(r)):i.set(0,0,0)}static getBarycoord(t,e,n,i,r){zn.subVectors(i,e),kn.subVectors(n,e),Vn.subVectors(t,e);const s=zn.dot(zn),a=zn.dot(kn),o=zn.dot(Vn),l=kn.dot(kn),c=kn.dot(Vn),h=s*l-a*a;if(0===h)return r.set(0,0,0),null;const u=1/h,d=(l*o-a*c)*u,p=(s*c-a*o)*u;return r.set(1-d-p,p,d)}static containsPoint(t,e,n,i){return null!==this.getBarycoord(t,e,n,i,Hn)&&Hn.x>=0&&Hn.y>=0&&Hn.x+Hn.y<=1}static getInterpolation(t,e,n,i,r,s,a,o){return null===this.getBarycoord(t,e,n,i,Hn)?(o.x=0,o.y=0,"z"in o&&(o.z=0),"w"in o&&(o.w=0),null):(o.setScalar(0),o.addScaledVector(r,Hn.x),o.addScaledVector(s,Hn.y),o.addScaledVector(a,Hn.z),o)}static getInterpolatedAttribute(t,e,n,i,r,s){return Zn.setScalar(0),Jn.setScalar(0),Kn.setScalar(0),Zn.fromBufferAttribute(t,e),Jn.fromBufferAttribute(t,n),Kn.fromBufferAttribute(t,i),s.setScalar(0),s.addScaledVector(Zn,r.x),s.addScaledVector(Jn,r.y),s.addScaledVector(Kn,r.z),s}static isFrontFacing(t,e,n,i){return zn.subVectors(n,e),kn.subVectors(t,e),zn.cross(kn).dot(i)<0}set(t,e,n){return this.a.copy(t),this.b.copy(e),this.c.copy(n),this}setFromPointsAndIndices(t,e,n,i){return this.a.copy(t[e]),this.b.copy(t[n]),this.c.copy(t[i]),this}setFromAttributeAndIndices(t,e,n,i){return this.a.fromBufferAttribute(t,e),this.b.fromBufferAttribute(t,n),this.c.fromBufferAttribute(t,i),this}clone(){return(new this.constructor).copy(this)}copy(t){return this.a.copy(t.a),this.b.copy(t.b),this.c.copy(t.c),this}getArea(){return zn.subVectors(this.c,this.b),kn.subVectors(this.a,this.b),.5*zn.cross(kn).length()}getMidpoint(t){return t.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(t){return $n.getNormal(this.a,this.b,this.c,t)}getPlane(t){return t.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(t,e){return $n.getBarycoord(t,this.a,this.b,this.c,e)}getInterpolation(t,e,n,i,r){return $n.getInterpolation(t,this.a,this.b,this.c,e,n,i,r)}containsPoint(t){return $n.containsPoint(t,this.a,this.b,this.c)}isFrontFacing(t){return $n.isFrontFacing(this.a,this.b,this.c,t)}intersectsBox(t){return t.intersectsTriangle(this)}closestPointToPoint(t,e){const n=this.a,i=this.b,r=this.c;let s,a;Gn.subVectors(i,n),Wn.subVectors(r,n),jn.subVectors(t,n);const o=Gn.dot(jn),l=Wn.dot(jn);if(o<=0&&l<=0)return e.copy(n);qn.subVectors(t,i);const c=Gn.dot(qn),h=Wn.dot(qn);if(c>=0&&h<=c)return e.copy(i);const u=o*h-c*l;if(u<=0&&o>=0&&c<=0)return s=o/(o-c),e.copy(n).addScaledVector(Gn,s);Yn.subVectors(t,r);const d=Gn.dot(Yn),p=Wn.dot(Yn);if(p>=0&&d<=p)return e.copy(r);const m=d*l-o*p;if(m<=0&&l>=0&&p<=0)return a=l/(l-p),e.copy(n).addScaledVector(Wn,a);const f=c*p-d*h;if(f<=0&&h-c>=0&&d-p>=0)return Xn.subVectors(r,i),a=(h-c)/(h-c+(d-p)),e.copy(i).addScaledVector(Xn,a);const g=1/(f+m+u);return s=m*g,a=u*g,e.copy(n).addScaledVector(Gn,s).addScaledVector(Wn,a)}equals(t){return t.a.equals(this.a)&&t.b.equals(this.b)&&t.c.equals(this.c)}}const Qn={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},ti={h:0,s:0,l:0},ei={h:0,s:0,l:0};function ni(t,e,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?t+6*(e-t)*n:n<.5?e:n<2/3?t+6*(e-t)*(2/3-n):t}class ii{constructor(t,e,n){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(t,e,n)}set(t,e,n){if(void 0===e&&void 0===n){const e=t;e&&e.isColor?this.copy(e):"number"==typeof e?this.setHex(e):"string"==typeof e&&this.setStyle(e)}else this.setRGB(t,e,n);return this}setScalar(t){return this.r=t,this.g=t,this.b=t,this}setHex(t,e=Ut){return t=Math.floor(t),this.r=(t>>16&255)/255,this.g=(t>>8&255)/255,this.b=(255&t)/255,_e.toWorkingColorSpace(this,e),this}setRGB(t,e,n,i=_e.workingColorSpace){return this.r=t,this.g=e,this.b=n,_e.toWorkingColorSpace(this,i),this}setHSL(t,e,n,i=_e.workingColorSpace){if(t=Qt(t,1),e=$t(e,0,1),n=$t(n,0,1),0===e)this.r=this.g=this.b=n;else{const i=n<=.5?n*(1+e):n+e-n*e,r=2*n-i;this.r=ni(r,i,t+1/3),this.g=ni(r,i,t),this.b=ni(r,i,t-1/3)}return _e.toWorkingColorSpace(this,i),this}setStyle(t,e=Ut){function n(e){void 0!==e&&parseFloat(e)<1&&console.warn("THREE.Color: Alpha component of "+t+" will be ignored.")}let i;if(i=/^(\w+)\(([^\)]*)\)/.exec(t)){let r;const s=i[1],a=i[2];switch(s){case"rgb":case"rgba":if(r=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setRGB(Math.min(255,parseInt(r[1],10))/255,Math.min(255,parseInt(r[2],10))/255,Math.min(255,parseInt(r[3],10))/255,e);if(r=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setRGB(Math.min(100,parseInt(r[1],10))/100,Math.min(100,parseInt(r[2],10))/100,Math.min(100,parseInt(r[3],10))/100,e);break;case"hsl":case"hsla":if(r=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setHSL(parseFloat(r[1])/360,parseFloat(r[2])/100,parseFloat(r[3])/100,e);break;default:console.warn("THREE.Color: Unknown color model "+t)}}else if(i=/^\#([A-Fa-f\d]+)$/.exec(t)){const n=i[1],r=n.length;if(3===r)return this.setRGB(parseInt(n.charAt(0),16)/15,parseInt(n.charAt(1),16)/15,parseInt(n.charAt(2),16)/15,e);if(6===r)return this.setHex(parseInt(n,16),e);console.warn("THREE.Color: Invalid hex color "+t)}else if(t&&t.length>0)return this.setColorName(t,e);return this}setColorName(t,e=Ut){const n=Qn[t.toLowerCase()];return void 0!==n?this.setHex(n,e):console.warn("THREE.Color: Unknown color "+t),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(t){return this.r=t.r,this.g=t.g,this.b=t.b,this}copySRGBToLinear(t){return this.r=ye(t.r),this.g=ye(t.g),this.b=ye(t.b),this}copyLinearToSRGB(t){return this.r=xe(t.r),this.g=xe(t.g),this.b=xe(t.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(t=Ut){return _e.fromWorkingColorSpace(ri.copy(this),t),65536*Math.round($t(255*ri.r,0,255))+256*Math.round($t(255*ri.g,0,255))+Math.round($t(255*ri.b,0,255))}getHexString(t=Ut){return("000000"+this.getHex(t).toString(16)).slice(-6)}getHSL(t,e=_e.workingColorSpace){_e.fromWorkingColorSpace(ri.copy(this),e);const n=ri.r,i=ri.g,r=ri.b,s=Math.max(n,i,r),a=Math.min(n,i,r);let o,l;const c=(a+s)/2;if(a===s)o=0,l=0;else{const t=s-a;switch(l=c<=.5?t/(s+a):t/(2-s-a),s){case n:o=(i-r)/t+(i0!=t>0&&this.version++,this._alphaTest=t}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(t){if(void 0!==t)for(const e in t){const n=t[e];if(void 0===n){console.warn(`THREE.Material: parameter '${e}' has value of undefined.`);continue}const i=this[e];void 0!==i?i&&i.isColor?i.set(n):i&&i.isVector3&&n&&n.isVector3?i.copy(n):this[e]=n:console.warn(`THREE.Material: '${e}' is not a property of THREE.${this.type}.`)}}toJSON(t){const e=void 0===t||"string"==typeof t;e&&(t={textures:{},images:{}});const n={metadata:{version:4.6,type:"Material",generator:"Material.toJSON"}};function a(t){const e=[];for(const n in t){const i=t[n];delete i.metadata,e.push(i)}return e}if(n.uuid=this.uuid,n.type=this.type,""!==this.name&&(n.name=this.name),this.color&&this.color.isColor&&(n.color=this.color.getHex()),void 0!==this.roughness&&(n.roughness=this.roughness),void 0!==this.metalness&&(n.metalness=this.metalness),void 0!==this.sheen&&(n.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(n.sheenColor=this.sheenColor.getHex()),void 0!==this.sheenRoughness&&(n.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),void 0!==this.emissiveIntensity&&1!==this.emissiveIntensity&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),void 0!==this.specularIntensity&&(n.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(n.specularColor=this.specularColor.getHex()),void 0!==this.shininess&&(n.shininess=this.shininess),void 0!==this.clearcoat&&(n.clearcoat=this.clearcoat),void 0!==this.clearcoatRoughness&&(n.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(n.clearcoatMap=this.clearcoatMap.toJSON(t).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(t).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(t).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),void 0!==this.dispersion&&(n.dispersion=this.dispersion),void 0!==this.iridescence&&(n.iridescence=this.iridescence),void 0!==this.iridescenceIOR&&(n.iridescenceIOR=this.iridescenceIOR),void 0!==this.iridescenceThicknessRange&&(n.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(n.iridescenceMap=this.iridescenceMap.toJSON(t).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(n.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(t).uuid),void 0!==this.anisotropy&&(n.anisotropy=this.anisotropy),void 0!==this.anisotropyRotation&&(n.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(n.anisotropyMap=this.anisotropyMap.toJSON(t).uuid),this.map&&this.map.isTexture&&(n.map=this.map.toJSON(t).uuid),this.matcap&&this.matcap.isTexture&&(n.matcap=this.matcap.toJSON(t).uuid),this.alphaMap&&this.alphaMap.isTexture&&(n.alphaMap=this.alphaMap.toJSON(t).uuid),this.lightMap&&this.lightMap.isTexture&&(n.lightMap=this.lightMap.toJSON(t).uuid,n.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(n.aoMap=this.aoMap.toJSON(t).uuid,n.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(n.bumpMap=this.bumpMap.toJSON(t).uuid,n.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(n.normalMap=this.normalMap.toJSON(t).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(n.displacementMap=this.displacementMap.toJSON(t).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(n.roughnessMap=this.roughnessMap.toJSON(t).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(n.metalnessMap=this.metalnessMap.toJSON(t).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(n.emissiveMap=this.emissiveMap.toJSON(t).uuid),this.specularMap&&this.specularMap.isTexture&&(n.specularMap=this.specularMap.toJSON(t).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(n.specularIntensityMap=this.specularIntensityMap.toJSON(t).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(n.specularColorMap=this.specularColorMap.toJSON(t).uuid),this.envMap&&this.envMap.isTexture&&(n.envMap=this.envMap.toJSON(t).uuid,void 0!==this.combine&&(n.combine=this.combine)),void 0!==this.envMapRotation&&(n.envMapRotation=this.envMapRotation.toArray()),void 0!==this.envMapIntensity&&(n.envMapIntensity=this.envMapIntensity),void 0!==this.reflectivity&&(n.reflectivity=this.reflectivity),void 0!==this.refractionRatio&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(t).uuid),void 0!==this.transmission&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(t).uuid),void 0!==this.thickness&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(t).uuid),void 0!==this.attenuationDistance&&this.attenuationDistance!==1/0&&(n.attenuationDistance=this.attenuationDistance),void 0!==this.attenuationColor&&(n.attenuationColor=this.attenuationColor.getHex()),void 0!==this.size&&(n.size=this.size),null!==this.shadowSide&&(n.shadowSide=this.shadowSide),void 0!==this.sizeAttenuation&&(n.sizeAttenuation=this.sizeAttenuation),1!==this.blending&&(n.blending=this.blending),0!==this.side&&(n.side=this.side),!0===this.vertexColors&&(n.vertexColors=!0),this.opacity<1&&(n.opacity=this.opacity),!0===this.transparent&&(n.transparent=!0),this.blendSrc!==r&&(n.blendSrc=this.blendSrc),this.blendDst!==s&&(n.blendDst=this.blendDst),this.blendEquation!==i&&(n.blendEquation=this.blendEquation),null!==this.blendSrcAlpha&&(n.blendSrcAlpha=this.blendSrcAlpha),null!==this.blendDstAlpha&&(n.blendDstAlpha=this.blendDstAlpha),null!==this.blendEquationAlpha&&(n.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(n.blendColor=this.blendColor.getHex()),0!==this.blendAlpha&&(n.blendAlpha=this.blendAlpha),3!==this.depthFunc&&(n.depthFunc=this.depthFunc),!1===this.depthTest&&(n.depthTest=this.depthTest),!1===this.depthWrite&&(n.depthWrite=this.depthWrite),!1===this.colorWrite&&(n.colorWrite=this.colorWrite),255!==this.stencilWriteMask&&(n.stencilWriteMask=this.stencilWriteMask),519!==this.stencilFunc&&(n.stencilFunc=this.stencilFunc),0!==this.stencilRef&&(n.stencilRef=this.stencilRef),255!==this.stencilFuncMask&&(n.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==Vt&&(n.stencilFail=this.stencilFail),this.stencilZFail!==Vt&&(n.stencilZFail=this.stencilZFail),this.stencilZPass!==Vt&&(n.stencilZPass=this.stencilZPass),!0===this.stencilWrite&&(n.stencilWrite=this.stencilWrite),void 0!==this.rotation&&0!==this.rotation&&(n.rotation=this.rotation),!0===this.polygonOffset&&(n.polygonOffset=!0),0!==this.polygonOffsetFactor&&(n.polygonOffsetFactor=this.polygonOffsetFactor),0!==this.polygonOffsetUnits&&(n.polygonOffsetUnits=this.polygonOffsetUnits),void 0!==this.linewidth&&1!==this.linewidth&&(n.linewidth=this.linewidth),void 0!==this.dashSize&&(n.dashSize=this.dashSize),void 0!==this.gapSize&&(n.gapSize=this.gapSize),void 0!==this.scale&&(n.scale=this.scale),!0===this.dithering&&(n.dithering=!0),this.alphaTest>0&&(n.alphaTest=this.alphaTest),!0===this.alphaHash&&(n.alphaHash=!0),!0===this.alphaToCoverage&&(n.alphaToCoverage=!0),!0===this.premultipliedAlpha&&(n.premultipliedAlpha=!0),!0===this.forceSinglePass&&(n.forceSinglePass=!0),!0===this.wireframe&&(n.wireframe=!0),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),"round"!==this.wireframeLinecap&&(n.wireframeLinecap=this.wireframeLinecap),"round"!==this.wireframeLinejoin&&(n.wireframeLinejoin=this.wireframeLinejoin),!0===this.flatShading&&(n.flatShading=!0),!1===this.visible&&(n.visible=!1),!1===this.toneMapped&&(n.toneMapped=!1),!1===this.fog&&(n.fog=!1),Object.keys(this.userData).length>0&&(n.userData=this.userData),e){const e=a(t.textures),i=a(t.images);e.length>0&&(n.textures=e),i.length>0&&(n.images=i)}return n}clone(){return(new this.constructor).copy(this)}copy(t){this.name=t.name,this.blending=t.blending,this.side=t.side,this.vertexColors=t.vertexColors,this.opacity=t.opacity,this.transparent=t.transparent,this.blendSrc=t.blendSrc,this.blendDst=t.blendDst,this.blendEquation=t.blendEquation,this.blendSrcAlpha=t.blendSrcAlpha,this.blendDstAlpha=t.blendDstAlpha,this.blendEquationAlpha=t.blendEquationAlpha,this.blendColor.copy(t.blendColor),this.blendAlpha=t.blendAlpha,this.depthFunc=t.depthFunc,this.depthTest=t.depthTest,this.depthWrite=t.depthWrite,this.stencilWriteMask=t.stencilWriteMask,this.stencilFunc=t.stencilFunc,this.stencilRef=t.stencilRef,this.stencilFuncMask=t.stencilFuncMask,this.stencilFail=t.stencilFail,this.stencilZFail=t.stencilZFail,this.stencilZPass=t.stencilZPass,this.stencilWrite=t.stencilWrite;const e=t.clippingPlanes;let n=null;if(null!==e){const t=e.length;n=new Array(t);for(let i=0;i!==t;++i)n[i]=e[i].clone()}return this.clippingPlanes=n,this.clipIntersection=t.clipIntersection,this.clipShadows=t.clipShadows,this.shadowSide=t.shadowSide,this.colorWrite=t.colorWrite,this.precision=t.precision,this.polygonOffset=t.polygonOffset,this.polygonOffsetFactor=t.polygonOffsetFactor,this.polygonOffsetUnits=t.polygonOffsetUnits,this.dithering=t.dithering,this.alphaTest=t.alphaTest,this.alphaHash=t.alphaHash,this.alphaToCoverage=t.alphaToCoverage,this.premultipliedAlpha=t.premultipliedAlpha,this.forceSinglePass=t.forceSinglePass,this.visible=t.visible,this.toneMapped=t.toneMapped,this.userData=JSON.parse(JSON.stringify(t.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(t){!0===t&&this.version++}onBuild(){console.warn("Material: onBuild() has been removed.")}}class oi extends ai{constructor(t){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new ii(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Mn,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.specularMap=t.specularMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.envMapRotation.copy(t.envMapRotation),this.combine=t.combine,this.reflectivity=t.reflectivity,this.refractionRatio=t.refractionRatio,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.fog=t.fog,this}}const li=ci();function ci(){const t=new ArrayBuffer(4),e=new Float32Array(t),n=new Uint32Array(t),i=new Uint32Array(512),r=new Uint32Array(512);for(let t=0;t<256;++t){const e=t-127;e<-27?(i[t]=0,i[256|t]=32768,r[t]=24,r[256|t]=24):e<-14?(i[t]=1024>>-e-14,i[256|t]=1024>>-e-14|32768,r[t]=-e-1,r[256|t]=-e-1):e<=15?(i[t]=e+15<<10,i[256|t]=e+15<<10|32768,r[t]=13,r[256|t]=13):e<128?(i[t]=31744,i[256|t]=64512,r[t]=24,r[256|t]=24):(i[t]=31744,i[256|t]=64512,r[t]=13,r[256|t]=13)}const s=new Uint32Array(2048),a=new Uint32Array(64),o=new Uint32Array(64);for(let t=1;t<1024;++t){let e=t<<13,n=0;for(;0==(8388608&e);)e<<=1,n-=8388608;e&=-8388609,n+=947912704,s[t]=e|n}for(let t=1024;t<2048;++t)s[t]=939524096+(t-1024<<13);for(let t=1;t<31;++t)a[t]=t<<23;a[31]=1199570944,a[32]=2147483648;for(let t=33;t<63;++t)a[t]=2147483648+(t-32<<23);a[63]=3347054592;for(let t=1;t<64;++t)32!==t&&(o[t]=1024);return{floatView:e,uint32View:n,baseTable:i,shiftTable:r,mantissaTable:s,exponentTable:a,offsetTable:o}}function hi(t){Math.abs(t)>65504&&console.warn("THREE.DataUtils.toHalfFloat(): Value out of range."),t=$t(t,-65504,65504),li.floatView[0]=t;const e=li.uint32View[0],n=e>>23&511;return li.baseTable[n]+((8388607&e)>>li.shiftTable[n])}function ui(t){const e=t>>10;return li.uint32View[0]=li.mantissaTable[li.offsetTable[e]+(1023&t)]+li.exponentTable[e],li.floatView[0]}const di={toHalfFloat:hi,fromHalfFloat:ui},pi=new De,mi=new re;class fi{constructor(t,e,n=!1){if(Array.isArray(t))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,this.name="",this.array=t,this.itemSize=e,this.count=void 0!==t?t.length/e:0,this.normalized=n,this.usage=Ht,this.updateRanges=[],this.gpuType=R,this.version=0}onUploadCallback(){}set needsUpdate(t){!0===t&&this.version++}setUsage(t){return this.usage=t,this}addUpdateRange(t,e){this.updateRanges.push({start:t,count:e})}clearUpdateRanges(){this.updateRanges.length=0}copy(t){return this.name=t.name,this.array=new t.array.constructor(t.array),this.itemSize=t.itemSize,this.count=t.count,this.normalized=t.normalized,this.usage=t.usage,this.gpuType=t.gpuType,this}copyAt(t,e,n){t*=this.itemSize,n*=e.itemSize;for(let i=0,r=this.itemSize;i0&&(t.userData=this.userData),void 0!==this.parameters){const e=this.parameters;for(const n in e)void 0!==e[n]&&(t[n]=e[n]);return t}t.data={attributes:{}};const e=this.index;null!==e&&(t.data.index={type:e.array.constructor.name,array:Array.prototype.slice.call(e.array)});const n=this.attributes;for(const e in n){const i=n[e];t.data.attributes[e]=i.toJSON(t.data)}const i={};let r=!1;for(const e in this.morphAttributes){const n=this.morphAttributes[e],s=[];for(let e=0,i=n.length;e0&&(i[e]=s,r=!0)}r&&(t.data.morphAttributes=i,t.data.morphTargetsRelative=this.morphTargetsRelative);const s=this.groups;s.length>0&&(t.data.groups=JSON.parse(JSON.stringify(s)));const a=this.boundingSphere;return null!==a&&(t.data.boundingSphere={center:a.center.toArray(),radius:a.radius}),t}clone(){return(new this.constructor).copy(this)}copy(t){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const e={};this.name=t.name;const n=t.index;null!==n&&this.setIndex(n.clone(e));const i=t.attributes;for(const t in i){const n=i[t];this.setAttribute(t,n.clone(e))}const r=t.morphAttributes;for(const t in r){const n=[],i=r[t];for(let t=0,r=i.length;t0){const n=t[e[0]];if(void 0!==n){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let t=0,e=n.length;t(t.far-t.near)**2)return}Ai.copy(r).invert(),Ci.copy(t.ray).applyMatrix4(Ai),null!==n.boundingBox&&!1===Ci.intersectsBox(n.boundingBox)||this._computeIntersections(t,e,Ci)}}_computeIntersections(t,e,n){let i;const r=this.geometry,s=this.material,a=r.index,o=r.attributes.position,l=r.attributes.uv,c=r.attributes.uv1,h=r.attributes.normal,u=r.groups,d=r.drawRange;if(null!==a)if(Array.isArray(s))for(let r=0,o=u.length;rn.far?null:{distance:c,point:Fi.clone(),object:t}}(t,e,n,i,Ii,Li,Ui,Oi);if(h){const t=new De;$n.getBarycoord(Oi,Ii,Li,Ui,t),r&&(h.uv=$n.getInterpolatedAttribute(r,o,l,c,t,new re)),s&&(h.uv1=$n.getInterpolatedAttribute(s,o,l,c,t,new re)),a&&(h.normal=$n.getInterpolatedAttribute(a,o,l,c,t,new De),h.normal.dot(i.direction)>0&&h.normal.multiplyScalar(-1));const e={a:o,b:l,c,normal:new De,materialIndex:0};$n.getNormal(Ii,Li,Ui,e.normal),h.face=e,h.barycoord=t}return h}class ki extends Ei{constructor(t=1,e=1,n=1,i=1,r=1,s=1){super(),this.type="BoxGeometry",this.parameters={width:t,height:e,depth:n,widthSegments:i,heightSegments:r,depthSegments:s};const a=this;i=Math.floor(i),r=Math.floor(r),s=Math.floor(s);const o=[],l=[],c=[],h=[];let u=0,d=0;function p(t,e,n,i,r,s,p,m,f,g,v){const _=s/f,y=p/g,x=s/2,M=p/2,S=m/2,b=f+1,w=g+1;let T=0,E=0;const A=new De;for(let s=0;s0?1:-1,c.push(A.x,A.y,A.z),h.push(o/f),h.push(1-s/g),T+=1}}for(let t=0;t0&&(e.defines=this.defines),e.vertexShader=this.vertexShader,e.fragmentShader=this.fragmentShader,e.lights=this.lights,e.clipping=this.clipping;const n={};for(const t in this.extensions)!0===this.extensions[t]&&(n[t]=!0);return Object.keys(n).length>0&&(e.extensions=n),e}}class ji extends Bn{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new un,this.projectionMatrix=new un,this.projectionMatrixInverse=new un,this.coordinateSystem=Wt}copy(t,e){return super.copy(t,e),this.matrixWorldInverse.copy(t.matrixWorldInverse),this.projectionMatrix.copy(t.projectionMatrix),this.projectionMatrixInverse.copy(t.projectionMatrixInverse),this.coordinateSystem=t.coordinateSystem,this}getWorldDirection(t){return super.getWorldDirection(t).negate()}updateMatrixWorld(t){super.updateMatrixWorld(t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(t,e){super.updateWorldMatrix(t,e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return(new this.constructor).copy(this)}}const qi=new De,Yi=new re,Zi=new re;class Ji extends ji{constructor(t=50,e=1,n=.1,i=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=t,this.zoom=1,this.near=n,this.far=i,this.focus=10,this.aspect=e,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(t,e){return super.copy(t,e),this.fov=t.fov,this.zoom=t.zoom,this.near=t.near,this.far=t.far,this.focus=t.focus,this.aspect=t.aspect,this.view=null===t.view?null:Object.assign({},t.view),this.filmGauge=t.filmGauge,this.filmOffset=t.filmOffset,this}setFocalLength(t){const e=.5*this.getFilmHeight()/t;this.fov=2*Jt*Math.atan(e),this.updateProjectionMatrix()}getFocalLength(){const t=Math.tan(.5*Zt*this.fov);return.5*this.getFilmHeight()/t}getEffectiveFOV(){return 2*Jt*Math.atan(Math.tan(.5*Zt*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(t,e,n){qi.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),e.set(qi.x,qi.y).multiplyScalar(-t/qi.z),qi.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(qi.x,qi.y).multiplyScalar(-t/qi.z)}getViewSize(t,e){return this.getViewBounds(t,Yi,Zi),e.subVectors(Zi,Yi)}setViewOffset(t,e,n,i,r,s){this.aspect=t/e,null===this.view&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=t,this.view.fullHeight=e,this.view.offsetX=n,this.view.offsetY=i,this.view.width=r,this.view.height=s,this.updateProjectionMatrix()}clearViewOffset(){null!==this.view&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const t=this.near;let e=t*Math.tan(.5*Zt*this.fov)/this.zoom,n=2*e,i=this.aspect*n,r=-.5*i;const s=this.view;if(null!==this.view&&this.view.enabled){const t=s.fullWidth,a=s.fullHeight;r+=s.offsetX*i/t,e-=s.offsetY*n/a,i*=s.width/t,n*=s.height/a}const a=this.filmOffset;0!==a&&(r+=t*a/this.getFilmWidth()),this.projectionMatrix.makePerspective(r,r+i,e,e-n,t,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(t){const e=super.toJSON(t);return e.object.fov=this.fov,e.object.zoom=this.zoom,e.object.near=this.near,e.object.far=this.far,e.object.focus=this.focus,e.object.aspect=this.aspect,null!==this.view&&(e.object.view=Object.assign({},this.view)),e.object.filmGauge=this.filmGauge,e.object.filmOffset=this.filmOffset,e}}const Ki=-90;class $i extends Bn{constructor(t,e,n){super(),this.type="CubeCamera",this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;const i=new Ji(Ki,1,t,e);i.layers=this.layers,this.add(i);const r=new Ji(Ki,1,t,e);r.layers=this.layers,this.add(r);const s=new Ji(Ki,1,t,e);s.layers=this.layers,this.add(s);const a=new Ji(Ki,1,t,e);a.layers=this.layers,this.add(a);const o=new Ji(Ki,1,t,e);o.layers=this.layers,this.add(o);const l=new Ji(Ki,1,t,e);l.layers=this.layers,this.add(l)}updateCoordinateSystem(){const t=this.coordinateSystem,e=this.children.concat(),[n,i,r,s,a,o]=e;for(const t of e)this.remove(t);if(t===Wt)n.up.set(0,1,0),n.lookAt(1,0,0),i.up.set(0,1,0),i.lookAt(-1,0,0),r.up.set(0,0,-1),r.lookAt(0,1,0),s.up.set(0,0,1),s.lookAt(0,-1,0),a.up.set(0,1,0),a.lookAt(0,0,1),o.up.set(0,1,0),o.lookAt(0,0,-1);else{if(t!==Xt)throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+t);n.up.set(0,-1,0),n.lookAt(-1,0,0),i.up.set(0,-1,0),i.lookAt(1,0,0),r.up.set(0,0,1),r.lookAt(0,1,0),s.up.set(0,0,-1),s.lookAt(0,-1,0),a.up.set(0,-1,0),a.lookAt(0,0,1),o.up.set(0,-1,0),o.lookAt(0,0,-1)}for(const t of e)this.add(t),t.updateMatrixWorld()}update(t,e){null===this.parent&&this.updateMatrixWorld();const{renderTarget:n,activeMipmapLevel:i}=this;this.coordinateSystem!==t.coordinateSystem&&(this.coordinateSystem=t.coordinateSystem,this.updateCoordinateSystem());const[r,s,a,o,l,c]=this.children,h=t.getRenderTarget(),u=t.getActiveCubeFace(),d=t.getActiveMipmapLevel(),p=t.xr.enabled;t.xr.enabled=!1;const m=n.texture.generateMipmaps;n.texture.generateMipmaps=!1,t.setRenderTarget(n,0,i),t.render(e,r),t.setRenderTarget(n,1,i),t.render(e,s),t.setRenderTarget(n,2,i),t.render(e,a),t.setRenderTarget(n,3,i),t.render(e,o),t.setRenderTarget(n,4,i),t.render(e,l),n.texture.generateMipmaps=m,t.setRenderTarget(n,5,i),t.render(e,c),t.setRenderTarget(h,u,d),t.xr.enabled=p,n.texture.needsPMREMUpdate=!0}}class Qi extends Ae{constructor(t,e,n,i,r,s,a,o,l,h){super(t=void 0!==t?t:[],e=void 0!==e?e:c,n,i,r,s,a,o,l,h),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(t){this.image=t}}class tr extends Pe{constructor(t=1,e={}){super(t,t,e),this.isWebGLCubeRenderTarget=!0;const n={width:t,height:t,depth:1},i=[n,n,n,n,n,n];this.texture=new Qi(i,e.mapping,e.wrapS,e.wrapT,e.magFilter,e.minFilter,e.format,e.type,e.anisotropy,e.colorSpace),this.texture.isRenderTargetTexture=!0,this.texture.generateMipmaps=void 0!==e.generateMipmaps&&e.generateMipmaps,this.texture.minFilter=void 0!==e.minFilter?e.minFilter:x}fromEquirectangularTexture(t,e){this.texture.type=e.type,this.texture.colorSpace=e.colorSpace,this.texture.generateMipmaps=e.generateMipmaps,this.texture.minFilter=e.minFilter,this.texture.magFilter=e.magFilter;const n={tEquirect:{value:null}},i="\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\tvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\n\t\t\t\t\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n\n\t\t\t\t}\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvWorldDirection = transformDirection( position, modelMatrix );\n\n\t\t\t\t\t#include \n\t\t\t\t\t#include \n\n\t\t\t\t}\n\t\t\t",r="\n\n\t\t\t\tuniform sampler2D tEquirect;\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\t#include \n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvec3 direction = normalize( vWorldDirection );\n\n\t\t\t\t\tvec2 sampleUV = equirectUv( direction );\n\n\t\t\t\t\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\n\t\t\t\t}\n\t\t\t",s=new ki(5,5,5),a=new Xi({name:"CubemapFromEquirect",uniforms:Vi(n),vertexShader:i,fragmentShader:r,side:1,blending:0});a.uniforms.tEquirect.value=e;const o=new Bi(s,a),l=e.minFilter;return e.minFilter===S&&(e.minFilter=x),new $i(1,10,this).update(t,o),e.minFilter=l,o.geometry.dispose(),o.material.dispose(),this}clear(t,e,n,i){const r=t.getRenderTarget();for(let r=0;r<6;r++)t.setRenderTarget(this,r),t.clear(e,n,i);t.setRenderTarget(r)}}const er=new De,nr=new De,ir=new se;class rr{constructor(t=new De(1,0,0),e=0){this.isPlane=!0,this.normal=t,this.constant=e}set(t,e){return this.normal.copy(t),this.constant=e,this}setComponents(t,e,n,i){return this.normal.set(t,e,n),this.constant=i,this}setFromNormalAndCoplanarPoint(t,e){return this.normal.copy(t),this.constant=-e.dot(this.normal),this}setFromCoplanarPoints(t,e,n){const i=er.subVectors(n,e).cross(nr.subVectors(t,e)).normalize();return this.setFromNormalAndCoplanarPoint(i,t),this}copy(t){return this.normal.copy(t.normal),this.constant=t.constant,this}normalize(){const t=1/this.normal.length();return this.normal.multiplyScalar(t),this.constant*=t,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(t){return this.normal.dot(t)+this.constant}distanceToSphere(t){return this.distanceToPoint(t.center)-t.radius}projectPoint(t,e){return e.copy(t).addScaledVector(this.normal,-this.distanceToPoint(t))}intersectLine(t,e){const n=t.delta(er),i=this.normal.dot(n);if(0===i)return 0===this.distanceToPoint(t.start)?e.copy(t.start):null;const r=-(t.start.dot(this.normal)+this.constant)/i;return r<0||r>1?null:e.copy(t.start).addScaledVector(n,r)}intersectsLine(t){const e=this.distanceToPoint(t.start),n=this.distanceToPoint(t.end);return e<0&&n>0||n<0&&e>0}intersectsBox(t){return t.intersectsPlane(this)}intersectsSphere(t){return t.intersectsPlane(this)}coplanarPoint(t){return t.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(t,e){const n=e||ir.getNormalMatrix(t),i=this.coplanarPoint(er).applyMatrix4(t),r=this.normal.applyMatrix3(n).normalize();return this.constant=-i.dot(r),this}translate(t){return this.constant-=t.dot(this.normal),this}equals(t){return t.normal.equals(this.normal)&&t.constant===this.constant}clone(){return(new this.constructor).copy(this)}}const sr=new en,ar=new De;class or{constructor(t=new rr,e=new rr,n=new rr,i=new rr,r=new rr,s=new rr){this.planes=[t,e,n,i,r,s]}set(t,e,n,i,r,s){const a=this.planes;return a[0].copy(t),a[1].copy(e),a[2].copy(n),a[3].copy(i),a[4].copy(r),a[5].copy(s),this}copy(t){const e=this.planes;for(let n=0;n<6;n++)e[n].copy(t.planes[n]);return this}setFromProjectionMatrix(t,e=2e3){const n=this.planes,i=t.elements,r=i[0],s=i[1],a=i[2],o=i[3],l=i[4],c=i[5],h=i[6],u=i[7],d=i[8],p=i[9],m=i[10],f=i[11],g=i[12],v=i[13],_=i[14],y=i[15];if(n[0].setComponents(o-r,u-l,f-d,y-g).normalize(),n[1].setComponents(o+r,u+l,f+d,y+g).normalize(),n[2].setComponents(o+s,u+c,f+p,y+v).normalize(),n[3].setComponents(o-s,u-c,f-p,y-v).normalize(),n[4].setComponents(o-a,u-h,f-m,y-_).normalize(),e===Wt)n[5].setComponents(o+a,u+h,f+m,y+_).normalize();else{if(e!==Xt)throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+e);n[5].setComponents(a,h,m,_).normalize()}return this}intersectsObject(t){if(void 0!==t.boundingSphere)null===t.boundingSphere&&t.computeBoundingSphere(),sr.copy(t.boundingSphere).applyMatrix4(t.matrixWorld);else{const e=t.geometry;null===e.boundingSphere&&e.computeBoundingSphere(),sr.copy(e.boundingSphere).applyMatrix4(t.matrixWorld)}return this.intersectsSphere(sr)}intersectsSprite(t){return sr.center.set(0,0,0),sr.radius=.7071067811865476,sr.applyMatrix4(t.matrixWorld),this.intersectsSphere(sr)}intersectsSphere(t){const e=this.planes,n=t.center,i=-t.radius;for(let t=0;t<6;t++)if(e[t].distanceToPoint(n)0?t.max.x:t.min.x,ar.y=i.normal.y>0?t.max.y:t.min.y,ar.z=i.normal.z>0?t.max.z:t.min.z,i.distanceToPoint(ar)<0)return!1}return!0}containsPoint(t){const e=this.planes;for(let n=0;n<6;n++)if(e[n].distanceToPoint(t)<0)return!1;return!0}clone(){return(new this.constructor).copy(this)}}function lr(){let t=null,e=!1,n=null,i=null;function r(e,s){n(e,s),i=t.requestAnimationFrame(r)}return{start:function(){!0!==e&&null!==n&&(i=t.requestAnimationFrame(r),e=!0)},stop:function(){t.cancelAnimationFrame(i),e=!1},setAnimationLoop:function(t){n=t},setContext:function(e){t=e}}}function cr(t){const e=new WeakMap;return{get:function(t){return t.isInterleavedBufferAttribute&&(t=t.data),e.get(t)},remove:function(n){n.isInterleavedBufferAttribute&&(n=n.data);const i=e.get(n);i&&(t.deleteBuffer(i.buffer),e.delete(n))},update:function(n,i){if(n.isInterleavedBufferAttribute&&(n=n.data),n.isGLBufferAttribute){const t=e.get(n);return void((!t||t.versiont.start-e.start));let e=0;for(let t=1;t 0\n\tvec4 plane;\n\t#ifdef ALPHA_TO_COVERAGE\n\t\tfloat distanceToPlane, distanceGradient;\n\t\tfloat clipOpacity = 1.0;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tdistanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n\t\t\tdistanceGradient = fwidth( distanceToPlane ) / 2.0;\n\t\t\tclipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n\t\t\tif ( clipOpacity == 0.0 ) discard;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\t\tfloat unionClipOpacity = 1.0;\n\t\t\t#pragma unroll_loop_start\n\t\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\t\tplane = clippingPlanes[ i ];\n\t\t\t\tdistanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n\t\t\t\tdistanceGradient = fwidth( distanceToPlane ) / 2.0;\n\t\t\t\tunionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n\t\t\t}\n\t\t\t#pragma unroll_loop_end\n\t\t\tclipOpacity *= 1.0 - unionClipOpacity;\n\t\t#endif\n\t\tdiffuseColor.a *= clipOpacity;\n\t\tif ( diffuseColor.a == 0.0 ) discard;\n\t#else\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\t\tbool clipped = true;\n\t\t\t#pragma unroll_loop_start\n\t\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\t\tplane = clippingPlanes[ i ];\n\t\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t\t}\n\t\t\t#pragma unroll_loop_end\n\t\t\tif ( clipped ) discard;\n\t\t#endif\n\t#endif\n#endif",clipping_planes_pars_fragment:"#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif",clipping_planes_pars_vertex:"#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif",clipping_planes_vertex:"#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif",color_fragment:"#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif",color_pars_fragment:"#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif",color_pars_vertex:"#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )\n\tvarying vec3 vColor;\n#endif",color_vertex:"#if defined( USE_COLOR_ALPHA )\n\tvColor = vec4( 1.0 );\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )\n\tvColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n\tvColor *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.xyz *= instanceColor.xyz;\n#endif\n#ifdef USE_BATCHING_COLOR\n\tvec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) );\n\tvColor.xyz *= batchingColor.xyz;\n#endif",common:"#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement( a ) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nvec3 pow2( const in vec3 x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\nfloat average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract( sin( sn ) * c );\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\n#ifdef USE_ALPHAHASH\n\tvarying vec3 vPosition;\n#endif\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}\nvec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat F_Schlick( const in float f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n} // validated",cube_uv_reflection_fragment:"#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_minTileSize 16.0\n\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\thighp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tuv.x += filterInt * 3.0 * cubeUV_minTileSize;\n\t\tuv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );\n\t\tuv.x *= CUBEUV_TEXEL_WIDTH;\n\t\tuv.y *= CUBEUV_TEXEL_HEIGHT;\n\t\t#ifdef texture2DGradEXT\n\t\t\treturn texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;\n\t\t#else\n\t\t\treturn texture2D( envMap, uv ).rgb;\n\t\t#endif\n\t}\n\t#define cubeUV_r0 1.0\n\t#define cubeUV_m0 - 2.0\n\t#define cubeUV_r1 0.8\n\t#define cubeUV_m1 - 1.0\n\t#define cubeUV_r4 0.4\n\t#define cubeUV_m4 2.0\n\t#define cubeUV_r5 0.305\n\t#define cubeUV_m5 3.0\n\t#define cubeUV_r6 0.21\n\t#define cubeUV_m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= cubeUV_r1 ) {\n\t\t\tmip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;\n\t\t} else if ( roughness >= cubeUV_r4 ) {\n\t\t\tmip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;\n\t\t} else if ( roughness >= cubeUV_r5 ) {\n\t\t\tmip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;\n\t\t} else if ( roughness >= cubeUV_r6 ) {\n\t\t\tmip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif",defaultnormal_vertex:"vec3 transformedNormal = objectNormal;\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = objectTangent;\n#endif\n#ifdef USE_BATCHING\n\tmat3 bm = mat3( batchingMatrix );\n\ttransformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) );\n\ttransformedNormal = bm * transformedNormal;\n\t#ifdef USE_TANGENT\n\t\ttransformedTangent = bm * transformedTangent;\n\t#endif\n#endif\n#ifdef USE_INSTANCING\n\tmat3 im = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) );\n\ttransformedNormal = im * transformedNormal;\n\t#ifdef USE_TANGENT\n\t\ttransformedTangent = im * transformedTangent;\n\t#endif\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\ttransformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif",displacementmap_pars_vertex:"#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif",displacementmap_vertex:"#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );\n#endif",emissivemap_fragment:"#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif",emissivemap_pars_fragment:"#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif",colorspace_fragment:"gl_FragColor = linearToOutputTexel( gl_FragColor );",colorspace_pars_fragment:"\nconst mat3 LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 = mat3(\n\tvec3( 0.8224621, 0.177538, 0.0 ),\n\tvec3( 0.0331941, 0.9668058, 0.0 ),\n\tvec3( 0.0170827, 0.0723974, 0.9105199 )\n);\nconst mat3 LINEAR_DISPLAY_P3_TO_LINEAR_SRGB = mat3(\n\tvec3( 1.2249401, - 0.2249404, 0.0 ),\n\tvec3( - 0.0420569, 1.0420571, 0.0 ),\n\tvec3( - 0.0196376, - 0.0786361, 1.0982735 )\n);\nvec4 LinearSRGBToLinearDisplayP3( in vec4 value ) {\n\treturn vec4( value.rgb * LINEAR_SRGB_TO_LINEAR_DISPLAY_P3, value.a );\n}\nvec4 LinearDisplayP3ToLinearSRGB( in vec4 value ) {\n\treturn vec4( value.rgb * LINEAR_DISPLAY_P3_TO_LINEAR_SRGB, value.a );\n}\nvec4 LinearTransferOETF( in vec4 value ) {\n\treturn value;\n}\nvec4 sRGBTransferOETF( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}",envmap_fragment:"#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif",envmap_common_pars_fragment:"#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\tuniform mat3 envMapRotation;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif",envmap_pars_fragment:"#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif",envmap_pars_vertex:"#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif",envmap_physical_pars_fragment:"#ifdef USE_ENVMAP\n\tvec3 getIBLIrradiance( const in vec3 normal ) {\n\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 );\n\t\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\tvec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\tvec3 reflectVec = reflect( - viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness );\n\t\t\treturn envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\t#ifdef USE_ANISOTROPY\n\t\tvec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {\n\t\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\t\tvec3 bentNormal = cross( bitangent, viewDir );\n\t\t\t\tbentNormal = normalize( cross( bentNormal, bitangent ) );\n\t\t\t\tbentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );\n\t\t\t\treturn getIBLRadiance( viewDir, bentNormal, roughness );\n\t\t\t#else\n\t\t\t\treturn vec3( 0.0 );\n\t\t\t#endif\n\t\t}\n\t#endif\n#endif",envmap_vertex:"#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif",fog_vertex:"#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif",fog_pars_vertex:"#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif",fog_fragment:"#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, vFogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif",fog_pars_fragment:"#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float vFogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif",gradientmap_pars_fragment:"#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn vec3( texture2D( gradientMap, coord ).r );\n\t#else\n\t\tvec2 fw = fwidth( coord ) * 0.5;\n\t\treturn mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );\n\t#endif\n}",lightmap_pars_fragment:"#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif",lights_lambert_fragment:"LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;",lights_lambert_pars_fragment:"varying vec3 vViewPosition;\nstruct LambertMaterial {\n\tvec3 diffuseColor;\n\tfloat specularStrength;\n};\nvoid RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Lambert\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Lambert",lights_pars_begin:"uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\n#if defined( USE_LIGHT_PROBES )\n\tuniform vec3 lightProbe[ 9 ];\n#endif\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {\n\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\treturn irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\tif ( cutoffDistance > 0.0 ) {\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t}\n\treturn distanceFalloff;\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n\treturn smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) {\n\t\tlight.color = directionalLight.color;\n\t\tlight.direction = directionalLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometryPosition;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tlight.color = pointLight.color;\n\t\tlight.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometryPosition;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat angleCos = dot( light.direction, spotLight.direction );\n\t\tfloat spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\tif ( spotAttenuation > 0.0 ) {\n\t\t\tfloat lightDistance = length( lVector );\n\t\t\tlight.color = spotLight.color * spotAttenuation;\n\t\t\tlight.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t\t} else {\n\t\t\tlight.color = vec3( 0.0 );\n\t\t\tlight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {\n\t\tfloat dotNL = dot( normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\treturn irradiance;\n\t}\n#endif",lights_toon_fragment:"ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;",lights_toon_pars_fragment:"varying vec3 vViewPosition;\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon",lights_phong_fragment:"BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;",lights_phong_pars_fragment:"varying vec3 vViewPosition;\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong",lights_physical_fragment:"PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n\tmaterial.ior = ior;\n\t#ifdef USE_SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULAR_COLORMAP\n\t\t\tspecularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb;\n\t\t#endif\n\t\t#ifdef USE_SPECULAR_INTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularColorFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_DISPERSION\n\tmaterial.dispersion = dispersion;\n#endif\n#ifdef USE_IRIDESCENCE\n\tmaterial.iridescence = iridescence;\n\tmaterial.iridescenceIOR = iridescenceIOR;\n\t#ifdef USE_IRIDESCENCEMAP\n\t\tmaterial.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r;\n\t#endif\n\t#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\t\tmaterial.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum;\n\t#else\n\t\tmaterial.iridescenceThickness = iridescenceThicknessMaximum;\n\t#endif\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheenColor;\n\t#ifdef USE_SHEEN_COLORMAP\n\t\tmaterial.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\t#ifdef USE_ANISOTROPYMAP\n\t\tmat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x );\n\t\tvec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb;\n\t\tvec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b;\n\t#else\n\t\tvec2 anisotropyV = anisotropyVector;\n\t#endif\n\tmaterial.anisotropy = length( anisotropyV );\n\tif( material.anisotropy == 0.0 ) {\n\t\tanisotropyV = vec2( 1.0, 0.0 );\n\t} else {\n\t\tanisotropyV /= material.anisotropy;\n\t\tmaterial.anisotropy = saturate( material.anisotropy );\n\t}\n\tmaterial.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) );\n\tmaterial.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y;\n\tmaterial.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y;\n#endif",lights_physical_pars_fragment:"struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat roughness;\n\tvec3 specularColor;\n\tfloat specularF90;\n\tfloat dispersion;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_IRIDESCENCE\n\t\tfloat iridescence;\n\t\tfloat iridescenceIOR;\n\t\tfloat iridescenceThickness;\n\t\tvec3 iridescenceFresnel;\n\t\tvec3 iridescenceF0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenColor;\n\t\tfloat sheenRoughness;\n\t#endif\n\t#ifdef IOR\n\t\tfloat ior;\n\t#endif\n\t#ifdef USE_TRANSMISSION\n\t\tfloat transmission;\n\t\tfloat transmissionAlpha;\n\t\tfloat thickness;\n\t\tfloat attenuationDistance;\n\t\tvec3 attenuationColor;\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tfloat anisotropy;\n\t\tfloat alphaT;\n\t\tvec3 anisotropyT;\n\t\tvec3 anisotropyB;\n\t#endif\n};\nvec3 clearcoatSpecularDirect = vec3( 0.0 );\nvec3 clearcoatSpecularIndirect = vec3( 0.0 );\nvec3 sheenSpecularDirect = vec3( 0.0 );\nvec3 sheenSpecularIndirect = vec3(0.0 );\nvec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {\n float x = clamp( 1.0 - dotVH, 0.0, 1.0 );\n float x2 = x * x;\n float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );\n return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );\n}\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\n#ifdef USE_ANISOTROPY\n\tfloat V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) {\n\t\tfloat gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) );\n\t\tfloat gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) );\n\t\tfloat v = 0.5 / ( gv + gl );\n\t\treturn saturate(v);\n\t}\n\tfloat D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) {\n\t\tfloat a2 = alphaT * alphaB;\n\t\thighp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH );\n\t\thighp float v2 = dot( v, v );\n\t\tfloat w2 = a2 / v2;\n\t\treturn RECIPROCAL_PI * a2 * pow2 ( w2 );\n\t}\n#endif\n#ifdef USE_CLEARCOAT\n\tvec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) {\n\t\tvec3 f0 = material.clearcoatF0;\n\t\tfloat f90 = material.clearcoatF90;\n\t\tfloat roughness = material.clearcoatRoughness;\n\t\tfloat alpha = pow2( roughness );\n\t\tvec3 halfDir = normalize( lightDir + viewDir );\n\t\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\t\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\t\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\t\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\t\tvec3 F = F_Schlick( f0, f90, dotVH );\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t\treturn F * ( V * D );\n\t}\n#endif\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {\n\tvec3 f0 = material.specularColor;\n\tfloat f90 = material.specularF90;\n\tfloat roughness = material.roughness;\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( f0, f90, dotVH );\n\t#ifdef USE_IRIDESCENCE\n\t\tF = mix( F, material.iridescenceFresnel, material.iridescence );\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tfloat dotTL = dot( material.anisotropyT, lightDir );\n\t\tfloat dotTV = dot( material.anisotropyT, viewDir );\n\t\tfloat dotTH = dot( material.anisotropyT, halfDir );\n\t\tfloat dotBL = dot( material.anisotropyB, lightDir );\n\t\tfloat dotBV = dot( material.anisotropyB, viewDir );\n\t\tfloat dotBH = dot( material.anisotropyB, halfDir );\n\t\tfloat V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL );\n\t\tfloat D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH );\n\t#else\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t#endif\n\treturn F * ( V * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n\tfloat alpha = pow2( roughness );\n\tfloat invAlpha = 1.0 / alpha;\n\tfloat cos2h = dotNH * dotNH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n\treturn saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );\n}\nvec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat D = D_Charlie( sheenRoughness, dotNH );\n\tfloat V = V_Neubelt( dotNV, dotNL );\n\treturn sheenColor * ( D * V );\n}\n#endif\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat r2 = roughness * roughness;\n\tfloat a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;\n\tfloat b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;\n\tfloat DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );\n\treturn saturate( DG * RECIPROCAL_PI );\n}\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n\treturn fab;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\n#ifdef USE_IRIDESCENCE\nvoid computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#else\nvoid computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#endif\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\t#ifdef USE_IRIDESCENCE\n\t\tvec3 Fr = mix( specularColor, iridescenceF0, iridescence );\n\t#else\n\t\tvec3 Fr = specularColor;\n\t#endif\n\tvec3 FssEss = Fr * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometryNormal;\n\t\tvec3 viewDir = geometryViewDir;\n\t\tvec3 position = geometryPosition;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );\n\t#endif\n\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material );\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n\t#endif\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\t#ifdef USE_IRIDESCENCE\n\t\tcomputeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );\n\t#else\n\t\tcomputeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n\t#endif\n\tvec3 totalScattering = singleScattering + multiScattering;\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );\n\treflectedLight.indirectSpecular += radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}",lights_fragment_begin:"\nvec3 geometryPosition = - vViewPosition;\nvec3 geometryNormal = normal;\nvec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\nvec3 geometryClearcoatNormal = vec3( 0.0 );\n#ifdef USE_CLEARCOAT\n\tgeometryClearcoatNormal = clearcoatNormal;\n#endif\n#ifdef USE_IRIDESCENCE\n\tfloat dotNVi = saturate( dot( normal, geometryViewDir ) );\n\tif ( material.iridescenceThickness == 0.0 ) {\n\t\tmaterial.iridescence = 0.0;\n\t} else {\n\t\tmaterial.iridescence = saturate( material.iridescence );\n\t}\n\tif ( material.iridescence > 0.0 ) {\n\t\tmaterial.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );\n\t\tmaterial.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );\n\t}\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometryPosition, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tvec4 spotColor;\n\tvec3 spotLightCoord;\n\tbool inSpotLightMap;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometryPosition, directLight );\n\t\t#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX\n\t\t#elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t#define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS\n\t\t#else\n\t\t#define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#endif\n\t\t#if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )\n\t\t\tspotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;\n\t\t\tinSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );\n\t\t\tspotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );\n\t\t\tdirectLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;\n\t\t#endif\n\t\t#undef SPOT_LIGHT_MAP_INDEX\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\t#if defined( USE_LIGHT_PROBES )\n\t\tirradiance += getLightProbeIrradiance( lightProbe, geometryNormal );\n\t#endif\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif",lights_fragment_maps:"#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\t\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getIBLIrradiance( geometryNormal );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\t#ifdef USE_ANISOTROPY\n\t\tradiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );\n\t#else\n\t\tradiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness );\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif",lights_fragment_end:"#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif",logdepthbuf_fragment:"#if defined( USE_LOGDEPTHBUF )\n\tgl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif",logdepthbuf_pars_fragment:"#if defined( USE_LOGDEPTHBUF )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif",logdepthbuf_pars_vertex:"#ifdef USE_LOGDEPTHBUF\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif",logdepthbuf_vertex:"#ifdef USE_LOGDEPTHBUF\n\tvFragDepth = 1.0 + gl_Position.w;\n\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n#endif",map_fragment:"#ifdef USE_MAP\n\tvec4 sampledDiffuseColor = texture2D( map, vMapUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tsampledDiffuseColor = vec4( mix( pow( sampledDiffuseColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), sampledDiffuseColor.rgb * 0.0773993808, vec3( lessThanEqual( sampledDiffuseColor.rgb, vec3( 0.04045 ) ) ) ), sampledDiffuseColor.w );\n\t\n\t#endif\n\tdiffuseColor *= sampledDiffuseColor;\n#endif",map_pars_fragment:"#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif",map_particle_fragment:"#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\t#if defined( USE_POINTS_UV )\n\t\tvec2 uv = vUv;\n\t#else\n\t\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n\t#endif\n#endif\n#ifdef USE_MAP\n\tdiffuseColor *= texture2D( map, uv );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif",map_particle_pars_fragment:"#if defined( USE_POINTS_UV )\n\tvarying vec2 vUv;\n#else\n\t#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\t\tuniform mat3 uvTransform;\n\t#endif\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif",metalnessmap_fragment:"float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif",metalnessmap_pars_fragment:"#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif",morphinstance_vertex:"#ifdef USE_INSTANCING_MORPH\n\tfloat morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\tfloat morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tmorphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r;\n\t}\n#endif",morphcolor_vertex:"#if defined( USE_MORPHCOLORS )\n\tvColor *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t#if defined( USE_COLOR_ALPHA )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];\n\t\t#elif defined( USE_COLOR )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];\n\t\t#endif\n\t}\n#endif",morphnormal_vertex:"#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tif ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];\n\t}\n#endif",morphtarget_pars_vertex:"#ifdef USE_MORPHTARGETS\n\t#ifndef USE_INSTANCING_MORPH\n\t\tuniform float morphTargetBaseInfluence;\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t#endif\n\tuniform sampler2DArray morphTargetsTexture;\n\tuniform ivec2 morphTargetsTextureSize;\n\tvec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n\t\tint texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n\t\tint y = texelIndex / morphTargetsTextureSize.x;\n\t\tint x = texelIndex - y * morphTargetsTextureSize.x;\n\t\tivec3 morphUV = ivec3( x, y, morphTargetIndex );\n\t\treturn texelFetch( morphTargetsTexture, morphUV, 0 );\n\t}\n#endif",morphtarget_vertex:"#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];\n\t}\n#endif",normal_fragment_begin:"float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\n\tvec3 fdx = dFdx( vViewPosition );\n\tvec3 fdy = dFdy( vViewPosition );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal *= faceDirection;\n\t#endif\n#endif\n#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )\n\t#ifdef USE_TANGENT\n\t\tmat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\t#else\n\t\tmat3 tbn = getTangentFrame( - vViewPosition, normal,\n\t\t#if defined( USE_NORMALMAP )\n\t\t\tvNormalMapUv\n\t\t#elif defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tvClearcoatNormalMapUv\n\t\t#else\n\t\t\tvUv\n\t\t#endif\n\t\t);\n\t#endif\n\t#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n\t\ttbn[0] *= faceDirection;\n\t\ttbn[1] *= faceDirection;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\t#ifdef USE_TANGENT\n\t\tmat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\t#else\n\t\tmat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );\n\t#endif\n\t#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n\t\ttbn2[0] *= faceDirection;\n\t\ttbn2[1] *= faceDirection;\n\t#endif\n#endif\nvec3 nonPerturbedNormal = normal;",normal_fragment_maps:"#ifdef USE_NORMALMAP_OBJECTSPACE\n\tnormal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( USE_NORMALMAP_TANGENTSPACE )\n\tvec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\tnormal = normalize( tbn * mapN );\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif",normal_pars_fragment:"#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif",normal_pars_vertex:"#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif",normal_vertex:"#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif",normalmap_pars_fragment:"#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef USE_NORMALMAP_OBJECTSPACE\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) )\n\tmat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {\n\t\tvec3 q0 = dFdx( eye_pos.xyz );\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\n\t\tvec2 st0 = dFdx( uv.st );\n\t\tvec2 st1 = dFdy( uv.st );\n\t\tvec3 N = surf_norm;\n\t\tvec3 q1perp = cross( q1, N );\n\t\tvec3 q0perp = cross( N, q0 );\n\t\tvec3 T = q1perp * st0.x + q0perp * st1.x;\n\t\tvec3 B = q1perp * st0.y + q0perp * st1.y;\n\t\tfloat det = max( dot( T, T ), dot( B, B ) );\n\t\tfloat scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );\n\t\treturn mat3( T * scale, B * scale, N );\n\t}\n#endif",clearcoat_normal_fragment_begin:"#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = nonPerturbedNormal;\n#endif",clearcoat_normal_fragment_maps:"#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\tclearcoatNormal = normalize( tbn2 * clearcoatMapN );\n#endif",clearcoat_pars_fragment:"#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif",iridescence_pars_fragment:"#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif",opaque_fragment:"#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= material.transmissionAlpha;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );",packing:"vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.;\nconst float Inv255 = 1. / 255.;\nconst vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 );\nconst vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g );\nconst vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b );\nconst vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a );\nvec4 packDepthToRGBA( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec4( 0., 0., 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec4( 1., 1., 1., 1. );\n\tfloat vuf;\n\tfloat af = modf( v * PackFactors.a, vuf );\n\tfloat bf = modf( vuf * ShiftRight8, vuf );\n\tfloat gf = modf( vuf * ShiftRight8, vuf );\n\treturn vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af );\n}\nvec3 packDepthToRGB( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec3( 0., 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec3( 1., 1., 1. );\n\tfloat vuf;\n\tfloat bf = modf( v * PackFactors.b, vuf );\n\tfloat gf = modf( vuf * ShiftRight8, vuf );\n\treturn vec3( vuf * Inv255, gf * PackUpscale, bf );\n}\nvec2 packDepthToRG( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec2( 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec2( 1., 1. );\n\tfloat vuf;\n\tfloat gf = modf( v * 256., vuf );\n\treturn vec2( vuf * Inv255, gf );\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors4 );\n}\nfloat unpackRGBToDepth( const in vec3 v ) {\n\treturn dot( v, UnpackFactors3 );\n}\nfloat unpackRGToDepth( const in vec2 v ) {\n\treturn v.r * UnpackFactors2.r + v.g * UnpackFactors2.g;\n}\nvec4 pack2HalfToRGBA( const in vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );\n}\nvec2 unpackRGBATo2Half( const in vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) {\n\treturn depth * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * depth - far );\n}",premultiplied_alpha_fragment:"#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif",project_vertex:"vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_BATCHING\n\tmvPosition = batchingMatrix * mvPosition;\n#endif\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;",dithering_fragment:"#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif",dithering_pars_fragment:"#ifdef DITHERING\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif",roughnessmap_fragment:"float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );\n\troughnessFactor *= texelRoughness.g;\n#endif",roughnessmap_pars_fragment:"#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif",shadowmap_pars_fragment:"#if NUM_SPOT_LIGHT_COORDS > 0\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#if NUM_SPOT_LIGHT_MAPS > 0\n\tuniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tfloat shadow = 1.0;\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\t\n\t\tfloat lightToPositionLength = length( lightToPosition );\n\t\tif ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) {\n\t\t\tfloat dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\t\tdp += shadowBias;\n\t\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\t\tshadow = (\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t\t) * ( 1.0 / 9.0 );\n\t\t\t#else\n\t\t\t\tshadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t\t#endif\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n#endif",shadowmap_pars_vertex:"#if NUM_SPOT_LIGHT_COORDS > 0\n\tuniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif",shadowmap_vertex:"#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )\n\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\tvec4 shadowWorldPosition;\n#endif\n#if defined( USE_SHADOWMAP )\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if NUM_SPOT_LIGHT_COORDS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition;\n\t\t#if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t\tshadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;\n\t\t#endif\n\t\tvSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n#endif",shadowmask_pars_fragment:"float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}",skinbase_vertex:"#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif",skinning_pars_vertex:"#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\tuniform highp sampler2D boneTexture;\n\tmat4 getBoneMatrix( const in float i ) {\n\t\tint size = textureSize( boneTexture, 0 ).x;\n\t\tint j = int( i ) * 4;\n\t\tint x = j % size;\n\t\tint y = j / size;\n\t\tvec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 );\n\t\tvec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 );\n\t\tvec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 );\n\t\tvec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 );\n\t\treturn mat4( v1, v2, v3, v4 );\n\t}\n#endif",skinning_vertex:"#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif",skinnormal_vertex:"#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\t#ifdef USE_TANGENT\n\t\tobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#endif\n#endif",specularmap_fragment:"float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif",specularmap_pars_fragment:"#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif",tonemapping_fragment:"#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif",tonemapping_pars_fragment:"#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn saturate( toneMappingExposure * color );\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 CineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ),\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3( 1.60475, -0.10208, -0.00327 ),\t\tvec3( -0.53108, 1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605, 1.07602 )\n\t);\n\tcolor *= toneMappingExposure / 0.6;\n\tcolor = ACESInputMat * color;\n\tcolor = RRTAndODTFit( color );\n\tcolor = ACESOutputMat * color;\n\treturn saturate( color );\n}\nconst mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(\n\tvec3( 1.6605, - 0.1246, - 0.0182 ),\n\tvec3( - 0.5876, 1.1329, - 0.1006 ),\n\tvec3( - 0.0728, - 0.0083, 1.1187 )\n);\nconst mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(\n\tvec3( 0.6274, 0.0691, 0.0164 ),\n\tvec3( 0.3293, 0.9195, 0.0880 ),\n\tvec3( 0.0433, 0.0113, 0.8956 )\n);\nvec3 agxDefaultContrastApprox( vec3 x ) {\n\tvec3 x2 = x * x;\n\tvec3 x4 = x2 * x2;\n\treturn + 15.5 * x4 * x2\n\t\t- 40.14 * x4 * x\n\t\t+ 31.96 * x4\n\t\t- 6.868 * x2 * x\n\t\t+ 0.4298 * x2\n\t\t+ 0.1191 * x\n\t\t- 0.00232;\n}\nvec3 AgXToneMapping( vec3 color ) {\n\tconst mat3 AgXInsetMatrix = mat3(\n\t\tvec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),\n\t\tvec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),\n\t\tvec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )\n\t);\n\tconst mat3 AgXOutsetMatrix = mat3(\n\t\tvec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),\n\t\tvec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),\n\t\tvec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )\n\t);\n\tconst float AgxMinEv = - 12.47393;\tconst float AgxMaxEv = 4.026069;\n\tcolor *= toneMappingExposure;\n\tcolor = LINEAR_SRGB_TO_LINEAR_REC2020 * color;\n\tcolor = AgXInsetMatrix * color;\n\tcolor = max( color, 1e-10 );\tcolor = log2( color );\n\tcolor = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );\n\tcolor = clamp( color, 0.0, 1.0 );\n\tcolor = agxDefaultContrastApprox( color );\n\tcolor = AgXOutsetMatrix * color;\n\tcolor = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );\n\tcolor = LINEAR_REC2020_TO_LINEAR_SRGB * color;\n\tcolor = clamp( color, 0.0, 1.0 );\n\treturn color;\n}\nvec3 NeutralToneMapping( vec3 color ) {\n\tconst float StartCompression = 0.8 - 0.04;\n\tconst float Desaturation = 0.15;\n\tcolor *= toneMappingExposure;\n\tfloat x = min( color.r, min( color.g, color.b ) );\n\tfloat offset = x < 0.08 ? x - 6.25 * x * x : 0.04;\n\tcolor -= offset;\n\tfloat peak = max( color.r, max( color.g, color.b ) );\n\tif ( peak < StartCompression ) return color;\n\tfloat d = 1. - StartCompression;\n\tfloat newPeak = 1. - d * d / ( peak + d - StartCompression );\n\tcolor *= newPeak / peak;\n\tfloat g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );\n\treturn mix( color, vec3( newPeak ), g );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }",transmission_fragment:"#ifdef USE_TRANSMISSION\n\tmaterial.transmission = transmission;\n\tmaterial.transmissionAlpha = 1.0;\n\tmaterial.thickness = thickness;\n\tmaterial.attenuationDistance = attenuationDistance;\n\tmaterial.attenuationColor = attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tmaterial.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tmaterial.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = inverseTransformDirection( normal, viewMatrix );\n\tvec4 transmitted = getIBLVolumeRefraction(\n\t\tn, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness,\n\t\tmaterial.attenuationColor, material.attenuationDistance );\n\tmaterial.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );\n\ttotalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );\n#endif",transmission_pars_fragment:"#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tfloat w0( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );\n\t}\n\tfloat w1( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 );\n\t}\n\tfloat w2( float a ){\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );\n\t}\n\tfloat w3( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * a );\n\t}\n\tfloat g0( float a ) {\n\t\treturn w0( a ) + w1( a );\n\t}\n\tfloat g1( float a ) {\n\t\treturn w2( a ) + w3( a );\n\t}\n\tfloat h0( float a ) {\n\t\treturn - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );\n\t}\n\tfloat h1( float a ) {\n\t\treturn 1.0 + w3( a ) / ( w2( a ) + w3( a ) );\n\t}\n\tvec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) {\n\t\tuv = uv * texelSize.zw + 0.5;\n\t\tvec2 iuv = floor( uv );\n\t\tvec2 fuv = fract( uv );\n\t\tfloat g0x = g0( fuv.x );\n\t\tfloat g1x = g1( fuv.x );\n\t\tfloat h0x = h0( fuv.x );\n\t\tfloat h1x = h1( fuv.x );\n\t\tfloat h0y = h0( fuv.y );\n\t\tfloat h1y = h1( fuv.y );\n\t\tvec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\treturn g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) +\n\t\t\tg1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) );\n\t}\n\tvec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) {\n\t\tvec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) );\n\t\tvec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) );\n\t\tvec2 fLodSizeInv = 1.0 / fLodSize;\n\t\tvec2 cLodSizeInv = 1.0 / cLodSize;\n\t\tvec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) );\n\t\tvec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) );\n\t\treturn mix( fSample, cSample, fract( lod ) );\n\t}\n\tvec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( const in float roughness, const in float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {\n\t\tfloat lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\treturn textureBicubic( transmissionSamplerMap, fragCoord.xy, lod );\n\t}\n\tvec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tif ( isinf( attenuationDistance ) ) {\n\t\t\treturn vec3( 1.0 );\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,\n\t\tconst in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,\n\t\tconst in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness,\n\t\tconst in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tvec4 transmittedLight;\n\t\tvec3 transmittance;\n\t\t#ifdef USE_DISPERSION\n\t\t\tfloat halfSpread = ( ior - 1.0 ) * 0.025 * dispersion;\n\t\t\tvec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread );\n\t\t\tfor ( int i = 0; i < 3; i ++ ) {\n\t\t\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix );\n\t\t\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\t\n\t\t\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\t\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\t\t\trefractionCoords += 1.0;\n\t\t\t\trefractionCoords /= 2.0;\n\t\t\n\t\t\t\tvec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] );\n\t\t\t\ttransmittedLight[ i ] = transmissionSample[ i ];\n\t\t\t\ttransmittedLight.a += transmissionSample.a;\n\t\t\t\ttransmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ];\n\t\t\t}\n\t\t\ttransmittedLight.a /= 3.0;\n\t\t\n\t\t#else\n\t\t\n\t\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\t\trefractionCoords += 1.0;\n\t\t\trefractionCoords /= 2.0;\n\t\t\ttransmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\t\ttransmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\t\n\t\t#endif\n\t\tvec3 attenuatedColor = transmittance * transmittedLight.rgb;\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\tfloat transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );\n\t}\n#endif",uv_pars_fragment:"#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_MAP\n\tvarying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n\tvarying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n\tvarying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n\tvarying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n\tvarying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n\tvarying vec2 vNormalMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tvarying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n\tvarying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tvarying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tvarying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tvarying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tvarying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tvarying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tvarying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tvarying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tvarying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tvarying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n\tvarying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tvarying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tvarying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tuniform mat3 transmissionMapTransform;\n\tvarying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n\tuniform mat3 thicknessMapTransform;\n\tvarying vec2 vThicknessMapUv;\n#endif",uv_pars_vertex:"#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_MAP\n\tuniform mat3 mapTransform;\n\tvarying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform mat3 alphaMapTransform;\n\tvarying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n\tuniform mat3 lightMapTransform;\n\tvarying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n\tuniform mat3 aoMapTransform;\n\tvarying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n\tuniform mat3 bumpMapTransform;\n\tvarying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n\tuniform mat3 normalMapTransform;\n\tvarying vec2 vNormalMapUv;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n\tuniform mat3 displacementMapTransform;\n\tvarying vec2 vDisplacementMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tuniform mat3 emissiveMapTransform;\n\tvarying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n\tuniform mat3 metalnessMapTransform;\n\tvarying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tuniform mat3 roughnessMapTransform;\n\tvarying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tuniform mat3 anisotropyMapTransform;\n\tvarying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tuniform mat3 clearcoatMapTransform;\n\tvarying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform mat3 clearcoatNormalMapTransform;\n\tvarying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform mat3 clearcoatRoughnessMapTransform;\n\tvarying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tuniform mat3 sheenColorMapTransform;\n\tvarying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tuniform mat3 sheenRoughnessMapTransform;\n\tvarying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tuniform mat3 iridescenceMapTransform;\n\tvarying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform mat3 iridescenceThicknessMapTransform;\n\tvarying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n\tuniform mat3 specularMapTransform;\n\tvarying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tuniform mat3 specularColorMapTransform;\n\tvarying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tuniform mat3 specularIntensityMapTransform;\n\tvarying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tuniform mat3 transmissionMapTransform;\n\tvarying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n\tuniform mat3 thicknessMapTransform;\n\tvarying vec2 vThicknessMapUv;\n#endif",uv_vertex:"#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvUv = vec3( uv, 1 ).xy;\n#endif\n#ifdef USE_MAP\n\tvMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ALPHAMAP\n\tvAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_LIGHTMAP\n\tvLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_AOMAP\n\tvAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_BUMPMAP\n\tvBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_NORMALMAP\n\tvNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n\tvDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tvEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_METALNESSMAP\n\tvMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tvRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tvAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tvClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tvClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tvClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tvIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tvIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tvSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tvSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULARMAP\n\tvSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tvSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tvSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tvTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_THICKNESSMAP\n\tvThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;\n#endif",worldpos_vertex:"#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_BATCHING\n\t\tworldPosition = batchingMatrix * worldPosition;\n\t#endif\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif",background_vert:"varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}",background_frag:"uniform sampler2D t2D;\nuniform float backgroundIntensity;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\ttexColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include \n\t#include \n}",backgroundCube_vert:"varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n\tgl_Position.z = gl_Position.w;\n}",backgroundCube_frag:"#ifdef ENVMAP_TYPE_CUBE\n\tuniform samplerCube envMap;\n#elif defined( ENVMAP_TYPE_CUBE_UV )\n\tuniform sampler2D envMap;\n#endif\nuniform float flipEnvMap;\nuniform float backgroundBlurriness;\nuniform float backgroundIntensity;\nuniform mat3 backgroundRotation;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness );\n\t#else\n\t\tvec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include \n\t#include \n}",cube_vert:"varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n\tgl_Position.z = gl_Position.w;\n}",cube_frag:"uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldDirection;\nvoid main() {\n\tvec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );\n\tgl_FragColor = texColor;\n\tgl_FragColor.a *= opacity;\n\t#include \n\t#include \n}",depth_vert:"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvHighPrecisionZW = gl_Position.zw;\n}",depth_frag:"#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include \n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#elif DEPTH_PACKING == 3202\n\t\tgl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 );\n\t#elif DEPTH_PACKING == 3203\n\t\tgl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 );\n\t#endif\n}",distanceRGBA_vert:"#define DISTANCE\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvWorldPosition = worldPosition.xyz;\n}",distanceRGBA_frag:"#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main () {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}",equirect_vert:"varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n}",equirect_frag:"uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\t#include \n\t#include \n}",linedashed_vert:"uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",linedashed_frag:"uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshbasic_vert:"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshbasic_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\t\treflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include \n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshlambert_vert:"#define LAMBERT\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}",meshlambert_frag:"#define LAMBERT\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshmatcap_vert:"#define MATCAP\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n}",meshmatcap_frag:"#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t#else\n\t\tvec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshnormal_vert:"#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvarying vec3 vViewPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}",meshnormal_frag:"#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvarying vec3 vViewPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\tgl_FragColor = vec4( packNormalToRGB( normal ), diffuseColor.a );\n\t#ifdef OPAQUE\n\t\tgl_FragColor.a = 1.0;\n\t#endif\n}",meshphong_vert:"#define PHONG\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}",meshphong_frag:"#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshphysical_vert:"#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition.xyz;\n#endif\n}",meshphysical_frag:"#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define USE_SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n\tuniform float ior;\n#endif\n#ifdef USE_SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularColor;\n\t#ifdef USE_SPECULAR_COLORMAP\n\t\tuniform sampler2D specularColorMap;\n\t#endif\n\t#ifdef USE_SPECULAR_INTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_DISPERSION\n\tuniform float dispersion;\n#endif\n#ifdef USE_IRIDESCENCE\n\tuniform float iridescence;\n\tuniform float iridescenceIOR;\n\tuniform float iridescenceThicknessMinimum;\n\tuniform float iridescenceThicknessMaximum;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheenColor;\n\tuniform float sheenRoughness;\n\t#ifdef USE_SHEEN_COLORMAP\n\t\tuniform sampler2D sheenColorMap;\n\t#endif\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tuniform sampler2D sheenRoughnessMap;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\tuniform vec2 anisotropyVector;\n\t#ifdef USE_ANISOTROPYMAP\n\t\tuniform sampler2D anisotropyMap;\n\t#endif\n#endif\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include \n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_SHEEN\n\t\tfloat sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );\n\t\toutgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect;\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshtoon_vert:"#define TOON\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n}",meshtoon_frag:"#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",points_vert:"uniform float size;\nuniform float scale;\n#include \n#include \n#include \n#include \n#include \n#include \n#ifdef USE_POINTS_UV\n\tvarying vec2 vUv;\n\tuniform mat3 uvTransform;\n#endif\nvoid main() {\n\t#ifdef USE_POINTS_UV\n\t\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n}",points_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",shadow_vert:"#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",shadow_frag:"uniform vec3 color;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include \n\t#include \n\t#include \n}",sprite_vert:"uniform float rotation;\nuniform vec2 center;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 mvPosition = modelViewMatrix[ 3 ];\n\tvec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include \n\t#include \n\t#include \n}",sprite_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n}"},dr={common:{diffuse:{value:new ii(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new se},alphaMap:{value:null},alphaMapTransform:{value:new se},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new se}},envmap:{envMap:{value:null},envMapRotation:{value:new se},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new se}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new se}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new se},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new se},normalScale:{value:new re(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new se},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new se}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new se}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new se}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new ii(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new ii(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new se},alphaTest:{value:0},uvTransform:{value:new se}},sprite:{diffuse:{value:new ii(16777215)},opacity:{value:1},center:{value:new re(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new se},alphaMap:{value:null},alphaMapTransform:{value:new se},alphaTest:{value:0}}},pr={basic:{uniforms:Hi([dr.common,dr.specularmap,dr.envmap,dr.aomap,dr.lightmap,dr.fog]),vertexShader:ur.meshbasic_vert,fragmentShader:ur.meshbasic_frag},lambert:{uniforms:Hi([dr.common,dr.specularmap,dr.envmap,dr.aomap,dr.lightmap,dr.emissivemap,dr.bumpmap,dr.normalmap,dr.displacementmap,dr.fog,dr.lights,{emissive:{value:new ii(0)}}]),vertexShader:ur.meshlambert_vert,fragmentShader:ur.meshlambert_frag},phong:{uniforms:Hi([dr.common,dr.specularmap,dr.envmap,dr.aomap,dr.lightmap,dr.emissivemap,dr.bumpmap,dr.normalmap,dr.displacementmap,dr.fog,dr.lights,{emissive:{value:new ii(0)},specular:{value:new ii(1118481)},shininess:{value:30}}]),vertexShader:ur.meshphong_vert,fragmentShader:ur.meshphong_frag},standard:{uniforms:Hi([dr.common,dr.envmap,dr.aomap,dr.lightmap,dr.emissivemap,dr.bumpmap,dr.normalmap,dr.displacementmap,dr.roughnessmap,dr.metalnessmap,dr.fog,dr.lights,{emissive:{value:new ii(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:ur.meshphysical_vert,fragmentShader:ur.meshphysical_frag},toon:{uniforms:Hi([dr.common,dr.aomap,dr.lightmap,dr.emissivemap,dr.bumpmap,dr.normalmap,dr.displacementmap,dr.gradientmap,dr.fog,dr.lights,{emissive:{value:new ii(0)}}]),vertexShader:ur.meshtoon_vert,fragmentShader:ur.meshtoon_frag},matcap:{uniforms:Hi([dr.common,dr.bumpmap,dr.normalmap,dr.displacementmap,dr.fog,{matcap:{value:null}}]),vertexShader:ur.meshmatcap_vert,fragmentShader:ur.meshmatcap_frag},points:{uniforms:Hi([dr.points,dr.fog]),vertexShader:ur.points_vert,fragmentShader:ur.points_frag},dashed:{uniforms:Hi([dr.common,dr.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:ur.linedashed_vert,fragmentShader:ur.linedashed_frag},depth:{uniforms:Hi([dr.common,dr.displacementmap]),vertexShader:ur.depth_vert,fragmentShader:ur.depth_frag},normal:{uniforms:Hi([dr.common,dr.bumpmap,dr.normalmap,dr.displacementmap,{opacity:{value:1}}]),vertexShader:ur.meshnormal_vert,fragmentShader:ur.meshnormal_frag},sprite:{uniforms:Hi([dr.sprite,dr.fog]),vertexShader:ur.sprite_vert,fragmentShader:ur.sprite_frag},background:{uniforms:{uvTransform:{value:new se},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:ur.background_vert,fragmentShader:ur.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new se}},vertexShader:ur.backgroundCube_vert,fragmentShader:ur.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:ur.cube_vert,fragmentShader:ur.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:ur.equirect_vert,fragmentShader:ur.equirect_frag},distanceRGBA:{uniforms:Hi([dr.common,dr.displacementmap,{referencePosition:{value:new De},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:ur.distanceRGBA_vert,fragmentShader:ur.distanceRGBA_frag},shadow:{uniforms:Hi([dr.lights,dr.fog,{color:{value:new ii(0)},opacity:{value:1}}]),vertexShader:ur.shadow_vert,fragmentShader:ur.shadow_frag}};pr.physical={uniforms:Hi([pr.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new se},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new se},clearcoatNormalScale:{value:new re(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new se},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new se},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new se},sheen:{value:0},sheenColor:{value:new ii(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new se},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new se},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new se},transmissionSamplerSize:{value:new re},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new se},attenuationDistance:{value:0},attenuationColor:{value:new ii(0)},specularColor:{value:new ii(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new se},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new se},anisotropyVector:{value:new re},anisotropyMap:{value:null},anisotropyMapTransform:{value:new se}}]),vertexShader:ur.meshphysical_vert,fragmentShader:ur.meshphysical_frag};const mr={r:0,b:0,g:0},fr=new Mn,gr=new un;function vr(t,e,n,i,r,s,a){const o=new ii(0);let l,c,h=!0===s?0:1,u=null,d=0,m=null;function f(t){let i=!0===t.isScene?t.background:null;return i&&i.isTexture&&(i=(t.backgroundBlurriness>0?n:e).get(i)),i}function g(e,n){e.getRGB(mr,Gi(t)),i.buffers.color.setClear(mr.r,mr.g,mr.b,n,a)}return{getClearColor:function(){return o},setClearColor:function(t,e=1){o.set(t),h=e,g(o,h)},getClearAlpha:function(){return h},setClearAlpha:function(t){h=t,g(o,h)},render:function(e){let n=!1;const r=f(e);null===r?g(o,h):r&&r.isColor&&(g(r,1),n=!0);const s=t.xr.getEnvironmentBlendMode();"additive"===s?i.buffers.color.setClear(0,0,0,1,a):"alpha-blend"===s&&i.buffers.color.setClear(0,0,0,0,a),(t.autoClear||n)&&(i.buffers.depth.setTest(!0),i.buffers.depth.setMask(!0),i.buffers.color.setMask(!0),t.clear(t.autoClearColor,t.autoClearDepth,t.autoClearStencil))},addToRenderList:function(e,n){const i=f(n);i&&(i.isCubeTexture||i.mapping===p)?(void 0===c&&(c=new Bi(new ki(1,1,1),new Xi({name:"BackgroundCubeMaterial",uniforms:Vi(pr.backgroundCube.uniforms),vertexShader:pr.backgroundCube.vertexShader,fragmentShader:pr.backgroundCube.fragmentShader,side:1,depthTest:!1,depthWrite:!1,fog:!1})),c.geometry.deleteAttribute("normal"),c.geometry.deleteAttribute("uv"),c.onBeforeRender=function(t,e,n){this.matrixWorld.copyPosition(n.matrixWorld)},Object.defineProperty(c.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),r.update(c)),fr.copy(n.backgroundRotation),fr.x*=-1,fr.y*=-1,fr.z*=-1,i.isCubeTexture&&!1===i.isRenderTargetTexture&&(fr.y*=-1,fr.z*=-1),c.material.uniforms.envMap.value=i,c.material.uniforms.flipEnvMap.value=i.isCubeTexture&&!1===i.isRenderTargetTexture?-1:1,c.material.uniforms.backgroundBlurriness.value=n.backgroundBlurriness,c.material.uniforms.backgroundIntensity.value=n.backgroundIntensity,c.material.uniforms.backgroundRotation.value.setFromMatrix4(gr.makeRotationFromEuler(fr)),c.material.toneMapped=_e.getTransfer(i.colorSpace)!==Bt,u===i&&d===i.version&&m===t.toneMapping||(c.material.needsUpdate=!0,u=i,d=i.version,m=t.toneMapping),c.layers.enableAll(),e.unshift(c,c.geometry,c.material,0,0,null)):i&&i.isTexture&&(void 0===l&&(l=new Bi(new hr(2,2),new Xi({name:"BackgroundMaterial",uniforms:Vi(pr.background.uniforms),vertexShader:pr.background.vertexShader,fragmentShader:pr.background.fragmentShader,side:0,depthTest:!1,depthWrite:!1,fog:!1})),l.geometry.deleteAttribute("normal"),Object.defineProperty(l.material,"map",{get:function(){return this.uniforms.t2D.value}}),r.update(l)),l.material.uniforms.t2D.value=i,l.material.uniforms.backgroundIntensity.value=n.backgroundIntensity,l.material.toneMapped=_e.getTransfer(i.colorSpace)!==Bt,!0===i.matrixAutoUpdate&&i.updateMatrix(),l.material.uniforms.uvTransform.value.copy(i.matrix),u===i&&d===i.version&&m===t.toneMapping||(l.material.needsUpdate=!0,u=i,d=i.version,m=t.toneMapping),l.layers.enableAll(),e.unshift(l,l.geometry,l.material,0,0,null))}}}function _r(t,e){const n=t.getParameter(t.MAX_VERTEX_ATTRIBS),i={},r=c(null);let s=r,a=!1;function o(e){return t.bindVertexArray(e)}function l(e){return t.deleteVertexArray(e)}function c(t){const e=[],i=[],r=[];for(let t=0;t=0){const n=r[e];let i=a[e];if(void 0===i&&("instanceMatrix"===e&&t.instanceMatrix&&(i=t.instanceMatrix),"instanceColor"===e&&t.instanceColor&&(i=t.instanceColor)),void 0===n)return!0;if(n.attribute!==i)return!0;if(i&&n.data!==i.data)return!0;o++}return s.attributesNum!==o||s.index!==i}(n,f,l,g),v&&function(t,e,n,i){const r={},a=e.attributes;let o=0;const l=n.getAttributes();for(const e in l)if(l[e].location>=0){let n=a[e];void 0===n&&("instanceMatrix"===e&&t.instanceMatrix&&(n=t.instanceMatrix),"instanceColor"===e&&t.instanceColor&&(n=t.instanceColor));const i={};i.attribute=n,n&&n.data&&(i.data=n.data),r[e]=i,o++}s.attributes=r,s.attributesNum=o,s.index=i}(n,f,l,g),null!==g&&e.update(g,t.ELEMENT_ARRAY_BUFFER),(v||a)&&(a=!1,function(n,i,r,s){h();const a=s.attributes,o=r.getAttributes(),l=i.defaultAttributeValues;for(const i in o){const r=o[i];if(r.location>=0){let o=a[i];if(void 0===o&&("instanceMatrix"===i&&n.instanceMatrix&&(o=n.instanceMatrix),"instanceColor"===i&&n.instanceColor&&(o=n.instanceColor)),void 0!==o){const i=o.normalized,a=o.itemSize,l=e.get(o);if(void 0===l)continue;const c=l.buffer,h=l.type,p=l.bytesPerElement,f=h===t.INT||h===t.UNSIGNED_INT||o.gpuType===A;if(o.isInterleavedBufferAttribute){const e=o.data,l=e.stride,g=o.offset;if(e.isInstancedInterleavedBuffer){for(let t=0;t0&&t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.HIGH_FLOAT).precision>0)return"highp";e="mediump"}return"mediump"===e&&t.getShaderPrecisionFormat(t.VERTEX_SHADER,t.MEDIUM_FLOAT).precision>0&&t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let a=void 0!==n.precision?n.precision:"highp";const o=s(a);o!==a&&(console.warn("THREE.WebGLRenderer:",a,"not supported, using",o,"instead."),a=o);const l=!0===n.logarithmicDepthBuffer,c=!0===n.reverseDepthBuffer&&e.has("EXT_clip_control");if(!0===c){const t=e.get("EXT_clip_control");t.clipControlEXT(t.LOWER_LEFT_EXT,t.ZERO_TO_ONE_EXT)}const h=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS),u=t.getParameter(t.MAX_VERTEX_TEXTURE_IMAGE_UNITS);return{isWebGL2:!0,getMaxAnisotropy:function(){if(void 0!==r)return r;if(!0===e.has("EXT_texture_filter_anisotropic")){const n=e.get("EXT_texture_filter_anisotropic");r=t.getParameter(n.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else r=0;return r},getMaxPrecision:s,textureFormatReadable:function(e){return e===F||i.convert(e)===t.getParameter(t.IMPLEMENTATION_COLOR_READ_FORMAT)},textureTypeReadable:function(n){const r=n===P&&(e.has("EXT_color_buffer_half_float")||e.has("EXT_color_buffer_float"));return!(n!==b&&i.convert(n)!==t.getParameter(t.IMPLEMENTATION_COLOR_READ_TYPE)&&n!==R&&!r)},precision:a,logarithmicDepthBuffer:l,reverseDepthBuffer:c,maxTextures:h,maxVertexTextures:u,maxTextureSize:t.getParameter(t.MAX_TEXTURE_SIZE),maxCubemapSize:t.getParameter(t.MAX_CUBE_MAP_TEXTURE_SIZE),maxAttributes:t.getParameter(t.MAX_VERTEX_ATTRIBS),maxVertexUniforms:t.getParameter(t.MAX_VERTEX_UNIFORM_VECTORS),maxVaryings:t.getParameter(t.MAX_VARYING_VECTORS),maxFragmentUniforms:t.getParameter(t.MAX_FRAGMENT_UNIFORM_VECTORS),vertexTextures:u>0,maxSamples:t.getParameter(t.MAX_SAMPLES)}}function Mr(t){const e=this;let n=null,i=0,r=!1,s=!1;const a=new rr,o=new se,l={value:null,needsUpdate:!1};function c(t,n,i,r){const s=null!==t?t.length:0;let c=null;if(0!==s){if(c=l.value,!0!==r||null===c){const e=i+4*s,r=n.matrixWorldInverse;o.getNormalMatrix(r),(null===c||c.length0),e.numPlanes=i,e.numIntersection=0);else{const t=s?0:i,e=4*t;let r=m.clippingState||null;l.value=r,r=c(u,o,e,h);for(let t=0;t!==e;++t)r[t]=n[t];m.clippingState=r,this.numIntersection=d?this.numPlanes:0,this.numPlanes+=t}}}function Sr(t){let e=new WeakMap;function n(t,e){return e===u?t.mapping=c:e===d&&(t.mapping=h),t}function i(t){const n=t.target;n.removeEventListener("dispose",i);const r=e.get(n);void 0!==r&&(e.delete(n),r.dispose())}return{get:function(r){if(r&&r.isTexture){const s=r.mapping;if(s===u||s===d){if(e.has(r))return n(e.get(r).texture,r.mapping);{const s=r.image;if(s&&s.height>0){const a=new tr(s.height);return a.fromEquirectangularTexture(t,r),e.set(r,a),r.addEventListener("dispose",i),n(a.texture,r.mapping)}return null}}}return r},dispose:function(){e=new WeakMap}}}class br extends ji{constructor(t=-1,e=1,n=1,i=-1,r=.1,s=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=t,this.right=e,this.top=n,this.bottom=i,this.near=r,this.far=s,this.updateProjectionMatrix()}copy(t,e){return super.copy(t,e),this.left=t.left,this.right=t.right,this.top=t.top,this.bottom=t.bottom,this.near=t.near,this.far=t.far,this.zoom=t.zoom,this.view=null===t.view?null:Object.assign({},t.view),this}setViewOffset(t,e,n,i,r,s){null===this.view&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=t,this.view.fullHeight=e,this.view.offsetX=n,this.view.offsetY=i,this.view.width=r,this.view.height=s,this.updateProjectionMatrix()}clearViewOffset(){null!==this.view&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const t=(this.right-this.left)/(2*this.zoom),e=(this.top-this.bottom)/(2*this.zoom),n=(this.right+this.left)/2,i=(this.top+this.bottom)/2;let r=n-t,s=n+t,a=i+e,o=i-e;if(null!==this.view&&this.view.enabled){const t=(this.right-this.left)/this.view.fullWidth/this.zoom,e=(this.top-this.bottom)/this.view.fullHeight/this.zoom;r+=t*this.view.offsetX,s=r+t*this.view.width,a-=e*this.view.offsetY,o=a-e*this.view.height}this.projectionMatrix.makeOrthographic(r,s,a,o,this.near,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(t){const e=super.toJSON(t);return e.object.zoom=this.zoom,e.object.left=this.left,e.object.right=this.right,e.object.top=this.top,e.object.bottom=this.bottom,e.object.near=this.near,e.object.far=this.far,null!==this.view&&(e.object.view=Object.assign({},this.view)),e}}const wr=[.125,.215,.35,.446,.526,.582],Tr=new br,Er=new ii;let Ar=null,Cr=0,Rr=0,Pr=!1;const Ir=(1+Math.sqrt(5))/2,Lr=1/Ir,Ur=[new De(-Ir,Lr,0),new De(Ir,Lr,0),new De(-Lr,0,Ir),new De(Lr,0,Ir),new De(0,Ir,-Lr),new De(0,Ir,Lr),new De(-1,1,-1),new De(1,1,-1),new De(-1,1,1),new De(1,1,1)];class Dr{constructor(t){this._renderer=t,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._compileMaterial(this._blurMaterial)}fromScene(t,e=0,n=.1,i=100){Ar=this._renderer.getRenderTarget(),Cr=this._renderer.getActiveCubeFace(),Rr=this._renderer.getActiveMipmapLevel(),Pr=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(256);const r=this._allocateTargets();return r.depthBuffer=!0,this._sceneToCubeUV(t,n,i,r),e>0&&this._blur(r,0,0,e),this._applyPMREM(r),this._cleanup(r),r}fromEquirectangular(t,e=null){return this._fromTexture(t,e)}fromCubemap(t,e=null){return this._fromTexture(t,e)}compileCubemapShader(){null===this._cubemapMaterial&&(this._cubemapMaterial=Br(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=Fr(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),null!==this._cubemapMaterial&&this._cubemapMaterial.dispose(),null!==this._equirectMaterial&&this._equirectMaterial.dispose()}_setSize(t){this._lodMax=Math.floor(Math.log2(t)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){null!==this._blurMaterial&&this._blurMaterial.dispose(),null!==this._pingPongRenderTarget&&this._pingPongRenderTarget.dispose();for(let t=0;tt-4?o=wr[a-t+4-1]:0===a&&(o=0),i.push(o);const l=1/(s-2),c=-l,h=1+l,u=[c,c,h,c,h,h,c,c,h,h,c,h],d=6,p=6,m=3,f=2,g=1,v=new Float32Array(m*p*d),_=new Float32Array(f*p*d),y=new Float32Array(g*p*d);for(let t=0;t2?0:-1,i=[e,n,0,e+2/3,n,0,e+2/3,n+1,0,e,n,0,e+2/3,n+1,0,e,n+1,0];v.set(i,m*p*t),_.set(u,f*p*t);const r=[t,t,t,t,t,t];y.set(r,g*p*t)}const x=new Ei;x.setAttribute("position",new fi(v,m)),x.setAttribute("uv",new fi(_,f)),x.setAttribute("faceIndex",new fi(y,g)),e.push(x),r>4&&r--}return{lodPlanes:e,sizeLods:n,sigmas:i}}(i)),this._blurMaterial=function(t,e,n){const i=new Float32Array(20),r=new De(0,1,0);return new Xi({name:"SphericalGaussianBlur",defines:{n:20,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/n,CUBEUV_MAX_MIP:`${t}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:i},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:r}},vertexShader:"\n\n\t\tprecision mediump float;\n\t\tprecision mediump int;\n\n\t\tattribute float faceIndex;\n\n\t\tvarying vec3 vOutputDirection;\n\n\t\t// RH coordinate system; PMREM face-indexing convention\n\t\tvec3 getDirection( vec2 uv, float face ) {\n\n\t\t\tuv = 2.0 * uv - 1.0;\n\n\t\t\tvec3 direction = vec3( uv, 1.0 );\n\n\t\t\tif ( face == 0.0 ) {\n\n\t\t\t\tdirection = direction.zyx; // ( 1, v, u ) pos x\n\n\t\t\t} else if ( face == 1.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xz *= -1.0; // ( -u, 1, -v ) pos y\n\n\t\t\t} else if ( face == 2.0 ) {\n\n\t\t\t\tdirection.x *= -1.0; // ( -u, v, 1 ) pos z\n\n\t\t\t} else if ( face == 3.0 ) {\n\n\t\t\t\tdirection = direction.zyx;\n\t\t\t\tdirection.xz *= -1.0; // ( -1, v, -u ) neg x\n\n\t\t\t} else if ( face == 4.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xy *= -1.0; // ( -u, -1, v ) neg y\n\n\t\t\t} else if ( face == 5.0 ) {\n\n\t\t\t\tdirection.z *= -1.0; // ( u, v, -1 ) neg z\n\n\t\t\t}\n\n\t\t\treturn direction;\n\n\t\t}\n\n\t\tvoid main() {\n\n\t\t\tvOutputDirection = getDirection( uv, faceIndex );\n\t\t\tgl_Position = vec4( position, 1.0 );\n\n\t\t}\n\t",fragmentShader:"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\t\t\tuniform int samples;\n\t\t\tuniform float weights[ n ];\n\t\t\tuniform bool latitudinal;\n\t\t\tuniform float dTheta;\n\t\t\tuniform float mipInt;\n\t\t\tuniform vec3 poleAxis;\n\n\t\t\t#define ENVMAP_TYPE_CUBE_UV\n\t\t\t#include \n\n\t\t\tvec3 getSample( float theta, vec3 axis ) {\n\n\t\t\t\tfloat cosTheta = cos( theta );\n\t\t\t\t// Rodrigues' axis-angle rotation\n\t\t\t\tvec3 sampleDirection = vOutputDirection * cosTheta\n\t\t\t\t\t+ cross( axis, vOutputDirection ) * sin( theta )\n\t\t\t\t\t+ axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );\n\n\t\t\t\treturn bilinearCubeUV( envMap, sampleDirection, mipInt );\n\n\t\t\t}\n\n\t\t\tvoid main() {\n\n\t\t\t\tvec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );\n\n\t\t\t\tif ( all( equal( axis, vec3( 0.0 ) ) ) ) {\n\n\t\t\t\t\taxis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );\n\n\t\t\t\t}\n\n\t\t\t\taxis = normalize( axis );\n\n\t\t\t\tgl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t\t\t\tgl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );\n\n\t\t\t\tfor ( int i = 1; i < n; i++ ) {\n\n\t\t\t\t\tif ( i >= samples ) {\n\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tfloat theta = dTheta * float( i );\n\t\t\t\t\tgl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );\n\t\t\t\t\tgl_FragColor.rgb += weights[ i ] * getSample( theta, axis );\n\n\t\t\t\t}\n\n\t\t\t}\n\t\t",blending:0,depthTest:!1,depthWrite:!1})}(i,t,e)}return i}_compileMaterial(t){const e=new Bi(this._lodPlanes[0],t);this._renderer.compile(e,Tr)}_sceneToCubeUV(t,e,n,i){const r=new Ji(90,1,e,n),s=[1,-1,1,1,1,1],a=[1,1,1,-1,-1,-1],o=this._renderer,l=o.autoClear,c=o.toneMapping;o.getClearColor(Er),o.toneMapping=0,o.autoClear=!1;const h=new oi({name:"PMREM.Background",side:1,depthWrite:!1,depthTest:!1}),u=new Bi(new ki,h);let d=!1;const p=t.background;p?p.isColor&&(h.color.copy(p),t.background=null,d=!0):(h.color.copy(Er),d=!0);for(let e=0;e<6;e++){const n=e%3;0===n?(r.up.set(0,s[e],0),r.lookAt(a[e],0,0)):1===n?(r.up.set(0,0,s[e]),r.lookAt(0,a[e],0)):(r.up.set(0,s[e],0),r.lookAt(0,0,a[e]));const l=this._cubeSize;Or(i,n*l,e>2?l:0,l,l),o.setRenderTarget(i),d&&o.render(u,r),o.render(t,r)}u.geometry.dispose(),u.material.dispose(),o.toneMapping=c,o.autoClear=l,t.background=p}_textureToCubeUV(t,e){const n=this._renderer,i=t.mapping===c||t.mapping===h;i?(null===this._cubemapMaterial&&(this._cubemapMaterial=Br()),this._cubemapMaterial.uniforms.flipEnvMap.value=!1===t.isRenderTargetTexture?-1:1):null===this._equirectMaterial&&(this._equirectMaterial=Fr());const r=i?this._cubemapMaterial:this._equirectMaterial,s=new Bi(this._lodPlanes[0],r);r.uniforms.envMap.value=t;const a=this._cubeSize;Or(e,0,0,3*a,2*a),n.setRenderTarget(e),n.render(s,Tr)}_applyPMREM(t){const e=this._renderer,n=e.autoClear;e.autoClear=!1;const i=this._lodPlanes.length;for(let e=1;e20&&console.warn(`sigmaRadians, ${r}, is too large and will clip, as it requested ${m} samples when the maximum is set to 20`);const f=[];let g=0;for(let t=0;t<20;++t){const e=t/p,n=Math.exp(-e*e/2);f.push(n),0===t?g+=n:tv-4?i-v+4:0),4*(this._cubeSize-_),3*_,2*_),o.setRenderTarget(e),o.render(c,Tr)}}function Nr(t,e,n){const i=new Pe(t,e,n);return i.texture.mapping=p,i.texture.name="PMREM.cubeUv",i.scissorTest=!0,i}function Or(t,e,n,i,r){t.viewport.set(e,n,i,r),t.scissor.set(e,n,i,r)}function Fr(){return new Xi({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:"\n\n\t\tprecision mediump float;\n\t\tprecision mediump int;\n\n\t\tattribute float faceIndex;\n\n\t\tvarying vec3 vOutputDirection;\n\n\t\t// RH coordinate system; PMREM face-indexing convention\n\t\tvec3 getDirection( vec2 uv, float face ) {\n\n\t\t\tuv = 2.0 * uv - 1.0;\n\n\t\t\tvec3 direction = vec3( uv, 1.0 );\n\n\t\t\tif ( face == 0.0 ) {\n\n\t\t\t\tdirection = direction.zyx; // ( 1, v, u ) pos x\n\n\t\t\t} else if ( face == 1.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xz *= -1.0; // ( -u, 1, -v ) pos y\n\n\t\t\t} else if ( face == 2.0 ) {\n\n\t\t\t\tdirection.x *= -1.0; // ( -u, v, 1 ) pos z\n\n\t\t\t} else if ( face == 3.0 ) {\n\n\t\t\t\tdirection = direction.zyx;\n\t\t\t\tdirection.xz *= -1.0; // ( -1, v, -u ) neg x\n\n\t\t\t} else if ( face == 4.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xy *= -1.0; // ( -u, -1, v ) neg y\n\n\t\t\t} else if ( face == 5.0 ) {\n\n\t\t\t\tdirection.z *= -1.0; // ( u, v, -1 ) neg z\n\n\t\t\t}\n\n\t\t\treturn direction;\n\n\t\t}\n\n\t\tvoid main() {\n\n\t\t\tvOutputDirection = getDirection( uv, faceIndex );\n\t\t\tgl_Position = vec4( position, 1.0 );\n\n\t\t}\n\t",fragmentShader:"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\n\t\t\t#include \n\n\t\t\tvoid main() {\n\n\t\t\t\tvec3 outputDirection = normalize( vOutputDirection );\n\t\t\t\tvec2 uv = equirectUv( outputDirection );\n\n\t\t\t\tgl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );\n\n\t\t\t}\n\t\t",blending:0,depthTest:!1,depthWrite:!1})}function Br(){return new Xi({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:"\n\n\t\tprecision mediump float;\n\t\tprecision mediump int;\n\n\t\tattribute float faceIndex;\n\n\t\tvarying vec3 vOutputDirection;\n\n\t\t// RH coordinate system; PMREM face-indexing convention\n\t\tvec3 getDirection( vec2 uv, float face ) {\n\n\t\t\tuv = 2.0 * uv - 1.0;\n\n\t\t\tvec3 direction = vec3( uv, 1.0 );\n\n\t\t\tif ( face == 0.0 ) {\n\n\t\t\t\tdirection = direction.zyx; // ( 1, v, u ) pos x\n\n\t\t\t} else if ( face == 1.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xz *= -1.0; // ( -u, 1, -v ) pos y\n\n\t\t\t} else if ( face == 2.0 ) {\n\n\t\t\t\tdirection.x *= -1.0; // ( -u, v, 1 ) pos z\n\n\t\t\t} else if ( face == 3.0 ) {\n\n\t\t\t\tdirection = direction.zyx;\n\t\t\t\tdirection.xz *= -1.0; // ( -1, v, -u ) neg x\n\n\t\t\t} else if ( face == 4.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xy *= -1.0; // ( -u, -1, v ) neg y\n\n\t\t\t} else if ( face == 5.0 ) {\n\n\t\t\t\tdirection.z *= -1.0; // ( u, v, -1 ) neg z\n\n\t\t\t}\n\n\t\t\treturn direction;\n\n\t\t}\n\n\t\tvoid main() {\n\n\t\t\tvOutputDirection = getDirection( uv, faceIndex );\n\t\t\tgl_Position = vec4( position, 1.0 );\n\n\t\t}\n\t",fragmentShader:"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tuniform float flipEnvMap;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform samplerCube envMap;\n\n\t\t\tvoid main() {\n\n\t\t\t\tgl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );\n\n\t\t\t}\n\t\t",blending:0,depthTest:!1,depthWrite:!1})}function zr(t){let e=new WeakMap,n=null;function i(t){const n=t.target;n.removeEventListener("dispose",i);const r=e.get(n);void 0!==r&&(e.delete(n),r.dispose())}return{get:function(r){if(r&&r.isTexture){const s=r.mapping,a=s===u||s===d,o=s===c||s===h;if(a||o){let s=e.get(r);const l=void 0!==s?s.texture.pmremVersion:0;if(r.isRenderTargetTexture&&r.pmremVersion!==l)return null===n&&(n=new Dr(t)),s=a?n.fromEquirectangular(r,s):n.fromCubemap(r,s),s.texture.pmremVersion=r.pmremVersion,e.set(r,s),s.texture;if(void 0!==s)return s.texture;{const l=r.image;return a&&l&&l.height>0||o&&l&&function(t){let e=0;for(let n=0;n<6;n++)void 0!==t[n]&&e++;return 6===e}(l)?(null===n&&(n=new Dr(t)),s=a?n.fromEquirectangular(r):n.fromCubemap(r),s.texture.pmremVersion=r.pmremVersion,e.set(r,s),r.addEventListener("dispose",i),s.texture):null}}}return r},dispose:function(){e=new WeakMap,null!==n&&(n.dispose(),n=null)}}}function kr(t){const e={};function n(n){if(void 0!==e[n])return e[n];let i;switch(n){case"WEBGL_depth_texture":i=t.getExtension("WEBGL_depth_texture")||t.getExtension("MOZ_WEBGL_depth_texture")||t.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":i=t.getExtension("EXT_texture_filter_anisotropic")||t.getExtension("MOZ_EXT_texture_filter_anisotropic")||t.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":i=t.getExtension("WEBGL_compressed_texture_s3tc")||t.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||t.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":i=t.getExtension("WEBGL_compressed_texture_pvrtc")||t.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:i=t.getExtension(n)}return e[n]=i,i}return{has:function(t){return null!==n(t)},init:function(){n("EXT_color_buffer_float"),n("WEBGL_clip_cull_distance"),n("OES_texture_float_linear"),n("EXT_color_buffer_half_float"),n("WEBGL_multisampled_render_to_texture"),n("WEBGL_render_shared_exponent")},get:function(t){const e=n(t);return null===e&&pe("THREE.WebGLRenderer: "+t+" extension not supported."),e}}}function Vr(t,e,n,i){const r={},s=new WeakMap;function a(t){const o=t.target;null!==o.index&&e.remove(o.index);for(const t in o.attributes)e.remove(o.attributes[t]);for(const t in o.morphAttributes){const n=o.morphAttributes[t];for(let t=0,i=n.length;te.maxTextureSize&&(x=Math.ceil(y/e.maxTextureSize),y=e.maxTextureSize);const M=new Float32Array(y*x*4*h),S=new Ie(M,y,x,h);S.type=R,S.needsUpdate=!0;const b=4*_;for(let T=0;T0)return t;const r=e*n;let s=$r[r];if(void 0===s&&(s=new Float32Array(r),$r[r]=s),0!==e){i.toArray(s,0);for(let i=1,r=0;i!==e;++i)r+=n,t[i].toArray(s,r)}return s}function rs(t,e){if(t.length!==e.length)return!1;for(let n=0,i=t.length;n":" "} ${r}: ${n[t]}`)}return i.join("\n")}(t.getShaderSource(e),i)}return r}function ea(t,e){const n=function(t){const e=_e.getPrimaries(_e.workingColorSpace),n=_e.getPrimaries(t);let i;switch(e===n?i="":e===kt&&n===zt?i="LinearDisplayP3ToLinearSRGB":e===zt&&n===kt&&(i="LinearSRGBToLinearDisplayP3"),t){case Dt:case Ot:return[i,"LinearTransferOETF"];case Ut:case Nt:return[i,"sRGBTransferOETF"];default:return console.warn("THREE.WebGLProgram: Unsupported color space:",t),[i,"LinearTransferOETF"]}}(e);return`vec4 ${t}( vec4 value ) { return ${n[0]}( ${n[1]}( value ) ); }`}function na(t,e){let n;switch(e){case 1:n="Linear";break;case 2:n="Reinhard";break;case 3:n="Cineon";break;case 4:n="ACESFilmic";break;case 6:n="AgX";break;case 7:n="Neutral";break;case 5:n="Custom";break;default:console.warn("THREE.WebGLProgram: Unsupported toneMapping:",e),n="Linear"}return"vec3 "+t+"( vec3 color ) { return "+n+"ToneMapping( color ); }"}const ia=new De;function ra(t){return""!==t}function sa(t,e){const n=e.numSpotLightShadows+e.numSpotLightMaps-e.numSpotLightShadowsWithMaps;return t.replace(/NUM_DIR_LIGHTS/g,e.numDirLights).replace(/NUM_SPOT_LIGHTS/g,e.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g,e.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g,n).replace(/NUM_RECT_AREA_LIGHTS/g,e.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g,e.numPointLights).replace(/NUM_HEMI_LIGHTS/g,e.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g,e.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g,e.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g,e.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g,e.numPointLightShadows)}function aa(t,e){return t.replace(/NUM_CLIPPING_PLANES/g,e.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,e.numClippingPlanes-e.numClipIntersection)}const oa=/^[ \t]*#include +<([\w\d./]+)>/gm;function la(t){return t.replace(oa,ha)}const ca=new Map;function ha(t,e){let n=ur[e];if(void 0===n){const t=ca.get(e);if(void 0===t)throw new Error("Can not resolve #include <"+e+">");n=ur[t],console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',e,t)}return la(n)}const ua=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function da(t){return t.replace(ua,pa)}function pa(t,e,n,i){let r="";for(let t=parseInt(e);t0&&(y+="\n"),x=["#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,v].filter(ra).join("\n"),x.length>0&&(x+="\n")):(y=[ma(n),"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,v,n.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",n.batching?"#define USE_BATCHING":"",n.batchingColor?"#define USE_BATCHING_COLOR":"",n.instancing?"#define USE_INSTANCING":"",n.instancingColor?"#define USE_INSTANCING_COLOR":"",n.instancingMorph?"#define USE_INSTANCING_MORPH":"",n.useFog&&n.fog?"#define USE_FOG":"",n.useFog&&n.fogExp2?"#define FOG_EXP2":"",n.map?"#define USE_MAP":"",n.envMap?"#define USE_ENVMAP":"",n.envMap?"#define "+d:"",n.lightMap?"#define USE_LIGHTMAP":"",n.aoMap?"#define USE_AOMAP":"",n.bumpMap?"#define USE_BUMPMAP":"",n.normalMap?"#define USE_NORMALMAP":"",n.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",n.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",n.displacementMap?"#define USE_DISPLACEMENTMAP":"",n.emissiveMap?"#define USE_EMISSIVEMAP":"",n.anisotropy?"#define USE_ANISOTROPY":"",n.anisotropyMap?"#define USE_ANISOTROPYMAP":"",n.clearcoatMap?"#define USE_CLEARCOATMAP":"",n.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",n.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",n.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",n.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",n.specularMap?"#define USE_SPECULARMAP":"",n.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",n.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",n.roughnessMap?"#define USE_ROUGHNESSMAP":"",n.metalnessMap?"#define USE_METALNESSMAP":"",n.alphaMap?"#define USE_ALPHAMAP":"",n.alphaHash?"#define USE_ALPHAHASH":"",n.transmission?"#define USE_TRANSMISSION":"",n.transmissionMap?"#define USE_TRANSMISSIONMAP":"",n.thicknessMap?"#define USE_THICKNESSMAP":"",n.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",n.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",n.mapUv?"#define MAP_UV "+n.mapUv:"",n.alphaMapUv?"#define ALPHAMAP_UV "+n.alphaMapUv:"",n.lightMapUv?"#define LIGHTMAP_UV "+n.lightMapUv:"",n.aoMapUv?"#define AOMAP_UV "+n.aoMapUv:"",n.emissiveMapUv?"#define EMISSIVEMAP_UV "+n.emissiveMapUv:"",n.bumpMapUv?"#define BUMPMAP_UV "+n.bumpMapUv:"",n.normalMapUv?"#define NORMALMAP_UV "+n.normalMapUv:"",n.displacementMapUv?"#define DISPLACEMENTMAP_UV "+n.displacementMapUv:"",n.metalnessMapUv?"#define METALNESSMAP_UV "+n.metalnessMapUv:"",n.roughnessMapUv?"#define ROUGHNESSMAP_UV "+n.roughnessMapUv:"",n.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+n.anisotropyMapUv:"",n.clearcoatMapUv?"#define CLEARCOATMAP_UV "+n.clearcoatMapUv:"",n.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+n.clearcoatNormalMapUv:"",n.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+n.clearcoatRoughnessMapUv:"",n.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+n.iridescenceMapUv:"",n.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+n.iridescenceThicknessMapUv:"",n.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+n.sheenColorMapUv:"",n.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+n.sheenRoughnessMapUv:"",n.specularMapUv?"#define SPECULARMAP_UV "+n.specularMapUv:"",n.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+n.specularColorMapUv:"",n.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+n.specularIntensityMapUv:"",n.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+n.transmissionMapUv:"",n.thicknessMapUv?"#define THICKNESSMAP_UV "+n.thicknessMapUv:"",n.vertexTangents&&!1===n.flatShading?"#define USE_TANGENT":"",n.vertexColors?"#define USE_COLOR":"",n.vertexAlphas?"#define USE_COLOR_ALPHA":"",n.vertexUv1s?"#define USE_UV1":"",n.vertexUv2s?"#define USE_UV2":"",n.vertexUv3s?"#define USE_UV3":"",n.pointsUvs?"#define USE_POINTS_UV":"",n.flatShading?"#define FLAT_SHADED":"",n.skinning?"#define USE_SKINNING":"",n.morphTargets?"#define USE_MORPHTARGETS":"",n.morphNormals&&!1===n.flatShading?"#define USE_MORPHNORMALS":"",n.morphColors?"#define USE_MORPHCOLORS":"",n.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+n.morphTextureStride:"",n.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+n.morphTargetsCount:"",n.doubleSided?"#define DOUBLE_SIDED":"",n.flipSided?"#define FLIP_SIDED":"",n.shadowMapEnabled?"#define USE_SHADOWMAP":"",n.shadowMapEnabled?"#define "+l:"",n.sizeAttenuation?"#define USE_SIZEATTENUATION":"",n.numLightProbes>0?"#define USE_LIGHT_PROBES":"",n.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",n.reverseDepthBuffer?"#define USE_REVERSEDEPTHBUF":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING","\tattribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR","\tattribute vec3 instanceColor;","#endif","#ifdef USE_INSTANCING_MORPH","\tuniform sampler2D morphTexture;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1","\tattribute vec2 uv1;","#endif","#ifdef USE_UV2","\tattribute vec2 uv2;","#endif","#ifdef USE_UV3","\tattribute vec2 uv3;","#endif","#ifdef USE_TANGENT","\tattribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )","\tattribute vec4 color;","#elif defined( USE_COLOR )","\tattribute vec3 color;","#endif","#ifdef USE_SKINNING","\tattribute vec4 skinIndex;","\tattribute vec4 skinWeight;","#endif","\n"].filter(ra).join("\n"),x=[ma(n),"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,v,n.useFog&&n.fog?"#define USE_FOG":"",n.useFog&&n.fogExp2?"#define FOG_EXP2":"",n.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",n.map?"#define USE_MAP":"",n.matcap?"#define USE_MATCAP":"",n.envMap?"#define USE_ENVMAP":"",n.envMap?"#define "+u:"",n.envMap?"#define "+d:"",n.envMap?"#define "+m:"",f?"#define CUBEUV_TEXEL_WIDTH "+f.texelWidth:"",f?"#define CUBEUV_TEXEL_HEIGHT "+f.texelHeight:"",f?"#define CUBEUV_MAX_MIP "+f.maxMip+".0":"",n.lightMap?"#define USE_LIGHTMAP":"",n.aoMap?"#define USE_AOMAP":"",n.bumpMap?"#define USE_BUMPMAP":"",n.normalMap?"#define USE_NORMALMAP":"",n.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",n.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",n.emissiveMap?"#define USE_EMISSIVEMAP":"",n.anisotropy?"#define USE_ANISOTROPY":"",n.anisotropyMap?"#define USE_ANISOTROPYMAP":"",n.clearcoat?"#define USE_CLEARCOAT":"",n.clearcoatMap?"#define USE_CLEARCOATMAP":"",n.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",n.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",n.dispersion?"#define USE_DISPERSION":"",n.iridescence?"#define USE_IRIDESCENCE":"",n.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",n.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",n.specularMap?"#define USE_SPECULARMAP":"",n.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",n.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",n.roughnessMap?"#define USE_ROUGHNESSMAP":"",n.metalnessMap?"#define USE_METALNESSMAP":"",n.alphaMap?"#define USE_ALPHAMAP":"",n.alphaTest?"#define USE_ALPHATEST":"",n.alphaHash?"#define USE_ALPHAHASH":"",n.sheen?"#define USE_SHEEN":"",n.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",n.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",n.transmission?"#define USE_TRANSMISSION":"",n.transmissionMap?"#define USE_TRANSMISSIONMAP":"",n.thicknessMap?"#define USE_THICKNESSMAP":"",n.vertexTangents&&!1===n.flatShading?"#define USE_TANGENT":"",n.vertexColors||n.instancingColor||n.batchingColor?"#define USE_COLOR":"",n.vertexAlphas?"#define USE_COLOR_ALPHA":"",n.vertexUv1s?"#define USE_UV1":"",n.vertexUv2s?"#define USE_UV2":"",n.vertexUv3s?"#define USE_UV3":"",n.pointsUvs?"#define USE_POINTS_UV":"",n.gradientMap?"#define USE_GRADIENTMAP":"",n.flatShading?"#define FLAT_SHADED":"",n.doubleSided?"#define DOUBLE_SIDED":"",n.flipSided?"#define FLIP_SIDED":"",n.shadowMapEnabled?"#define USE_SHADOWMAP":"",n.shadowMapEnabled?"#define "+l:"",n.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",n.numLightProbes>0?"#define USE_LIGHT_PROBES":"",n.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",n.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",n.reverseDepthBuffer?"#define USE_REVERSEDEPTHBUF":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",0!==n.toneMapping?"#define TONE_MAPPING":"",0!==n.toneMapping?ur.tonemapping_pars_fragment:"",0!==n.toneMapping?na("toneMapping",n.toneMapping):"",n.dithering?"#define DITHERING":"",n.opaque?"#define OPAQUE":"",ur.colorspace_pars_fragment,ea("linearToOutputTexel",n.outputColorSpace),(_e.getLuminanceCoefficients(ia),["float luminance( const in vec3 rgb ) {",`\tconst vec3 weights = vec3( ${ia.x.toFixed(4)}, ${ia.y.toFixed(4)}, ${ia.z.toFixed(4)} );`,"\treturn dot( weights, rgb );","}"].join("\n")),n.useDepthPacking?"#define DEPTH_PACKING "+n.depthPacking:"","\n"].filter(ra).join("\n")),a=la(a),a=sa(a,n),a=aa(a,n),o=la(o),o=sa(o,n),o=aa(o,n),a=da(a),o=da(o),!0!==n.isRawShaderMaterial&&(M="#version 300 es\n",y=[g,"#define attribute in","#define varying out","#define texture2D texture"].join("\n")+"\n"+y,x=["#define varying in",n.glslVersion===Gt?"":"layout(location = 0) out highp vec4 pc_fragColor;",n.glslVersion===Gt?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join("\n")+"\n"+x);const S=M+y+a,b=M+x+o,w=$s(r,r.VERTEX_SHADER,S),T=$s(r,r.FRAGMENT_SHADER,b);function E(e){if(t.debug.checkShaderErrors){const n=r.getProgramInfoLog(_).trim(),i=r.getShaderInfoLog(w).trim(),s=r.getShaderInfoLog(T).trim();let a=!0,o=!0;if(!1===r.getProgramParameter(_,r.LINK_STATUS))if(a=!1,"function"==typeof t.debug.onShaderError)t.debug.onShaderError(r,_,w,T);else{const t=ta(r,w,"vertex"),i=ta(r,T,"fragment");console.error("THREE.WebGLProgram: Shader Error "+r.getError()+" - VALIDATE_STATUS "+r.getProgramParameter(_,r.VALIDATE_STATUS)+"\n\nMaterial Name: "+e.name+"\nMaterial Type: "+e.type+"\n\nProgram Info Log: "+n+"\n"+t+"\n"+i)}else""!==n?console.warn("THREE.WebGLProgram: Program Info Log:",n):""!==i&&""!==s||(o=!1);o&&(e.diagnostics={runnable:a,programLog:n,vertexShader:{log:i,prefix:y},fragmentShader:{log:s,prefix:x}})}r.deleteShader(w),r.deleteShader(T),A=new Ks(r,_),C=function(t,e){const n={},i=t.getProgramParameter(e,t.ACTIVE_ATTRIBUTES);for(let r=0;r0,Y=s.clearcoat>0,Z=s.dispersion>0,J=s.iridescence>0,K=s.sheen>0,$=s.transmission>0,Q=q&&!!s.anisotropyMap,tt=Y&&!!s.clearcoatMap,et=Y&&!!s.clearcoatNormalMap,nt=Y&&!!s.clearcoatRoughnessMap,it=J&&!!s.iridescenceMap,rt=J&&!!s.iridescenceThicknessMap,st=K&&!!s.sheenColorMap,at=K&&!!s.sheenRoughnessMap,ot=!!s.specularMap,lt=!!s.specularColorMap,ct=!!s.specularIntensityMap,ht=$&&!!s.transmissionMap,ut=$&&!!s.thicknessMap,dt=!!s.gradientMap,pt=!!s.alphaMap,mt=s.alphaTest>0,ft=!!s.alphaHash,gt=!!s.extensions;let vt=0;s.toneMapped&&(null!==U&&!0!==U.isXRRenderTarget||(vt=t.toneMapping));const _t={shaderID:T,shaderType:s.type,shaderName:s.name,vertexShader:C,fragmentShader:R,defines:s.defines,customVertexShaderID:P,customFragmentShaderID:I,isRawShaderMaterial:!0===s.isRawShaderMaterial,glslVersion:s.glslVersion,precision:f,batching:N,batchingColor:N&&null!==y._colorsTexture,instancing:D,instancingColor:D&&null!==y.instanceColor,instancingMorph:D&&null!==y.morphTexture,supportsVertexTextures:m,outputColorSpace:null===U?t.outputColorSpace:!0===U.isXRRenderTarget?U.texture.colorSpace:Dt,alphaToCoverage:!!s.alphaToCoverage,map:O,matcap:F,envMap:B,envMapMode:B&&b.mapping,envMapCubeUVHeight:w,aoMap:z,lightMap:k,bumpMap:V,normalMap:H,displacementMap:m&&G,emissiveMap:W,normalMapObjectSpace:H&&1===s.normalMapType,normalMapTangentSpace:H&&0===s.normalMapType,metalnessMap:X,roughnessMap:j,anisotropy:q,anisotropyMap:Q,clearcoat:Y,clearcoatMap:tt,clearcoatNormalMap:et,clearcoatRoughnessMap:nt,dispersion:Z,iridescence:J,iridescenceMap:it,iridescenceThicknessMap:rt,sheen:K,sheenColorMap:st,sheenRoughnessMap:at,specularMap:ot,specularColorMap:lt,specularIntensityMap:ct,transmission:$,transmissionMap:ht,thicknessMap:ut,gradientMap:dt,opaque:!1===s.transparent&&1===s.blending&&!1===s.alphaToCoverage,alphaMap:pt,alphaTest:mt,alphaHash:ft,combine:s.combine,mapUv:O&&v(s.map.channel),aoMapUv:z&&v(s.aoMap.channel),lightMapUv:k&&v(s.lightMap.channel),bumpMapUv:V&&v(s.bumpMap.channel),normalMapUv:H&&v(s.normalMap.channel),displacementMapUv:G&&v(s.displacementMap.channel),emissiveMapUv:W&&v(s.emissiveMap.channel),metalnessMapUv:X&&v(s.metalnessMap.channel),roughnessMapUv:j&&v(s.roughnessMap.channel),anisotropyMapUv:Q&&v(s.anisotropyMap.channel),clearcoatMapUv:tt&&v(s.clearcoatMap.channel),clearcoatNormalMapUv:et&&v(s.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:nt&&v(s.clearcoatRoughnessMap.channel),iridescenceMapUv:it&&v(s.iridescenceMap.channel),iridescenceThicknessMapUv:rt&&v(s.iridescenceThicknessMap.channel),sheenColorMapUv:st&&v(s.sheenColorMap.channel),sheenRoughnessMapUv:at&&v(s.sheenRoughnessMap.channel),specularMapUv:ot&&v(s.specularMap.channel),specularColorMapUv:lt&&v(s.specularColorMap.channel),specularIntensityMapUv:ct&&v(s.specularIntensityMap.channel),transmissionMapUv:ht&&v(s.transmissionMap.channel),thicknessMapUv:ut&&v(s.thicknessMap.channel),alphaMapUv:pt&&v(s.alphaMap.channel),vertexTangents:!!M.attributes.tangent&&(H||q),vertexColors:s.vertexColors,vertexAlphas:!0===s.vertexColors&&!!M.attributes.color&&4===M.attributes.color.itemSize,pointsUvs:!0===y.isPoints&&!!M.attributes.uv&&(O||pt),fog:!!x,useFog:!0===s.fog,fogExp2:!!x&&x.isFogExp2,flatShading:!0===s.flatShading,sizeAttenuation:!0===s.sizeAttenuation,logarithmicDepthBuffer:u,reverseDepthBuffer:d,skinning:!0===y.isSkinnedMesh,morphTargets:void 0!==M.morphAttributes.position,morphNormals:void 0!==M.morphAttributes.normal,morphColors:void 0!==M.morphAttributes.color,morphTargetsCount:A,morphTextureStride:L,numDirLights:o.directional.length,numPointLights:o.point.length,numSpotLights:o.spot.length,numSpotLightMaps:o.spotLightMap.length,numRectAreaLights:o.rectArea.length,numHemiLights:o.hemi.length,numDirLightShadows:o.directionalShadowMap.length,numPointLightShadows:o.pointShadowMap.length,numSpotLightShadows:o.spotShadowMap.length,numSpotLightShadowsWithMaps:o.numSpotLightShadowsWithMaps,numLightProbes:o.numLightProbes,numClippingPlanes:a.numPlanes,numClipIntersection:a.numIntersection,dithering:s.dithering,shadowMapEnabled:t.shadowMap.enabled&&h.length>0,shadowMapType:t.shadowMap.type,toneMapping:vt,decodeVideoTexture:O&&!0===s.map.isVideoTexture&&_e.getTransfer(s.map.colorSpace)===Bt,premultipliedAlpha:s.premultipliedAlpha,doubleSided:2===s.side,flipSided:1===s.side,useDepthPacking:s.depthPacking>=0,depthPacking:s.depthPacking||0,index0AttributeName:s.index0AttributeName,extensionClipCullDistance:gt&&!0===s.extensions.clipCullDistance&&i.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(gt&&!0===s.extensions.multiDraw||N)&&i.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:i.has("KHR_parallel_shader_compile"),customProgramCacheKey:s.customProgramCacheKey()};return _t.vertexUv1s=c.has(1),_t.vertexUv2s=c.has(2),_t.vertexUv3s=c.has(3),c.clear(),_t},getProgramCacheKey:function(e){const n=[];if(e.shaderID?n.push(e.shaderID):(n.push(e.customVertexShaderID),n.push(e.customFragmentShaderID)),void 0!==e.defines)for(const t in e.defines)n.push(t),n.push(e.defines[t]);return!1===e.isRawShaderMaterial&&(function(t,e){t.push(e.precision),t.push(e.outputColorSpace),t.push(e.envMapMode),t.push(e.envMapCubeUVHeight),t.push(e.mapUv),t.push(e.alphaMapUv),t.push(e.lightMapUv),t.push(e.aoMapUv),t.push(e.bumpMapUv),t.push(e.normalMapUv),t.push(e.displacementMapUv),t.push(e.emissiveMapUv),t.push(e.metalnessMapUv),t.push(e.roughnessMapUv),t.push(e.anisotropyMapUv),t.push(e.clearcoatMapUv),t.push(e.clearcoatNormalMapUv),t.push(e.clearcoatRoughnessMapUv),t.push(e.iridescenceMapUv),t.push(e.iridescenceThicknessMapUv),t.push(e.sheenColorMapUv),t.push(e.sheenRoughnessMapUv),t.push(e.specularMapUv),t.push(e.specularColorMapUv),t.push(e.specularIntensityMapUv),t.push(e.transmissionMapUv),t.push(e.thicknessMapUv),t.push(e.combine),t.push(e.fogExp2),t.push(e.sizeAttenuation),t.push(e.morphTargetsCount),t.push(e.morphAttributeCount),t.push(e.numDirLights),t.push(e.numPointLights),t.push(e.numSpotLights),t.push(e.numSpotLightMaps),t.push(e.numHemiLights),t.push(e.numRectAreaLights),t.push(e.numDirLightShadows),t.push(e.numPointLightShadows),t.push(e.numSpotLightShadows),t.push(e.numSpotLightShadowsWithMaps),t.push(e.numLightProbes),t.push(e.shadowMapType),t.push(e.toneMapping),t.push(e.numClippingPlanes),t.push(e.numClipIntersection),t.push(e.depthPacking)}(n,e),function(t,e){o.disableAll(),e.supportsVertexTextures&&o.enable(0),e.instancing&&o.enable(1),e.instancingColor&&o.enable(2),e.instancingMorph&&o.enable(3),e.matcap&&o.enable(4),e.envMap&&o.enable(5),e.normalMapObjectSpace&&o.enable(6),e.normalMapTangentSpace&&o.enable(7),e.clearcoat&&o.enable(8),e.iridescence&&o.enable(9),e.alphaTest&&o.enable(10),e.vertexColors&&o.enable(11),e.vertexAlphas&&o.enable(12),e.vertexUv1s&&o.enable(13),e.vertexUv2s&&o.enable(14),e.vertexUv3s&&o.enable(15),e.vertexTangents&&o.enable(16),e.anisotropy&&o.enable(17),e.alphaHash&&o.enable(18),e.batching&&o.enable(19),e.dispersion&&o.enable(20),e.batchingColor&&o.enable(21),t.push(o.mask),o.disableAll(),e.fog&&o.enable(0),e.useFog&&o.enable(1),e.flatShading&&o.enable(2),e.logarithmicDepthBuffer&&o.enable(3),e.reverseDepthBuffer&&o.enable(4),e.skinning&&o.enable(5),e.morphTargets&&o.enable(6),e.morphNormals&&o.enable(7),e.morphColors&&o.enable(8),e.premultipliedAlpha&&o.enable(9),e.shadowMapEnabled&&o.enable(10),e.doubleSided&&o.enable(11),e.flipSided&&o.enable(12),e.useDepthPacking&&o.enable(13),e.dithering&&o.enable(14),e.transmission&&o.enable(15),e.sheen&&o.enable(16),e.opaque&&o.enable(17),e.pointsUvs&&o.enable(18),e.decodeVideoTexture&&o.enable(19),e.alphaToCoverage&&o.enable(20),t.push(o.mask)}(n,e),n.push(t.outputColorSpace)),n.push(e.customProgramCacheKey),n.join()},getUniforms:function(t){const e=g[t.type];let n;if(e){const t=pr[e];n=Wi.clone(t.uniforms)}else n=t.uniforms;return n},acquireProgram:function(e,n){let i;for(let t=0,e=h.length;t0?i.push(h):!0===a.transparent?r.push(h):n.push(h)},unshift:function(t,e,a,o,l,c){const h=s(t,e,a,o,l,c);a.transmission>0?i.unshift(h):!0===a.transparent?r.unshift(h):n.unshift(h)},finish:function(){for(let n=e,i=t.length;n1&&n.sort(t||Ma),i.length>1&&i.sort(e||Sa),r.length>1&&r.sort(e||Sa)}}}function wa(){let t=new WeakMap;return{get:function(e,n){const i=t.get(e);let r;return void 0===i?(r=new ba,t.set(e,[r])):n>=i.length?(r=new ba,i.push(r)):r=i[n],r},dispose:function(){t=new WeakMap}}}function Ta(){const t={};return{get:function(e){if(void 0!==t[e.id])return t[e.id];let n;switch(e.type){case"DirectionalLight":n={direction:new De,color:new ii};break;case"SpotLight":n={position:new De,direction:new De,color:new ii,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":n={position:new De,color:new ii,distance:0,decay:0};break;case"HemisphereLight":n={direction:new De,skyColor:new ii,groundColor:new ii};break;case"RectAreaLight":n={color:new ii,position:new De,halfWidth:new De,halfHeight:new De}}return t[e.id]=n,n}}}let Ea=0;function Aa(t,e){return(e.castShadow?2:0)-(t.castShadow?2:0)+(e.map?1:0)-(t.map?1:0)}function Ca(t){const e=new Ta,n=function(){const t={};return{get:function(e){if(void 0!==t[e.id])return t[e.id];let n;switch(e.type){case"DirectionalLight":case"SpotLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new re};break;case"PointLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new re,shadowCameraNear:1,shadowCameraFar:1e3}}return t[e.id]=n,n}}}(),i={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let t=0;t<9;t++)i.probe.push(new De);const r=new De,s=new un,a=new un;return{setup:function(r){let s=0,a=0,o=0;for(let t=0;t<9;t++)i.probe[t].set(0,0,0);let l=0,c=0,h=0,u=0,d=0,p=0,m=0,f=0,g=0,v=0,_=0;r.sort(Aa);for(let t=0,y=r.length;t0&&(!0===t.has("OES_texture_float_linear")?(i.rectAreaLTC1=dr.LTC_FLOAT_1,i.rectAreaLTC2=dr.LTC_FLOAT_2):(i.rectAreaLTC1=dr.LTC_HALF_1,i.rectAreaLTC2=dr.LTC_HALF_2)),i.ambient[0]=s,i.ambient[1]=a,i.ambient[2]=o;const y=i.hash;y.directionalLength===l&&y.pointLength===c&&y.spotLength===h&&y.rectAreaLength===u&&y.hemiLength===d&&y.numDirectionalShadows===p&&y.numPointShadows===m&&y.numSpotShadows===f&&y.numSpotMaps===g&&y.numLightProbes===_||(i.directional.length=l,i.spot.length=h,i.rectArea.length=u,i.point.length=c,i.hemi.length=d,i.directionalShadow.length=p,i.directionalShadowMap.length=p,i.pointShadow.length=m,i.pointShadowMap.length=m,i.spotShadow.length=f,i.spotShadowMap.length=f,i.directionalShadowMatrix.length=p,i.pointShadowMatrix.length=m,i.spotLightMatrix.length=f+g-v,i.spotLightMap.length=g,i.numSpotLightShadowsWithMaps=v,i.numLightProbes=_,y.directionalLength=l,y.pointLength=c,y.spotLength=h,y.rectAreaLength=u,y.hemiLength=d,y.numDirectionalShadows=p,y.numPointShadows=m,y.numSpotShadows=f,y.numSpotMaps=g,y.numLightProbes=_,i.version=Ea++)},setupView:function(t,e){let n=0,o=0,l=0,c=0,h=0;const u=e.matrixWorldInverse;for(let e=0,d=t.length;e=r.length?(s=new Ra(t),r.push(s)):s=r[i],s},dispose:function(){e=new WeakMap}}}class Ia extends ai{constructor(t){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=3200,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(t)}copy(t){return super.copy(t),this.depthPacking=t.depthPacking,this.map=t.map,this.alphaMap=t.alphaMap,this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this}}class La extends ai{constructor(t){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(t)}copy(t){return super.copy(t),this.map=t.map,this.alphaMap=t.alphaMap,this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this}}function Ua(t,e,n){let i=new or;const r=new re,s=new re,a=new Ce,o=new Ia({depthPacking:3201}),l=new La,c={},h=n.maxTextureSize,u={0:1,1:0,2:2},d=new Xi({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new re},radius:{value:4}},vertexShader:"void main() {\n\tgl_Position = vec4( position, 1.0 );\n}",fragmentShader:"uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include \nvoid main() {\n\tconst float samples = float( VSM_SAMPLES );\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );\n\tfloat uvStart = samples <= 1.0 ? 0.0 : - 1.0;\n\tfor ( float i = 0.0; i < samples; i ++ ) {\n\t\tfloat uvOffset = uvStart + i * uvStride;\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean / samples;\n\tsquared_mean = squared_mean / samples;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}"}),p=d.clone();p.defines.HORIZONTAL_PASS=1;const m=new Ei;m.setAttribute("position",new fi(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const f=new Bi(m,d),g=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=1;let _=this.type;function y(n,i){const s=e.update(f);d.defines.VSM_SAMPLES!==n.blurSamples&&(d.defines.VSM_SAMPLES=n.blurSamples,p.defines.VSM_SAMPLES=n.blurSamples,d.needsUpdate=!0,p.needsUpdate=!0),null===n.mapPass&&(n.mapPass=new Pe(r.x,r.y)),d.uniforms.shadow_pass.value=n.map.texture,d.uniforms.resolution.value=n.mapSize,d.uniforms.radius.value=n.radius,t.setRenderTarget(n.mapPass),t.clear(),t.renderBufferDirect(i,null,s,d,f,null),p.uniforms.shadow_pass.value=n.mapPass.texture,p.uniforms.resolution.value=n.mapSize,p.uniforms.radius.value=n.radius,t.setRenderTarget(n.map),t.clear(),t.renderBufferDirect(i,null,s,p,f,null)}function x(e,n,i,r){let s=null;const a=!0===i.isPointLight?e.customDistanceMaterial:e.customDepthMaterial;if(void 0!==a)s=a;else if(s=!0===i.isPointLight?l:o,t.localClippingEnabled&&!0===n.clipShadows&&Array.isArray(n.clippingPlanes)&&0!==n.clippingPlanes.length||n.displacementMap&&0!==n.displacementScale||n.alphaMap&&n.alphaTest>0||n.map&&n.alphaTest>0){const t=s.uuid,e=n.uuid;let i=c[t];void 0===i&&(i={},c[t]=i);let r=i[e];void 0===r&&(r=s.clone(),i[e]=r,n.addEventListener("dispose",S)),s=r}return s.visible=n.visible,s.wireframe=n.wireframe,s.side=3===r?null!==n.shadowSide?n.shadowSide:n.side:null!==n.shadowSide?n.shadowSide:u[n.side],s.alphaMap=n.alphaMap,s.alphaTest=n.alphaTest,s.map=n.map,s.clipShadows=n.clipShadows,s.clippingPlanes=n.clippingPlanes,s.clipIntersection=n.clipIntersection,s.displacementMap=n.displacementMap,s.displacementScale=n.displacementScale,s.displacementBias=n.displacementBias,s.wireframeLinewidth=n.wireframeLinewidth,s.linewidth=n.linewidth,!0===i.isPointLight&&!0===s.isMeshDistanceMaterial&&(t.properties.get(s).light=i),s}function M(n,r,s,a,o){if(!1===n.visible)return;if(n.layers.test(r.layers)&&(n.isMesh||n.isLine||n.isPoints)&&(n.castShadow||n.receiveShadow&&3===o)&&(!n.frustumCulled||i.intersectsObject(n))){n.modelViewMatrix.multiplyMatrices(s.matrixWorldInverse,n.matrixWorld);const i=e.update(n),l=n.material;if(Array.isArray(l)){const e=i.groups;for(let c=0,h=e.length;ch||r.y>h)&&(r.x>h&&(s.x=Math.floor(h/f.x),r.x=s.x*f.x,u.mapSize.x=s.x),r.y>h&&(s.y=Math.floor(h/f.y),r.y=s.y*f.y,u.mapSize.y=s.y)),null===u.map||!0===p||!0===m){const t=3!==this.type?{minFilter:v,magFilter:v}:{};null!==u.map&&u.map.dispose(),u.map=new Pe(r.x,r.y,t),u.map.texture.name=c.name+".shadowMap",u.camera.updateProjectionMatrix()}t.setRenderTarget(u.map),t.clear();const g=u.getViewportCount();for(let t=0;t=1):-1!==U.indexOf("OpenGL ES")&&(L=parseFloat(/^OpenGL ES (\d)/.exec(U)[1]),I=L>=2);let D=null,N={};const O=t.getParameter(t.SCISSOR_BOX),F=t.getParameter(t.VIEWPORT),B=(new Ce).fromArray(O),z=(new Ce).fromArray(F);function k(e,n,i,r){const s=new Uint8Array(4),a=t.createTexture();t.bindTexture(e,a),t.texParameteri(e,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(e,t.TEXTURE_MAG_FILTER,t.NEAREST);for(let a=0;ae?(t.repeat.x=1,t.repeat.y=n/e,t.offset.x=0,t.offset.y=(1-t.repeat.y)/2):(t.repeat.x=e/n,t.repeat.y=1,t.offset.x=(1-t.repeat.x)/2,t.offset.y=0),t},cover:function(t,e){const n=t.image&&t.image.width?t.image.width/t.image.height:1;return n>e?(t.repeat.x=e/n,t.repeat.y=1,t.offset.x=(1-t.repeat.x)/2,t.offset.y=0):(t.repeat.x=1,t.repeat.y=n/e,t.offset.x=0,t.offset.y=(1-t.repeat.y)/2),t},fill:function(t){return t.repeat.x=1,t.repeat.y=1,t.offset.x=0,t.offset.y=0,t},getByteLength:Oa};function Ba(t,e,n,i,r,s,a){const o=e.has("WEBGL_multisampled_render_to_texture")?e.get("WEBGL_multisampled_render_to_texture"):null,l="undefined"!=typeof navigator&&/OculusBrowser/g.test(navigator.userAgent),c=new re,h=new WeakMap;let u;const d=new WeakMap;let p=!1;try{p="undefined"!=typeof OffscreenCanvas&&null!==new OffscreenCanvas(1,1).getContext("2d")}catch(t){}function w(t,e){return p?new OffscreenCanvas(t,e):he("canvas")}function T(t,e,n){let i=1;const r=it(t);if((r.width>n||r.height>n)&&(i=n/Math.max(r.width,r.height)),i<1){if("undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&t instanceof ImageBitmap||"undefined"!=typeof VideoFrame&&t instanceof VideoFrame){const n=Math.floor(i*r.width),s=Math.floor(i*r.height);void 0===u&&(u=w(n,s));const a=e?w(n,s):u;return a.width=n,a.height=s,a.getContext("2d").drawImage(t,0,0,n,s),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+r.width+"x"+r.height+") to ("+n+"x"+s+")."),a}return"data"in t&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+r.width+"x"+r.height+")."),t}return t}function A(t){return t.generateMipmaps&&t.minFilter!==v&&t.minFilter!==x}function P(e){t.generateMipmap(e)}function I(n,i,r,s,a=!1){if(null!==n){if(void 0!==t[n])return t[n];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+n+"'")}let o=i;if(i===t.RED&&(r===t.FLOAT&&(o=t.R32F),r===t.HALF_FLOAT&&(o=t.R16F),r===t.UNSIGNED_BYTE&&(o=t.R8)),i===t.RED_INTEGER&&(r===t.UNSIGNED_BYTE&&(o=t.R8UI),r===t.UNSIGNED_SHORT&&(o=t.R16UI),r===t.UNSIGNED_INT&&(o=t.R32UI),r===t.BYTE&&(o=t.R8I),r===t.SHORT&&(o=t.R16I),r===t.INT&&(o=t.R32I)),i===t.RG&&(r===t.FLOAT&&(o=t.RG32F),r===t.HALF_FLOAT&&(o=t.RG16F),r===t.UNSIGNED_BYTE&&(o=t.RG8)),i===t.RG_INTEGER&&(r===t.UNSIGNED_BYTE&&(o=t.RG8UI),r===t.UNSIGNED_SHORT&&(o=t.RG16UI),r===t.UNSIGNED_INT&&(o=t.RG32UI),r===t.BYTE&&(o=t.RG8I),r===t.SHORT&&(o=t.RG16I),r===t.INT&&(o=t.RG32I)),i===t.RGB_INTEGER&&(r===t.UNSIGNED_BYTE&&(o=t.RGB8UI),r===t.UNSIGNED_SHORT&&(o=t.RGB16UI),r===t.UNSIGNED_INT&&(o=t.RGB32UI),r===t.BYTE&&(o=t.RGB8I),r===t.SHORT&&(o=t.RGB16I),r===t.INT&&(o=t.RGB32I)),i===t.RGBA_INTEGER&&(r===t.UNSIGNED_BYTE&&(o=t.RGBA8UI),r===t.UNSIGNED_SHORT&&(o=t.RGBA16UI),r===t.UNSIGNED_INT&&(o=t.RGBA32UI),r===t.BYTE&&(o=t.RGBA8I),r===t.SHORT&&(o=t.RGBA16I),r===t.INT&&(o=t.RGBA32I)),i===t.RGB&&r===t.UNSIGNED_INT_5_9_9_9_REV&&(o=t.RGB9_E5),i===t.RGBA){const e=a?Ft:_e.getTransfer(s);r===t.FLOAT&&(o=t.RGBA32F),r===t.HALF_FLOAT&&(o=t.RGBA16F),r===t.UNSIGNED_BYTE&&(o=e===Bt?t.SRGB8_ALPHA8:t.RGBA8),r===t.UNSIGNED_SHORT_4_4_4_4&&(o=t.RGBA4),r===t.UNSIGNED_SHORT_5_5_5_1&&(o=t.RGB5_A1)}return o!==t.R16F&&o!==t.R32F&&o!==t.RG16F&&o!==t.RG32F&&o!==t.RGBA16F&&o!==t.RGBA32F||e.get("EXT_color_buffer_float"),o}function L(e,n){let i;return e?null===n||n===C||n===U?i=t.DEPTH24_STENCIL8:n===R?i=t.DEPTH32F_STENCIL8:n===E&&(i=t.DEPTH24_STENCIL8,console.warn("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):null===n||n===C||n===U?i=t.DEPTH_COMPONENT24:n===R?i=t.DEPTH_COMPONENT32F:n===E&&(i=t.DEPTH_COMPONENT16),i}function D(t,e){return!0===A(t)||t.isFramebufferTexture&&t.minFilter!==v&&t.minFilter!==x?Math.log2(Math.max(e.width,e.height))+1:void 0!==t.mipmaps&&t.mipmaps.length>0?t.mipmaps.length:t.isCompressedTexture&&Array.isArray(t.image)?e.mipmaps.length:1}function N(t){const e=t.target;e.removeEventListener("dispose",N),function(t){const e=i.get(t);if(void 0===e.__webglInit)return;const n=t.source,r=d.get(n);if(r){const i=r[e.__cacheKey];i.usedTimes--,0===i.usedTimes&&B(t),0===Object.keys(r).length&&d.delete(n)}i.remove(t)}(e),e.isVideoTexture&&h.delete(e)}function O(e){const n=e.target;n.removeEventListener("dispose",O),function(e){const n=i.get(e);if(e.depthTexture&&e.depthTexture.dispose(),e.isWebGLCubeRenderTarget)for(let e=0;e<6;e++){if(Array.isArray(n.__webglFramebuffer[e]))for(let i=0;i0&&s.__version!==e.version){const t=e.image;if(null===t)console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");else{if(!1!==t.complete)return void Y(s,e,r);console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete")}}n.bindTexture(t.TEXTURE_2D,s.__webglTexture,t.TEXTURE0+r)}const G={[m]:t.REPEAT,[f]:t.CLAMP_TO_EDGE,[g]:t.MIRRORED_REPEAT},W={[v]:t.NEAREST,[_]:t.NEAREST_MIPMAP_NEAREST,[y]:t.NEAREST_MIPMAP_LINEAR,[x]:t.LINEAR,[M]:t.LINEAR_MIPMAP_NEAREST,[S]:t.LINEAR_MIPMAP_LINEAR},X={512:t.NEVER,519:t.ALWAYS,513:t.LESS,515:t.LEQUAL,514:t.EQUAL,518:t.GEQUAL,516:t.GREATER,517:t.NOTEQUAL};function j(n,s){if(s.type!==R||!1!==e.has("OES_texture_float_linear")||s.magFilter!==x&&s.magFilter!==M&&s.magFilter!==y&&s.magFilter!==S&&s.minFilter!==x&&s.minFilter!==M&&s.minFilter!==y&&s.minFilter!==S||console.warn("THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),t.texParameteri(n,t.TEXTURE_WRAP_S,G[s.wrapS]),t.texParameteri(n,t.TEXTURE_WRAP_T,G[s.wrapT]),n!==t.TEXTURE_3D&&n!==t.TEXTURE_2D_ARRAY||t.texParameteri(n,t.TEXTURE_WRAP_R,G[s.wrapR]),t.texParameteri(n,t.TEXTURE_MAG_FILTER,W[s.magFilter]),t.texParameteri(n,t.TEXTURE_MIN_FILTER,W[s.minFilter]),s.compareFunction&&(t.texParameteri(n,t.TEXTURE_COMPARE_MODE,t.COMPARE_REF_TO_TEXTURE),t.texParameteri(n,t.TEXTURE_COMPARE_FUNC,X[s.compareFunction])),!0===e.has("EXT_texture_filter_anisotropic")){if(s.magFilter===v)return;if(s.minFilter!==y&&s.minFilter!==S)return;if(s.type===R&&!1===e.has("OES_texture_float_linear"))return;if(s.anisotropy>1||i.get(s).__currentAnisotropy){const a=e.get("EXT_texture_filter_anisotropic");t.texParameterf(n,a.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(s.anisotropy,r.getMaxAnisotropy())),i.get(s).__currentAnisotropy=s.anisotropy}}}function q(e,n){let i=!1;void 0===e.__webglInit&&(e.__webglInit=!0,n.addEventListener("dispose",N));const r=n.source;let s=d.get(r);void 0===s&&(s={},d.set(r,s));const o=function(t){const e=[];return e.push(t.wrapS),e.push(t.wrapT),e.push(t.wrapR||0),e.push(t.magFilter),e.push(t.minFilter),e.push(t.anisotropy),e.push(t.internalFormat),e.push(t.format),e.push(t.type),e.push(t.generateMipmaps),e.push(t.premultiplyAlpha),e.push(t.flipY),e.push(t.unpackAlignment),e.push(t.colorSpace),e.join()}(n);if(o!==e.__cacheKey){void 0===s[o]&&(s[o]={texture:t.createTexture(),usedTimes:0},a.memory.textures++,i=!0),s[o].usedTimes++;const r=s[e.__cacheKey];void 0!==r&&(s[e.__cacheKey].usedTimes--,0===r.usedTimes&&B(n)),e.__cacheKey=o,e.__webglTexture=s[o].texture}return i}function Y(e,a,o){let l=t.TEXTURE_2D;(a.isDataArrayTexture||a.isCompressedArrayTexture)&&(l=t.TEXTURE_2D_ARRAY),a.isData3DTexture&&(l=t.TEXTURE_3D);const c=q(e,a),h=a.source;n.bindTexture(l,e.__webglTexture,t.TEXTURE0+o);const u=i.get(h);if(h.version!==u.__version||!0===c){n.activeTexture(t.TEXTURE0+o);const e=_e.getPrimaries(_e.workingColorSpace),i=a.colorSpace===Lt?null:_e.getPrimaries(a.colorSpace),d=a.colorSpace===Lt||e===i?t.NONE:t.BROWSER_DEFAULT_WEBGL;t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,a.flipY),t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,a.premultiplyAlpha),t.pixelStorei(t.UNPACK_ALIGNMENT,a.unpackAlignment),t.pixelStorei(t.UNPACK_COLORSPACE_CONVERSION_WEBGL,d);let p=T(a.image,!1,r.maxTextureSize);p=nt(a,p);const m=s.convert(a.format,a.colorSpace),f=s.convert(a.type);let g,v=I(a.internalFormat,m,f,a.colorSpace,a.isVideoTexture);j(l,a);const _=a.mipmaps,y=!0!==a.isVideoTexture,x=void 0===u.__version||!0===c,M=h.dataReady,S=D(a,p);if(a.isDepthTexture)v=L(a.format===V,a.type),x&&(y?n.texStorage2D(t.TEXTURE_2D,1,v,p.width,p.height):n.texImage2D(t.TEXTURE_2D,0,v,p.width,p.height,0,m,f,null));else if(a.isDataTexture)if(_.length>0){y&&x&&n.texStorage2D(t.TEXTURE_2D,S,v,_[0].width,_[0].height);for(let e=0,i=_.length;e0){const i=Oa(g.width,g.height,a.format,a.type);for(const r of a.layerUpdates){const s=g.data.subarray(r*i/g.data.BYTES_PER_ELEMENT,(r+1)*i/g.data.BYTES_PER_ELEMENT);n.compressedTexSubImage3D(t.TEXTURE_2D_ARRAY,e,0,0,r,g.width,g.height,1,m,s,0,0)}a.clearLayerUpdates()}else n.compressedTexSubImage3D(t.TEXTURE_2D_ARRAY,e,0,0,0,g.width,g.height,p.depth,m,g.data,0,0)}else n.compressedTexImage3D(t.TEXTURE_2D_ARRAY,e,v,g.width,g.height,p.depth,0,g.data,0,0);else console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else y?M&&n.texSubImage3D(t.TEXTURE_2D_ARRAY,e,0,0,0,g.width,g.height,p.depth,m,f,g.data):n.texImage3D(t.TEXTURE_2D_ARRAY,e,v,g.width,g.height,p.depth,0,m,f,g.data)}else{y&&x&&n.texStorage2D(t.TEXTURE_2D,S,v,_[0].width,_[0].height);for(let e=0,i=_.length;e0){const e=Oa(p.width,p.height,a.format,a.type);for(const i of a.layerUpdates){const r=p.data.subarray(i*e/p.data.BYTES_PER_ELEMENT,(i+1)*e/p.data.BYTES_PER_ELEMENT);n.texSubImage3D(t.TEXTURE_2D_ARRAY,0,0,0,i,p.width,p.height,1,m,f,r)}a.clearLayerUpdates()}else n.texSubImage3D(t.TEXTURE_2D_ARRAY,0,0,0,0,p.width,p.height,p.depth,m,f,p.data)}else n.texImage3D(t.TEXTURE_2D_ARRAY,0,v,p.width,p.height,p.depth,0,m,f,p.data);else if(a.isData3DTexture)y?(x&&n.texStorage3D(t.TEXTURE_3D,S,v,p.width,p.height,p.depth),M&&n.texSubImage3D(t.TEXTURE_3D,0,0,0,0,p.width,p.height,p.depth,m,f,p.data)):n.texImage3D(t.TEXTURE_3D,0,v,p.width,p.height,p.depth,0,m,f,p.data);else if(a.isFramebufferTexture){if(x)if(y)n.texStorage2D(t.TEXTURE_2D,S,v,p.width,p.height);else{let e=p.width,i=p.height;for(let r=0;r>=1,i>>=1}}else if(_.length>0){if(y&&x){const e=it(_[0]);n.texStorage2D(t.TEXTURE_2D,S,v,e.width,e.height)}for(let e=0,i=_.length;e>h),i=Math.max(1,r.height>>h);c===t.TEXTURE_3D||c===t.TEXTURE_2D_ARRAY?n.texImage3D(c,h,p,e,i,r.depth,0,u,d,null):n.texImage2D(c,h,p,e,i,0,u,d,null)}n.bindFramebuffer(t.FRAMEBUFFER,e),et(r)?o.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,l,c,i.get(a).__webglTexture,0,tt(r)):(c===t.TEXTURE_2D||c>=t.TEXTURE_CUBE_MAP_POSITIVE_X&&c<=t.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&t.framebufferTexture2D(t.FRAMEBUFFER,l,c,i.get(a).__webglTexture,h),n.bindFramebuffer(t.FRAMEBUFFER,null)}function J(e,n,i){if(t.bindRenderbuffer(t.RENDERBUFFER,e),n.depthBuffer){const r=n.depthTexture,s=r&&r.isDepthTexture?r.type:null,a=L(n.stencilBuffer,s),l=n.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,c=tt(n);et(n)?o.renderbufferStorageMultisampleEXT(t.RENDERBUFFER,c,a,n.width,n.height):i?t.renderbufferStorageMultisample(t.RENDERBUFFER,c,a,n.width,n.height):t.renderbufferStorage(t.RENDERBUFFER,a,n.width,n.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,l,t.RENDERBUFFER,e)}else{const e=n.textures;for(let r=0;r{delete r.__boundDepthTexture,delete r.__depthDisposeCallback,t.removeEventListener("dispose",e)};t.addEventListener("dispose",e),r.__depthDisposeCallback=e}r.__boundDepthTexture=t}if(e.depthTexture&&!r.__autoAllocateDepthBuffer){if(s)throw new Error("target.depthTexture not supported in Cube render targets");!function(e,r){if(r&&r.isWebGLCubeRenderTarget)throw new Error("Depth Texture with cube render targets is not supported");if(n.bindFramebuffer(t.FRAMEBUFFER,e),!r.depthTexture||!r.depthTexture.isDepthTexture)throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");i.get(r.depthTexture).__webglTexture&&r.depthTexture.image.width===r.width&&r.depthTexture.image.height===r.height||(r.depthTexture.image.width=r.width,r.depthTexture.image.height=r.height,r.depthTexture.needsUpdate=!0),H(r.depthTexture,0);const s=i.get(r.depthTexture).__webglTexture,a=tt(r);if(r.depthTexture.format===k)et(r)?o.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,t.DEPTH_ATTACHMENT,t.TEXTURE_2D,s,0,a):t.framebufferTexture2D(t.FRAMEBUFFER,t.DEPTH_ATTACHMENT,t.TEXTURE_2D,s,0);else{if(r.depthTexture.format!==V)throw new Error("Unknown depthTexture format");et(r)?o.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.TEXTURE_2D,s,0,a):t.framebufferTexture2D(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.TEXTURE_2D,s,0)}}(r.__webglFramebuffer,e)}else if(s){r.__webglDepthbuffer=[];for(let i=0;i<6;i++)if(n.bindFramebuffer(t.FRAMEBUFFER,r.__webglFramebuffer[i]),void 0===r.__webglDepthbuffer[i])r.__webglDepthbuffer[i]=t.createRenderbuffer(),J(r.__webglDepthbuffer[i],e,!1);else{const n=e.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,s=r.__webglDepthbuffer[i];t.bindRenderbuffer(t.RENDERBUFFER,s),t.framebufferRenderbuffer(t.FRAMEBUFFER,n,t.RENDERBUFFER,s)}}else if(n.bindFramebuffer(t.FRAMEBUFFER,r.__webglFramebuffer),void 0===r.__webglDepthbuffer)r.__webglDepthbuffer=t.createRenderbuffer(),J(r.__webglDepthbuffer,e,!1);else{const n=e.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,i=r.__webglDepthbuffer;t.bindRenderbuffer(t.RENDERBUFFER,i),t.framebufferRenderbuffer(t.FRAMEBUFFER,n,t.RENDERBUFFER,i)}n.bindFramebuffer(t.FRAMEBUFFER,null)}const $=[],Q=[];function tt(t){return Math.min(r.maxSamples,t.samples)}function et(t){const n=i.get(t);return t.samples>0&&!0===e.has("WEBGL_multisampled_render_to_texture")&&!1!==n.__useRenderToTexture}function nt(t,e){const n=t.colorSpace,i=t.format,r=t.type;return!0===t.isCompressedTexture||!0===t.isVideoTexture||n!==Dt&&n!==Lt&&(_e.getTransfer(n)===Bt?i===F&&r===b||console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):console.error("THREE.WebGLTextures: Unsupported texture color space:",n)),e}function it(t){return"undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement?(c.width=t.naturalWidth||t.width,c.height=t.naturalHeight||t.height):"undefined"!=typeof VideoFrame&&t instanceof VideoFrame?(c.width=t.displayWidth,c.height=t.displayHeight):(c.width=t.width,c.height=t.height),c}this.allocateTextureUnit=function(){const t=z;return t>=r.maxTextures&&console.warn("THREE.WebGLTextures: Trying to use "+t+" texture units while this GPU supports only "+r.maxTextures),z+=1,t},this.resetTextureUnits=function(){z=0},this.setTexture2D=H,this.setTexture2DArray=function(e,r){const s=i.get(e);e.version>0&&s.__version!==e.version?Y(s,e,r):n.bindTexture(t.TEXTURE_2D_ARRAY,s.__webglTexture,t.TEXTURE0+r)},this.setTexture3D=function(e,r){const s=i.get(e);e.version>0&&s.__version!==e.version?Y(s,e,r):n.bindTexture(t.TEXTURE_3D,s.__webglTexture,t.TEXTURE0+r)},this.setTextureCube=function(e,a){const o=i.get(e);e.version>0&&o.__version!==e.version?function(e,a,o){if(6!==a.image.length)return;const l=q(e,a),c=a.source;n.bindTexture(t.TEXTURE_CUBE_MAP,e.__webglTexture,t.TEXTURE0+o);const h=i.get(c);if(c.version!==h.__version||!0===l){n.activeTexture(t.TEXTURE0+o);const e=_e.getPrimaries(_e.workingColorSpace),i=a.colorSpace===Lt?null:_e.getPrimaries(a.colorSpace),u=a.colorSpace===Lt||e===i?t.NONE:t.BROWSER_DEFAULT_WEBGL;t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,a.flipY),t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,a.premultiplyAlpha),t.pixelStorei(t.UNPACK_ALIGNMENT,a.unpackAlignment),t.pixelStorei(t.UNPACK_COLORSPACE_CONVERSION_WEBGL,u);const d=a.isCompressedTexture||a.image[0].isCompressedTexture,p=a.image[0]&&a.image[0].isDataTexture,m=[];for(let t=0;t<6;t++)m[t]=d||p?p?a.image[t].image:a.image[t]:T(a.image[t],!0,r.maxCubemapSize),m[t]=nt(a,m[t]);const f=m[0],g=s.convert(a.format,a.colorSpace),v=s.convert(a.type),_=I(a.internalFormat,g,v,a.colorSpace),y=!0!==a.isVideoTexture,x=void 0===h.__version||!0===l,M=c.dataReady;let S,b=D(a,f);if(j(t.TEXTURE_CUBE_MAP,a),d){y&&x&&n.texStorage2D(t.TEXTURE_CUBE_MAP,b,_,f.width,f.height);for(let e=0;e<6;e++){S=m[e].mipmaps;for(let i=0;i0&&b++;const e=it(m[0]);n.texStorage2D(t.TEXTURE_CUBE_MAP,b,_,e.width,e.height)}for(let e=0;e<6;e++)if(p){y?M&&n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,0,0,m[e].width,m[e].height,g,v,m[e].data):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,_,m[e].width,m[e].height,0,g,v,m[e].data);for(let i=0;i1;if(u||(void 0===l.__webglTexture&&(l.__webglTexture=t.createTexture()),l.__version=r.version,a.memory.textures++),h){o.__webglFramebuffer=[];for(let e=0;e<6;e++)if(r.mipmaps&&r.mipmaps.length>0){o.__webglFramebuffer[e]=[];for(let n=0;n0){o.__webglFramebuffer=[];for(let e=0;e0&&!1===et(e)){o.__webglMultisampledFramebuffer=t.createFramebuffer(),o.__webglColorRenderbuffer=[],n.bindFramebuffer(t.FRAMEBUFFER,o.__webglMultisampledFramebuffer);for(let n=0;n0)for(let i=0;i0)for(let n=0;n0)if(!1===et(e)){const r=e.textures,s=e.width,a=e.height;let o=t.COLOR_BUFFER_BIT;const c=e.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,h=i.get(e),u=r.length>1;if(u)for(let e=0;eo+c?(l.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:t.handedness,target:this})):!l.inputState.pinching&&a<=o-c&&(l.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:t.handedness,target:this}))}else null!==o&&t.gripSpace&&(r=e.getPose(t.gripSpace,n),null!==r&&(o.matrix.fromArray(r.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,r.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(r.linearVelocity)):o.hasLinearVelocity=!1,r.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(r.angularVelocity)):o.hasAngularVelocity=!1));null!==a&&(i=e.getPose(t.targetRaySpace,n),null===i&&null!==r&&(i=r),null!==i&&(a.matrix.fromArray(i.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),a.matrixWorldNeedsUpdate=!0,i.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(i.linearVelocity)):a.hasLinearVelocity=!1,i.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(i.angularVelocity)):a.hasAngularVelocity=!1,this.dispatchEvent(Ha)))}return null!==a&&(a.visible=null!==i),null!==o&&(o.visible=null!==r),null!==l&&(l.visible=null!==s),this}_getHandJoint(t,e){if(void 0===t.joints[e.jointName]){const n=new Va;n.matrixAutoUpdate=!1,n.visible=!1,t.joints[e.jointName]=n,t.add(n)}return t.joints[e.jointName]}}class Wa{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(t,e,n){if(null===this.texture){const i=new Ae;t.properties.get(i).__webglTexture=e.texture,e.depthNear==n.depthNear&&e.depthFar==n.depthFar||(this.depthNear=e.depthNear,this.depthFar=e.depthFar),this.texture=i}}getMesh(t){if(null!==this.texture&&null===this.mesh){const e=t.cameras[0].viewport,n=new Xi({vertexShader:"\nvoid main() {\n\n\tgl_Position = vec4( position, 1.0 );\n\n}",fragmentShader:"\nuniform sampler2DArray depthColor;\nuniform float depthWidth;\nuniform float depthHeight;\n\nvoid main() {\n\n\tvec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight );\n\n\tif ( coord.x >= 1.0 ) {\n\n\t\tgl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r;\n\n\t} else {\n\n\t\tgl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r;\n\n\t}\n\n}",uniforms:{depthColor:{value:this.texture},depthWidth:{value:e.z},depthHeight:{value:e.w}}});this.mesh=new Bi(new hr(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class Xa extends jt{constructor(t,e){super();const n=this;let i=null,r=1,s=null,a="local-floor",o=1,l=null,c=null,h=null,u=null,d=null,p=null;const m=new Wa,f=e.getContextAttributes();let g=null,v=null;const _=[],y=[],x=new re;let M=null;const S=new Ji;S.layers.enable(1),S.viewport=new Ce;const w=new Ji;w.layers.enable(2),w.viewport=new Ce;const T=[S,w],E=new ka;E.layers.enable(1),E.layers.enable(2);let A=null,R=null;function P(t){const e=y.indexOf(t.inputSource);if(-1===e)return;const n=_[e];void 0!==n&&(n.update(t.inputSource,t.frame,l||s),n.dispatchEvent({type:t.type,data:t.inputSource}))}function I(){i.removeEventListener("select",P),i.removeEventListener("selectstart",P),i.removeEventListener("selectend",P),i.removeEventListener("squeeze",P),i.removeEventListener("squeezestart",P),i.removeEventListener("squeezeend",P),i.removeEventListener("end",I),i.removeEventListener("inputsourceschange",L);for(let t=0;t<_.length;t++){const e=y[t];null!==e&&(y[t]=null,_[t].disconnect(e))}A=null,R=null,m.reset(),t.setRenderTarget(g),d=null,u=null,h=null,i=null,v=null,z.stop(),n.isPresenting=!1,t.setPixelRatio(M),t.setSize(x.width,x.height,!1),n.dispatchEvent({type:"sessionend"})}function L(t){for(let e=0;e=0&&(y[i]=null,_[i].disconnect(n))}for(let e=0;e=y.length){y.push(n),i=t;break}if(null===y[t]){y[t]=n,i=t;break}}if(-1===i)break}const r=_[i];r&&r.connect(n)}}this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(t){let e=_[t];return void 0===e&&(e=new Ga,_[t]=e),e.getTargetRaySpace()},this.getControllerGrip=function(t){let e=_[t];return void 0===e&&(e=new Ga,_[t]=e),e.getGripSpace()},this.getHand=function(t){let e=_[t];return void 0===e&&(e=new Ga,_[t]=e),e.getHandSpace()},this.setFramebufferScaleFactor=function(t){r=t,!0===n.isPresenting&&console.warn("THREE.WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(t){a=t,!0===n.isPresenting&&console.warn("THREE.WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return l||s},this.setReferenceSpace=function(t){l=t},this.getBaseLayer=function(){return null!==u?u:d},this.getBinding=function(){return h},this.getFrame=function(){return p},this.getSession=function(){return i},this.setSession=async function(c){if(i=c,null!==i){if(g=t.getRenderTarget(),i.addEventListener("select",P),i.addEventListener("selectstart",P),i.addEventListener("selectend",P),i.addEventListener("squeeze",P),i.addEventListener("squeezestart",P),i.addEventListener("squeezeend",P),i.addEventListener("end",I),i.addEventListener("inputsourceschange",L),!0!==f.xrCompatible&&await e.makeXRCompatible(),M=t.getPixelRatio(),t.getSize(x),void 0===i.renderState.layers){const n={antialias:f.antialias,alpha:!0,depth:f.depth,stencil:f.stencil,framebufferScaleFactor:r};d=new XRWebGLLayer(i,e,n),i.updateRenderState({baseLayer:d}),t.setPixelRatio(1),t.setSize(d.framebufferWidth,d.framebufferHeight,!1),v=new Pe(d.framebufferWidth,d.framebufferHeight,{format:F,type:b,colorSpace:t.outputColorSpace,stencilBuffer:f.stencil})}else{let n=null,s=null,a=null;f.depth&&(a=f.stencil?e.DEPTH24_STENCIL8:e.DEPTH_COMPONENT24,n=f.stencil?V:k,s=f.stencil?U:C);const o={colorFormat:e.RGBA8,depthFormat:a,scaleFactor:r};h=new XRWebGLBinding(i,e),u=h.createProjectionLayer(o),i.updateRenderState({layers:[u]}),t.setPixelRatio(1),t.setSize(u.textureWidth,u.textureHeight,!1),v=new Pe(u.textureWidth,u.textureHeight,{format:F,type:b,depthTexture:new jr(u.textureWidth,u.textureHeight,s,void 0,void 0,void 0,void 0,void 0,void 0,n),stencilBuffer:f.stencil,colorSpace:t.outputColorSpace,samples:f.antialias?4:0,resolveDepthBuffer:!1===u.ignoreDepthValues})}v.isXRRenderTarget=!0,this.setFoveation(o),l=null,s=await i.requestReferenceSpace(a),z.setContext(i),z.start(),n.isPresenting=!0,n.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(null!==i)return i.environmentBlendMode},this.getDepthTexture=function(){return m.getDepthTexture()};const D=new De,N=new De;function O(t,e){null===e?t.matrixWorld.copy(t.matrix):t.matrixWorld.multiplyMatrices(e.matrixWorld,t.matrix),t.matrixWorldInverse.copy(t.matrixWorld).invert()}this.updateCamera=function(t){if(null===i)return;let e=t.near,n=t.far;null!==m.texture&&(m.depthNear>0&&(e=m.depthNear),m.depthFar>0&&(n=m.depthFar)),E.near=w.near=S.near=e,E.far=w.far=S.far=n,A===E.near&&R===E.far||(i.updateRenderState({depthNear:E.near,depthFar:E.far}),A=E.near,R=E.far);const r=t.parent,s=E.cameras;O(E,r);for(let t=0;t0&&(t.alphaTest.value=i.alphaTest);const r=e.get(i),s=r.envMap,a=r.envMapRotation;s&&(t.envMap.value=s,ja.copy(a),ja.x*=-1,ja.y*=-1,ja.z*=-1,s.isCubeTexture&&!1===s.isRenderTargetTexture&&(ja.y*=-1,ja.z*=-1),t.envMapRotation.value.setFromMatrix4(qa.makeRotationFromEuler(ja)),t.flipEnvMap.value=s.isCubeTexture&&!1===s.isRenderTargetTexture?-1:1,t.reflectivity.value=i.reflectivity,t.ior.value=i.ior,t.refractionRatio.value=i.refractionRatio),i.lightMap&&(t.lightMap.value=i.lightMap,t.lightMapIntensity.value=i.lightMapIntensity,n(i.lightMap,t.lightMapTransform)),i.aoMap&&(t.aoMap.value=i.aoMap,t.aoMapIntensity.value=i.aoMapIntensity,n(i.aoMap,t.aoMapTransform))}return{refreshFogUniforms:function(e,n){n.color.getRGB(e.fogColor.value,Gi(t)),n.isFog?(e.fogNear.value=n.near,e.fogFar.value=n.far):n.isFogExp2&&(e.fogDensity.value=n.density)},refreshMaterialUniforms:function(t,r,s,a,o){r.isMeshBasicMaterial||r.isMeshLambertMaterial?i(t,r):r.isMeshToonMaterial?(i(t,r),function(t,e){e.gradientMap&&(t.gradientMap.value=e.gradientMap)}(t,r)):r.isMeshPhongMaterial?(i(t,r),function(t,e){t.specular.value.copy(e.specular),t.shininess.value=Math.max(e.shininess,1e-4)}(t,r)):r.isMeshStandardMaterial?(i(t,r),function(t,e){t.metalness.value=e.metalness,e.metalnessMap&&(t.metalnessMap.value=e.metalnessMap,n(e.metalnessMap,t.metalnessMapTransform)),t.roughness.value=e.roughness,e.roughnessMap&&(t.roughnessMap.value=e.roughnessMap,n(e.roughnessMap,t.roughnessMapTransform)),e.envMap&&(t.envMapIntensity.value=e.envMapIntensity)}(t,r),r.isMeshPhysicalMaterial&&function(t,e,i){t.ior.value=e.ior,e.sheen>0&&(t.sheenColor.value.copy(e.sheenColor).multiplyScalar(e.sheen),t.sheenRoughness.value=e.sheenRoughness,e.sheenColorMap&&(t.sheenColorMap.value=e.sheenColorMap,n(e.sheenColorMap,t.sheenColorMapTransform)),e.sheenRoughnessMap&&(t.sheenRoughnessMap.value=e.sheenRoughnessMap,n(e.sheenRoughnessMap,t.sheenRoughnessMapTransform))),e.clearcoat>0&&(t.clearcoat.value=e.clearcoat,t.clearcoatRoughness.value=e.clearcoatRoughness,e.clearcoatMap&&(t.clearcoatMap.value=e.clearcoatMap,n(e.clearcoatMap,t.clearcoatMapTransform)),e.clearcoatRoughnessMap&&(t.clearcoatRoughnessMap.value=e.clearcoatRoughnessMap,n(e.clearcoatRoughnessMap,t.clearcoatRoughnessMapTransform)),e.clearcoatNormalMap&&(t.clearcoatNormalMap.value=e.clearcoatNormalMap,n(e.clearcoatNormalMap,t.clearcoatNormalMapTransform),t.clearcoatNormalScale.value.copy(e.clearcoatNormalScale),1===e.side&&t.clearcoatNormalScale.value.negate())),e.dispersion>0&&(t.dispersion.value=e.dispersion),e.iridescence>0&&(t.iridescence.value=e.iridescence,t.iridescenceIOR.value=e.iridescenceIOR,t.iridescenceThicknessMinimum.value=e.iridescenceThicknessRange[0],t.iridescenceThicknessMaximum.value=e.iridescenceThicknessRange[1],e.iridescenceMap&&(t.iridescenceMap.value=e.iridescenceMap,n(e.iridescenceMap,t.iridescenceMapTransform)),e.iridescenceThicknessMap&&(t.iridescenceThicknessMap.value=e.iridescenceThicknessMap,n(e.iridescenceThicknessMap,t.iridescenceThicknessMapTransform))),e.transmission>0&&(t.transmission.value=e.transmission,t.transmissionSamplerMap.value=i.texture,t.transmissionSamplerSize.value.set(i.width,i.height),e.transmissionMap&&(t.transmissionMap.value=e.transmissionMap,n(e.transmissionMap,t.transmissionMapTransform)),t.thickness.value=e.thickness,e.thicknessMap&&(t.thicknessMap.value=e.thicknessMap,n(e.thicknessMap,t.thicknessMapTransform)),t.attenuationDistance.value=e.attenuationDistance,t.attenuationColor.value.copy(e.attenuationColor)),e.anisotropy>0&&(t.anisotropyVector.value.set(e.anisotropy*Math.cos(e.anisotropyRotation),e.anisotropy*Math.sin(e.anisotropyRotation)),e.anisotropyMap&&(t.anisotropyMap.value=e.anisotropyMap,n(e.anisotropyMap,t.anisotropyMapTransform))),t.specularIntensity.value=e.specularIntensity,t.specularColor.value.copy(e.specularColor),e.specularColorMap&&(t.specularColorMap.value=e.specularColorMap,n(e.specularColorMap,t.specularColorMapTransform)),e.specularIntensityMap&&(t.specularIntensityMap.value=e.specularIntensityMap,n(e.specularIntensityMap,t.specularIntensityMapTransform))}(t,r,o)):r.isMeshMatcapMaterial?(i(t,r),function(t,e){e.matcap&&(t.matcap.value=e.matcap)}(t,r)):r.isMeshDepthMaterial?i(t,r):r.isMeshDistanceMaterial?(i(t,r),function(t,n){const i=e.get(n).light;t.referencePosition.value.setFromMatrixPosition(i.matrixWorld),t.nearDistance.value=i.shadow.camera.near,t.farDistance.value=i.shadow.camera.far}(t,r)):r.isMeshNormalMaterial?i(t,r):r.isLineBasicMaterial?(function(t,e){t.diffuse.value.copy(e.color),t.opacity.value=e.opacity,e.map&&(t.map.value=e.map,n(e.map,t.mapTransform))}(t,r),r.isLineDashedMaterial&&function(t,e){t.dashSize.value=e.dashSize,t.totalSize.value=e.dashSize+e.gapSize,t.scale.value=e.scale}(t,r)):r.isPointsMaterial?function(t,e,i,r){t.diffuse.value.copy(e.color),t.opacity.value=e.opacity,t.size.value=e.size*i,t.scale.value=.5*r,e.map&&(t.map.value=e.map,n(e.map,t.uvTransform)),e.alphaMap&&(t.alphaMap.value=e.alphaMap,n(e.alphaMap,t.alphaMapTransform)),e.alphaTest>0&&(t.alphaTest.value=e.alphaTest)}(t,r,s,a):r.isSpriteMaterial?function(t,e){t.diffuse.value.copy(e.color),t.opacity.value=e.opacity,t.rotation.value=e.rotation,e.map&&(t.map.value=e.map,n(e.map,t.mapTransform)),e.alphaMap&&(t.alphaMap.value=e.alphaMap,n(e.alphaMap,t.alphaMapTransform)),e.alphaTest>0&&(t.alphaTest.value=e.alphaTest)}(t,r):r.isShadowMaterial?(t.color.value.copy(r.color),t.opacity.value=r.opacity):r.isShaderMaterial&&(r.uniformsNeedUpdate=!1)}}}function Za(t,e,n,i){let r={},s={},a=[];const o=t.getParameter(t.MAX_UNIFORM_BUFFER_BINDINGS);function l(t,e,n,i){const r=t.value,s=e+"_"+n;if(void 0===i[s])return i[s]="number"==typeof r||"boolean"==typeof r?r:r.clone(),!0;{const t=i[s];if("number"==typeof r||"boolean"==typeof r){if(t!==r)return i[s]=r,!0}else if(!1===t.equals(r))return t.copy(r),!0}return!1}function c(t){const e={boundary:0,storage:0};return"number"==typeof t||"boolean"==typeof t?(e.boundary=4,e.storage=4):t.isVector2?(e.boundary=8,e.storage=8):t.isVector3||t.isColor?(e.boundary=16,e.storage=12):t.isVector4?(e.boundary=16,e.storage=16):t.isMatrix3?(e.boundary=48,e.storage=48):t.isMatrix4?(e.boundary=64,e.storage=64):t.isTexture?console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."):console.warn("THREE.WebGLRenderer: Unsupported uniform value type.",t),e}function h(e){const n=e.target;n.removeEventListener("dispose",h);const i=a.indexOf(n.__bindingPointIndex);a.splice(i,1),t.deleteBuffer(r[n.id]),delete r[n.id],delete s[n.id]}return{bind:function(t,e){const n=e.program;i.uniformBlockBinding(t,n)},update:function(n,u){let d=r[n.id];void 0===d&&(function(t){const e=t.uniforms;let n=0;for(let t=0,i=e.length;t0&&(n+=16-i),t.__size=n,t.__cache={}}(n),d=function(e){const n=function(){for(let t=0;t0&&(e.object.backgroundBlurriness=this.backgroundBlurriness),1!==this.backgroundIntensity&&(e.object.backgroundIntensity=this.backgroundIntensity),e.object.backgroundRotation=this.backgroundRotation.toArray(),1!==this.environmentIntensity&&(e.object.environmentIntensity=this.environmentIntensity),e.object.environmentRotation=this.environmentRotation.toArray(),e}}class Qa{constructor(t,e){this.isInterleavedBuffer=!0,this.array=t,this.stride=e,this.count=void 0!==t?t.length/e:0,this.usage=Ht,this.updateRanges=[],this.version=0,this.uuid=Kt()}onUploadCallback(){}set needsUpdate(t){!0===t&&this.version++}setUsage(t){return this.usage=t,this}addUpdateRange(t,e){this.updateRanges.push({start:t,count:e})}clearUpdateRanges(){this.updateRanges.length=0}copy(t){return this.array=new t.array.constructor(t.array),this.count=t.count,this.stride=t.stride,this.usage=t.usage,this}copyAt(t,e,n){t*=this.stride,n*=e.stride;for(let i=0,r=this.stride;it.far||e.push({distance:o,point:ro.clone(),uv:$n.getInterpolation(ro,ho,uo,po,mo,fo,go,new re),face:null,object:this})}copy(t,e){return super.copy(t,e),void 0!==t.center&&this.center.copy(t.center),this.material=t.material,this}}function _o(t,e,n,i,r,s){oo.subVectors(t,n).addScalar(.5).multiply(i),void 0!==r?(lo.x=s*oo.x-r*oo.y,lo.y=r*oo.x+s*oo.y):lo.copy(oo),t.copy(e),t.x+=lo.x,t.y+=lo.y,t.applyMatrix4(co)}const yo=new De,xo=new De;class Mo extends Bn{constructor(){super(),this._currentLevel=0,this.type="LOD",Object.defineProperties(this,{levels:{enumerable:!0,value:[]},isLOD:{value:!0}}),this.autoUpdate=!0}copy(t){super.copy(t,!1);const e=t.levels;for(let t=0,n=e.length;t0){let n,i;for(n=1,i=e.length;n0){yo.setFromMatrixPosition(this.matrixWorld);const n=t.ray.origin.distanceTo(yo);this.getObjectForDistance(n).raycast(t,e)}}update(t){const e=this.levels;if(e.length>1){yo.setFromMatrixPosition(t.matrixWorld),xo.setFromMatrixPosition(this.matrixWorld);const n=yo.distanceTo(xo)/t.zoom;let i,r;for(e[0].object.visible=!0,i=1,r=e.length;i=t))break;e[i-1].object.visible=!1,e[i].object.visible=!0}for(this._currentLevel=i-1;i=i.length&&i.push({start:-1,count:-1,z:-1,index:-1});const s=i[this.index];r.push(s),this.index++,s.start=t.start,s.count=t.count,s.z=e,s.index=n}reset(){this.list.length=0,this.index=0}}const Zo=new un,Jo=new un,Ko=new un,$o=new ii(1,1,1),Qo=new un,tl=new or,el=new Fe,nl=new en,il=new De,rl=new De,sl=new De,al=new Yo,ol=new Bi,ll=[];function cl(t,e,n=0){const i=e.itemSize;if(t.isInterleavedBufferAttribute||t.array.constructor!==e.array.constructor){const r=t.count;for(let s=0;s65535?new Uint32Array(i):new Uint16Array(i);e.setIndex(new fi(t,1))}this._geometryInitialized=!0}}_validateGeometry(t){const e=this.geometry;if(Boolean(t.getIndex())!==Boolean(e.getIndex()))throw new Error('BatchedMesh: All geometries must consistently have "index".');for(const n in e.attributes){if(!t.hasAttribute(n))throw new Error(`BatchedMesh: Added geometry missing "${n}". All geometries must have consistent attributes.`);const i=t.getAttribute(n),r=e.getAttribute(n);if(i.itemSize!==r.itemSize||i.normalized!==r.normalized)throw new Error("BatchedMesh: All attributes must have a consistent itemSize and normalized value.")}}setCustomSort(t){return this.customSort=t,this}computeBoundingBox(){null===this.boundingBox&&(this.boundingBox=new Fe);const t=this.boundingBox,e=this._drawInfo;t.makeEmpty();for(let n=0,i=e.length;n=this.maxInstanceCount&&0===this._availableInstanceIds.length)throw new Error("BatchedMesh: Maximum item count reached.");const e={visible:!0,active:!0,geometryIndex:t};let n=null;this._availableInstanceIds.length>0?(n=this._availableInstanceIds.pop(),this._drawInfo[n]=e):(n=this._drawInfo.length,this._drawInfo.push(e));const i=this._matricesTexture,r=i.image.data;Ko.toArray(r,16*n),i.needsUpdate=!0;const s=this._colorsTexture;return s&&($o.toArray(s.image.data,4*n),s.needsUpdate=!0),n}addGeometry(t,e=-1,n=-1){if(this._initializeGeometry(t),this._validateGeometry(t),this._drawInfo.length>=this._maxInstanceCount)throw new Error("BatchedMesh: Maximum item count reached.");const i={vertexStart:-1,vertexCount:-1,indexStart:-1,indexCount:-1};let r=null;const s=this._reservedRanges,a=this._drawRanges,o=this._bounds;0!==this._geometryCount&&(r=s[s.length-1]),i.vertexCount=-1===e?t.getAttribute("position").count:e,i.vertexStart=null===r?0:r.vertexStart+r.vertexCount;const l=t.getIndex(),c=null!==l;if(c&&(i.indexCount=-1===n?l.count:n,i.indexStart=null===r?0:r.indexStart+r.indexCount),-1!==i.indexStart&&i.indexStart+i.indexCount>this._maxIndexCount||i.vertexStart+i.vertexCount>this._maxVertexCount)throw new Error("BatchedMesh: Reserved space request exceeds the maximum buffer size.");const h=this._geometryCount;return this._geometryCount++,s.push(i),a.push({start:c?i.indexStart:i.vertexStart,count:-1}),o.push({boxInitialized:!1,box:new Fe,sphereInitialized:!1,sphere:new en}),this.setGeometryAt(h,t),h}setGeometryAt(t,e){if(t>=this._geometryCount)throw new Error("BatchedMesh: Maximum geometry count reached.");this._validateGeometry(e);const n=this.geometry,i=null!==n.getIndex(),r=n.getIndex(),s=e.getIndex(),a=this._reservedRanges[t];if(i&&s.count>a.indexCount||e.attributes.position.count>a.vertexCount)throw new Error("BatchedMesh: Reserved space not large enough for provided geometry.");const o=a.vertexStart,l=a.vertexCount;for(const t in n.attributes){const i=e.getAttribute(t),r=n.getAttribute(t);cl(i,r,o);const s=i.itemSize;for(let t=i.count,e=l;t=e.length||!1===e[t].active||(e[t].active=!1,this._availableInstanceIds.push(t),this._visibilityChanged=!0),this}getBoundingBoxAt(t,e){if(t>=this._geometryCount)return null;const n=this._bounds[t],i=n.box,r=this.geometry;if(!1===n.boxInitialized){i.makeEmpty();const e=r.index,s=r.attributes.position,a=this._drawRanges[t];for(let t=a.start,n=a.start+a.count;t=this._geometryCount)return null;const n=this._bounds[t],i=n.sphere,r=this.geometry;if(!1===n.sphereInitialized){i.makeEmpty(),this.getBoundingBoxAt(t,el),el.getCenter(i.center);const e=r.index,s=r.attributes.position,a=this._drawRanges[t];let o=0;for(let t=a.start,n=a.start+a.count;t=n.length||!1===n[t].active||(e.toArray(r,16*t),i.needsUpdate=!0),this}getMatrixAt(t,e){const n=this._drawInfo,i=this._matricesTexture.image.data;return t>=n.length||!1===n[t].active?null:e.fromArray(i,16*t)}setColorAt(t,e){null===this._colorsTexture&&this._initColorsTexture();const n=this._colorsTexture,i=this._colorsTexture.image.data,r=this._drawInfo;return t>=r.length||!1===r[t].active||(e.toArray(i,4*t),n.needsUpdate=!0),this}getColorAt(t,e){const n=this._colorsTexture.image.data,i=this._drawInfo;return t>=i.length||!1===i[t].active?null:e.fromArray(n,4*t)}setVisibleAt(t,e){const n=this._drawInfo;return t>=n.length||!1===n[t].active||n[t].visible===e||(n[t].visible=e,this._visibilityChanged=!0),this}getVisibleAt(t){const e=this._drawInfo;return!(t>=e.length||!1===e[t].active)&&e[t].visible}setGeometryIdAt(t,e){const n=this._drawInfo;return t>=n.length||!1===n[t].active||e<0||e>=this._geometryCount?null:(n[t].geometryIndex=e,this)}getGeometryIdAt(t){const e=this._drawInfo;return t>=e.length||!1===e[t].active?-1:e[t].geometryIndex}getGeometryRangeAt(t,e={}){if(t<0||t>=this._geometryCount)return null;const n=this._drawRanges[t];return e.start=n.start,e.count=n.count,e}raycast(t,e){const n=this._drawInfo,i=this._drawRanges,r=this.matrixWorld,s=this.geometry;ol.material=this.material,ol.geometry.index=s.index,ol.geometry.attributes=s.attributes,null===ol.geometry.boundingBox&&(ol.geometry.boundingBox=new Fe),null===ol.geometry.boundingSphere&&(ol.geometry.boundingSphere=new en);for(let s=0,a=n.length;s({...t}))),this._reservedRanges=t._reservedRanges.map((t=>({...t}))),this._drawInfo=t._drawInfo.map((t=>({...t}))),this._bounds=t._bounds.map((t=>({boxInitialized:t.boxInitialized,box:t.box.clone(),sphereInitialized:t.sphereInitialized,sphere:t.sphere.clone()}))),this._maxInstanceCount=t._maxInstanceCount,this._maxVertexCount=t._maxVertexCount,this._maxIndexCount=t._maxIndexCount,this._geometryInitialized=t._geometryInitialized,this._geometryCount=t._geometryCount,this._multiDrawCounts=t._multiDrawCounts.slice(),this._multiDrawStarts=t._multiDrawStarts.slice(),this._matricesTexture=t._matricesTexture.clone(),this._matricesTexture.image.data=this._matricesTexture.image.data.slice(),null!==this._colorsTexture&&(this._colorsTexture=t._colorsTexture.clone(),this._colorsTexture.image.data=this._colorsTexture.image.data.slice()),this}dispose(){return this.geometry.dispose(),this._matricesTexture.dispose(),this._matricesTexture=null,this._indirectTexture.dispose(),this._indirectTexture=null,null!==this._colorsTexture&&(this._colorsTexture.dispose(),this._colorsTexture=null),this}onBeforeRender(t,e,n,i,r){if(!this._visibilityChanged&&!this.perObjectFrustumCulled&&!this.sortObjects)return;const s=i.getIndex(),a=null===s?1:s.array.BYTES_PER_ELEMENT,o=this._drawInfo,l=this._multiDrawStarts,c=this._multiDrawCounts,h=this._drawRanges,u=this.perObjectFrustumCulled,d=this._indirectTexture,p=d.image.data;u&&(Qo.multiplyMatrices(n.projectionMatrix,n.matrixWorldInverse).multiply(this.matrixWorld),tl.setFromProjectionMatrix(Qo,t.coordinateSystem));let m=0;if(this.sortObjects){Jo.copy(this.matrixWorld).invert(),il.setFromMatrixPosition(n.matrixWorld).applyMatrix4(Jo),rl.set(0,0,-1).transformDirection(n.matrixWorld).transformDirection(Jo);for(let t=0,e=o.length;t0){const n=t[e[0]];if(void 0!==n){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let t=0,e=n.length;ti)return;vl.applyMatrix4(t.matrixWorld);const o=e.ray.origin.distanceTo(vl);return oe.far?void 0:{distance:o,point:_l.clone().applyMatrix4(t.matrixWorld),index:r,face:null,faceIndex:null,barycoord:null,object:t}}const Ml=new De,Sl=new De;class bl extends yl{constructor(t,e){super(t,e),this.isLineSegments=!0,this.type="LineSegments"}computeLineDistances(){const t=this.geometry;if(null===t.index){const e=t.attributes.position,n=[];for(let t=0,i=e.count;t0){const n=t[e[0]];if(void 0!==n){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let t=0,e=n.length;tr.far)return;s.push({distance:l,distanceToRay:Math.sqrt(o),point:n,index:e,face:null,faceIndex:null,barycoord:null,object:a})}}class Ll extends Ae{constructor(t,e,n,i,r,s,a,o,l,c,h,u){super(null,s,a,o,l,c,i,r,h,u),this.isCompressedTexture=!0,this.image={width:e,height:n},this.mipmaps=t,this.flipY=!1,this.generateMipmaps=!1}}class Ul{constructor(){this.type="Curve",this.arcLengthDivisions=200}getPoint(){return console.warn("THREE.Curve: .getPoint() not implemented."),null}getPointAt(t,e){const n=this.getUtoTmapping(t);return this.getPoint(n,e)}getPoints(t=5){const e=[];for(let n=0;n<=t;n++)e.push(this.getPoint(n/t));return e}getSpacedPoints(t=5){const e=[];for(let n=0;n<=t;n++)e.push(this.getPointAt(n/t));return e}getLength(){const t=this.getLengths();return t[t.length-1]}getLengths(t=this.arcLengthDivisions){if(this.cacheArcLengths&&this.cacheArcLengths.length===t+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;const e=[];let n,i=this.getPoint(0),r=0;e.push(0);for(let s=1;s<=t;s++)n=this.getPoint(s/t),r+=n.distanceTo(i),e.push(r),i=n;return this.cacheArcLengths=e,e}updateArcLengths(){this.needsUpdate=!0,this.getLengths()}getUtoTmapping(t,e){const n=this.getLengths();let i=0;const r=n.length;let s;s=e||t*n[r-1];let a,o=0,l=r-1;for(;o<=l;)if(i=Math.floor(o+(l-o)/2),a=n[i]-s,a<0)o=i+1;else{if(!(a>0)){l=i;break}l=i-1}if(i=l,n[i]===s)return i/(r-1);const c=n[i];return(i+(s-c)/(n[i+1]-c))/(r-1)}getTangent(t,e){const n=1e-4;let i=t-n,r=t+n;i<0&&(i=0),r>1&&(r=1);const s=this.getPoint(i),a=this.getPoint(r),o=e||(s.isVector2?new re:new De);return o.copy(a).sub(s).normalize(),o}getTangentAt(t,e){const n=this.getUtoTmapping(t);return this.getTangent(n,e)}computeFrenetFrames(t,e){const n=new De,i=[],r=[],s=[],a=new De,o=new un;for(let e=0;e<=t;e++){const n=e/t;i[e]=this.getTangentAt(n,new De)}r[0]=new De,s[0]=new De;let l=Number.MAX_VALUE;const c=Math.abs(i[0].x),h=Math.abs(i[0].y),u=Math.abs(i[0].z);c<=l&&(l=c,n.set(1,0,0)),h<=l&&(l=h,n.set(0,1,0)),u<=l&&n.set(0,0,1),a.crossVectors(i[0],n).normalize(),r[0].crossVectors(i[0],a),s[0].crossVectors(i[0],r[0]);for(let e=1;e<=t;e++){if(r[e]=r[e-1].clone(),s[e]=s[e-1].clone(),a.crossVectors(i[e-1],i[e]),a.length()>Number.EPSILON){a.normalize();const t=Math.acos($t(i[e-1].dot(i[e]),-1,1));r[e].applyMatrix4(o.makeRotationAxis(a,t))}s[e].crossVectors(i[e],r[e])}if(!0===e){let e=Math.acos($t(r[0].dot(r[t]),-1,1));e/=t,i[0].dot(a.crossVectors(r[0],r[t]))>0&&(e=-e);for(let n=1;n<=t;n++)r[n].applyMatrix4(o.makeRotationAxis(i[n],e*n)),s[n].crossVectors(i[n],r[n])}return{tangents:i,normals:r,binormals:s}}clone(){return(new this.constructor).copy(this)}copy(t){return this.arcLengthDivisions=t.arcLengthDivisions,this}toJSON(){const t={metadata:{version:4.6,type:"Curve",generator:"Curve.toJSON"}};return t.arcLengthDivisions=this.arcLengthDivisions,t.type=this.type,t}fromJSON(t){return this.arcLengthDivisions=t.arcLengthDivisions,this}}class Dl extends Ul{constructor(t=0,e=0,n=1,i=1,r=0,s=2*Math.PI,a=!1,o=0){super(),this.isEllipseCurve=!0,this.type="EllipseCurve",this.aX=t,this.aY=e,this.xRadius=n,this.yRadius=i,this.aStartAngle=r,this.aEndAngle=s,this.aClockwise=a,this.aRotation=o}getPoint(t,e=new re){const n=e,i=2*Math.PI;let r=this.aEndAngle-this.aStartAngle;const s=Math.abs(r)i;)r-=i;r0?0:(Math.floor(Math.abs(l)/r)+1)*r:0===c&&l===r-1&&(l=r-2,c=1),this.closed||l>0?a=i[(l-1)%r]:(Fl.subVectors(i[0],i[1]).add(i[0]),a=Fl);const h=i[l%r],u=i[(l+1)%r];if(this.closed||l+2i.length-2?i.length-1:s+1],h=i[s>i.length-3?i.length-1:s+2];return n.set(Hl(a,o.x,l.x,c.x,h.x),Hl(a,o.y,l.y,c.y,h.y)),n}copy(t){super.copy(t),this.points=[];for(let e=0,n=t.points.length;e=n){const t=i[r]-n,s=this.curves[r],a=s.getLength(),o=0===a?0:1-t/a;return s.getPointAt(o,e)}r++}return null}getLength(){const t=this.getCurveLengths();return t[t.length-1]}updateArcLengths(){this.needsUpdate=!0,this.cacheLengths=null,this.getCurveLengths()}getCurveLengths(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;const t=[];let e=0;for(let n=0,i=this.curves.length;n1&&!e[e.length-1].equals(e[0])&&e.push(e[0]),e}copy(t){super.copy(t),this.curves=[];for(let e=0,n=t.curves.length;e0){const t=l.getPoint(0);t.equals(this.currentPoint)||this.lineTo(t.x,t.y)}this.curves.push(l);const c=l.getPoint(1);return this.currentPoint.copy(c),this}copy(t){return super.copy(t),this.currentPoint.copy(t.currentPoint),this}toJSON(){const t=super.toJSON();return t.currentPoint=this.currentPoint.toArray(),t}fromJSON(t){return super.fromJSON(t),this.currentPoint.fromArray(t.currentPoint),this}}class ec extends Ei{constructor(t=[new re(0,-.5),new re(.5,0),new re(0,.5)],e=12,n=0,i=2*Math.PI){super(),this.type="LatheGeometry",this.parameters={points:t,segments:e,phiStart:n,phiLength:i},e=Math.floor(e),i=$t(i,0,2*Math.PI);const r=[],s=[],a=[],o=[],l=[],c=1/e,h=new De,u=new re,d=new De,p=new De,m=new De;let f=0,g=0;for(let e=0;e<=t.length-1;e++)switch(e){case 0:f=t[e+1].x-t[e].x,g=t[e+1].y-t[e].y,d.x=1*g,d.y=-f,d.z=0*g,m.copy(d),d.normalize(),o.push(d.x,d.y,d.z);break;case t.length-1:o.push(m.x,m.y,m.z);break;default:f=t[e+1].x-t[e].x,g=t[e+1].y-t[e].y,d.x=1*g,d.y=-f,d.z=0*g,p.copy(d),d.x+=m.x,d.y+=m.y,d.z+=m.z,d.normalize(),o.push(d.x,d.y,d.z),m.copy(p)}for(let r=0;r<=e;r++){const d=n+r*c*i,p=Math.sin(d),m=Math.cos(d);for(let n=0;n<=t.length-1;n++){h.x=t[n].x*p,h.y=t[n].y,h.z=t[n].x*m,s.push(h.x,h.y,h.z),u.x=r/e,u.y=n/(t.length-1),a.push(u.x,u.y);const i=o[3*n+0]*p,c=o[3*n+1],d=o[3*n+0]*m;l.push(i,c,d)}}for(let n=0;n0&&(c.push(r,s,o),_+=3),e>0&&(c.push(s,a,o),_+=3)}l.addGroup(g,_,0),g+=_}(),!1===s&&(t>0&&v(!0),e>0&&v(!1)),this.setIndex(c),this.setAttribute("position",new _i(h,3)),this.setAttribute("normal",new _i(u,3)),this.setAttribute("uv",new _i(d,2))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new rc(t.radiusTop,t.radiusBottom,t.height,t.radialSegments,t.heightSegments,t.openEnded,t.thetaStart,t.thetaLength)}}class sc extends rc{constructor(t=1,e=1,n=32,i=1,r=!1,s=0,a=2*Math.PI){super(0,t,e,n,i,r,s,a),this.type="ConeGeometry",this.parameters={radius:t,height:e,radialSegments:n,heightSegments:i,openEnded:r,thetaStart:s,thetaLength:a}}static fromJSON(t){return new sc(t.radius,t.height,t.radialSegments,t.heightSegments,t.openEnded,t.thetaStart,t.thetaLength)}}class ac extends Ei{constructor(t=[],e=[],n=1,i=0){super(),this.type="PolyhedronGeometry",this.parameters={vertices:t,indices:e,radius:n,detail:i};const r=[],s=[];function a(t,e,n,i){const r=i+1,s=[];for(let i=0;i<=r;i++){s[i]=[];const a=t.clone().lerp(n,i/r),o=e.clone().lerp(n,i/r),l=r-i;for(let t=0;t<=l;t++)s[i][t]=0===t&&i===r?a:a.clone().lerp(o,t/l)}for(let t=0;t.9&&a<.1&&(e<.2&&(s[t+0]+=1),n<.2&&(s[t+2]+=1),i<.2&&(s[t+4]+=1))}}()}(),this.setAttribute("position",new _i(r,3)),this.setAttribute("normal",new _i(r.slice(),3)),this.setAttribute("uv",new _i(s,2)),0===i?this.computeVertexNormals():this.normalizeNormals()}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new ac(t.vertices,t.indices,t.radius,t.details)}}class oc extends ac{constructor(t=1,e=0){const n=(1+Math.sqrt(5))/2,i=1/n;super([-1,-1,-1,-1,-1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,1,1,1,-1,1,1,1,0,-i,-n,0,-i,n,0,i,-n,0,i,n,-i,-n,0,-i,n,0,i,-n,0,i,n,0,-n,0,-i,n,0,-i,-n,0,i,n,0,i],[3,11,7,3,7,15,3,15,13,7,19,17,7,17,6,7,6,15,17,4,8,17,8,10,17,10,6,8,0,16,8,16,2,8,2,10,0,12,1,0,1,18,0,18,16,6,10,2,6,2,13,6,13,15,2,16,18,2,18,3,2,3,13,18,1,9,18,9,11,18,11,3,4,14,12,4,12,0,4,0,8,11,9,5,11,5,19,11,19,7,19,5,14,19,14,4,19,4,17,1,12,14,1,14,5,1,5,9],t,e),this.type="DodecahedronGeometry",this.parameters={radius:t,detail:e}}static fromJSON(t){return new oc(t.radius,t.detail)}}const lc=new De,cc=new De,hc=new De,uc=new $n;class dc extends Ei{constructor(t=null,e=1){if(super(),this.type="EdgesGeometry",this.parameters={geometry:t,thresholdAngle:e},null!==t){const n=4,i=Math.pow(10,n),r=Math.cos(Zt*e),s=t.getIndex(),a=t.getAttribute("position"),o=s?s.count:a.count,l=[0,0,0],c=["a","b","c"],h=new Array(3),u={},d=[];for(let t=0;t0)for(s=e;s=e;s-=i)a=Nc(s,t[s],t[s+1],a);return a&&Rc(a,a.next)&&(Oc(a),a=a.next),a}function fc(t,e){if(!t)return t;e||(e=t);let n,i=t;do{if(n=!1,i.steiner||!Rc(i,i.next)&&0!==Cc(i.prev,i,i.next))i=i.next;else{if(Oc(i),i=e=i.prev,i===i.next)break;n=!0}}while(n||i!==e);return e}function gc(t,e,n,i,r,s,a){if(!t)return;!a&&s&&function(t,e,n,i){let r=t;do{0===r.z&&(r.z=wc(r.x,r.y,e,n,i)),r.prevZ=r.prev,r.nextZ=r.next,r=r.next}while(r!==t);r.prevZ.nextZ=null,r.prevZ=null,function(t){let e,n,i,r,s,a,o,l,c=1;do{for(n=t,t=null,s=null,a=0;n;){for(a++,i=n,o=0,e=0;e0||l>0&&i;)0!==o&&(0===l||!i||n.z<=i.z)?(r=n,n=n.nextZ,o--):(r=i,i=i.nextZ,l--),s?s.nextZ=r:t=r,r.prevZ=s,s=r;n=i}s.nextZ=null,c*=2}while(a>1)}(r)}(t,i,r,s);let o,l,c=t;for(;t.prev!==t.next;)if(o=t.prev,l=t.next,s?_c(t,i,r,s):vc(t))e.push(o.i/n|0),e.push(t.i/n|0),e.push(l.i/n|0),Oc(t),t=l.next,c=l.next;else if((t=l)===c){a?1===a?gc(t=yc(fc(t),e,n),e,n,i,r,s,2):2===a&&xc(t,e,n,i,r,s):gc(fc(t),e,n,i,r,s,1);break}}function vc(t){const e=t.prev,n=t,i=t.next;if(Cc(e,n,i)>=0)return!1;const r=e.x,s=n.x,a=i.x,o=e.y,l=n.y,c=i.y,h=rs?r>a?r:a:s>a?s:a,p=o>l?o>c?o:c:l>c?l:c;let m=i.next;for(;m!==e;){if(m.x>=h&&m.x<=d&&m.y>=u&&m.y<=p&&Ec(r,o,s,l,a,c,m.x,m.y)&&Cc(m.prev,m,m.next)>=0)return!1;m=m.next}return!0}function _c(t,e,n,i){const r=t.prev,s=t,a=t.next;if(Cc(r,s,a)>=0)return!1;const o=r.x,l=s.x,c=a.x,h=r.y,u=s.y,d=a.y,p=ol?o>c?o:c:l>c?l:c,g=h>u?h>d?h:d:u>d?u:d,v=wc(p,m,e,n,i),_=wc(f,g,e,n,i);let y=t.prevZ,x=t.nextZ;for(;y&&y.z>=v&&x&&x.z<=_;){if(y.x>=p&&y.x<=f&&y.y>=m&&y.y<=g&&y!==r&&y!==a&&Ec(o,h,l,u,c,d,y.x,y.y)&&Cc(y.prev,y,y.next)>=0)return!1;if(y=y.prevZ,x.x>=p&&x.x<=f&&x.y>=m&&x.y<=g&&x!==r&&x!==a&&Ec(o,h,l,u,c,d,x.x,x.y)&&Cc(x.prev,x,x.next)>=0)return!1;x=x.nextZ}for(;y&&y.z>=v;){if(y.x>=p&&y.x<=f&&y.y>=m&&y.y<=g&&y!==r&&y!==a&&Ec(o,h,l,u,c,d,y.x,y.y)&&Cc(y.prev,y,y.next)>=0)return!1;y=y.prevZ}for(;x&&x.z<=_;){if(x.x>=p&&x.x<=f&&x.y>=m&&x.y<=g&&x!==r&&x!==a&&Ec(o,h,l,u,c,d,x.x,x.y)&&Cc(x.prev,x,x.next)>=0)return!1;x=x.nextZ}return!0}function yc(t,e,n){let i=t;do{const r=i.prev,s=i.next.next;!Rc(r,s)&&Pc(r,i,i.next,s)&&Uc(r,s)&&Uc(s,r)&&(e.push(r.i/n|0),e.push(i.i/n|0),e.push(s.i/n|0),Oc(i),Oc(i.next),i=t=s),i=i.next}while(i!==t);return fc(i)}function xc(t,e,n,i,r,s){let a=t;do{let t=a.next.next;for(;t!==a.prev;){if(a.i!==t.i&&Ac(a,t)){let o=Dc(a,t);return a=fc(a,a.next),o=fc(o,o.next),gc(a,e,n,i,r,s,0),void gc(o,e,n,i,r,s,0)}t=t.next}a=a.next}while(a!==t)}function Mc(t,e){return t.x-e.x}function Sc(t,e){const n=function(t,e){let n,i=e,r=-1/0;const s=t.x,a=t.y;do{if(a<=i.y&&a>=i.next.y&&i.next.y!==i.y){const t=i.x+(a-i.y)*(i.next.x-i.x)/(i.next.y-i.y);if(t<=s&&t>r&&(r=t,n=i.x=i.x&&i.x>=l&&s!==i.x&&Ec(an.x||i.x===n.x&&bc(n,i)))&&(n=i,u=h)),i=i.next}while(i!==o);return n}(t,e);if(!n)return e;const i=Dc(n,t);return fc(i,i.next),fc(n,n.next)}function bc(t,e){return Cc(t.prev,t,e.prev)<0&&Cc(e.next,t,t.next)<0}function wc(t,e,n,i,r){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-n)*r|0)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-i)*r|0)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function Tc(t){let e=t,n=t;do{(e.x=(t-a)*(s-o)&&(t-a)*(i-o)>=(n-a)*(e-o)&&(n-a)*(s-o)>=(r-a)*(i-o)}function Ac(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){let n=t;do{if(n.i!==t.i&&n.next.i!==t.i&&n.i!==e.i&&n.next.i!==e.i&&Pc(n,n.next,t,e))return!0;n=n.next}while(n!==t);return!1}(t,e)&&(Uc(t,e)&&Uc(e,t)&&function(t,e){let n=t,i=!1;const r=(t.x+e.x)/2,s=(t.y+e.y)/2;do{n.y>s!=n.next.y>s&&n.next.y!==n.y&&r<(n.next.x-n.x)*(s-n.y)/(n.next.y-n.y)+n.x&&(i=!i),n=n.next}while(n!==t);return i}(t,e)&&(Cc(t.prev,t,e.prev)||Cc(t,e.prev,e))||Rc(t,e)&&Cc(t.prev,t,t.next)>0&&Cc(e.prev,e,e.next)>0)}function Cc(t,e,n){return(e.y-t.y)*(n.x-e.x)-(e.x-t.x)*(n.y-e.y)}function Rc(t,e){return t.x===e.x&&t.y===e.y}function Pc(t,e,n,i){const r=Lc(Cc(t,e,n)),s=Lc(Cc(t,e,i)),a=Lc(Cc(n,i,t)),o=Lc(Cc(n,i,e));return r!==s&&a!==o||!(0!==r||!Ic(t,n,e))||!(0!==s||!Ic(t,i,e))||!(0!==a||!Ic(n,t,i))||!(0!==o||!Ic(n,e,i))}function Ic(t,e,n){return e.x<=Math.max(t.x,n.x)&&e.x>=Math.min(t.x,n.x)&&e.y<=Math.max(t.y,n.y)&&e.y>=Math.min(t.y,n.y)}function Lc(t){return t>0?1:t<0?-1:0}function Uc(t,e){return Cc(t.prev,t,t.next)<0?Cc(t,e,t.next)>=0&&Cc(t,t.prev,e)>=0:Cc(t,e,t.prev)<0||Cc(t,t.next,e)<0}function Dc(t,e){const n=new Fc(t.i,t.x,t.y),i=new Fc(e.i,e.x,e.y),r=t.next,s=e.prev;return t.next=e,e.prev=t,n.next=r,r.prev=n,i.next=n,n.prev=i,s.next=i,i.prev=s,i}function Nc(t,e,n,i){const r=new Fc(t,e,n);return i?(r.next=i.next,r.prev=i,i.next.prev=r,i.next=r):(r.prev=r,r.next=r),r}function Oc(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function Fc(t,e,n){this.i=t,this.x=e,this.y=n,this.prev=null,this.next=null,this.z=0,this.prevZ=null,this.nextZ=null,this.steiner=!1}class Bc{static area(t){const e=t.length;let n=0;for(let i=e-1,r=0;r80*n){o=c=t[0],l=h=t[1];for(let e=n;ec&&(c=u),d>h&&(h=d);p=Math.max(c-o,h-l),p=0!==p?32767/p:0}return gc(s,a,n,o,l,p,0),a}(n,i);for(let t=0;t2&&t[e-1].equals(t[0])&&t.pop()}function kc(t,e){for(let n=0;nNumber.EPSILON){const u=Math.sqrt(h),d=Math.sqrt(l*l+c*c),p=e.x-o/u,m=e.y+a/u,f=((n.x-c/d-p)*c-(n.y+l/d-m)*l)/(a*c-o*l);i=p+a*f-t.x,r=m+o*f-t.y;const g=i*i+r*r;if(g<=2)return new re(i,r);s=Math.sqrt(g/2)}else{let t=!1;a>Number.EPSILON?l>Number.EPSILON&&(t=!0):a<-Number.EPSILON?l<-Number.EPSILON&&(t=!0):Math.sign(o)===Math.sign(c)&&(t=!0),t?(i=-o,r=a,s=Math.sqrt(h)):(i=a,r=o,s=Math.sqrt(h/2))}return new re(i/s,r/s)}const I=[];for(let t=0,e=E.length,n=e-1,i=t+1;t=0;t--){const e=t/p,n=h*Math.cos(e*Math.PI/2),i=u*Math.sin(e*Math.PI/2)+d;for(let t=0,e=E.length;t=0;){const i=n;let r=n-1;r<0&&(r=t.length-1);for(let t=0,n=o+2*p;t0)&&d.push(e,r,l),(t!==n-1||o0!=t>0&&this.version++,this._anisotropy=t}get clearcoat(){return this._clearcoat}set clearcoat(t){this._clearcoat>0!=t>0&&this.version++,this._clearcoat=t}get iridescence(){return this._iridescence}set iridescence(t){this._iridescence>0!=t>0&&this.version++,this._iridescence=t}get dispersion(){return this._dispersion}set dispersion(t){this._dispersion>0!=t>0&&this.version++,this._dispersion=t}get sheen(){return this._sheen}set sheen(t){this._sheen>0!=t>0&&this.version++,this._sheen=t}get transmission(){return this._transmission}set transmission(t){this._transmission>0!=t>0&&this.version++,this._transmission=t}copy(t){return super.copy(t),this.defines={STANDARD:"",PHYSICAL:""},this.anisotropy=t.anisotropy,this.anisotropyRotation=t.anisotropyRotation,this.anisotropyMap=t.anisotropyMap,this.clearcoat=t.clearcoat,this.clearcoatMap=t.clearcoatMap,this.clearcoatRoughness=t.clearcoatRoughness,this.clearcoatRoughnessMap=t.clearcoatRoughnessMap,this.clearcoatNormalMap=t.clearcoatNormalMap,this.clearcoatNormalScale.copy(t.clearcoatNormalScale),this.dispersion=t.dispersion,this.ior=t.ior,this.iridescence=t.iridescence,this.iridescenceMap=t.iridescenceMap,this.iridescenceIOR=t.iridescenceIOR,this.iridescenceThicknessRange=[...t.iridescenceThicknessRange],this.iridescenceThicknessMap=t.iridescenceThicknessMap,this.sheen=t.sheen,this.sheenColor.copy(t.sheenColor),this.sheenColorMap=t.sheenColorMap,this.sheenRoughness=t.sheenRoughness,this.sheenRoughnessMap=t.sheenRoughnessMap,this.transmission=t.transmission,this.transmissionMap=t.transmissionMap,this.thickness=t.thickness,this.thicknessMap=t.thicknessMap,this.attenuationDistance=t.attenuationDistance,this.attenuationColor.copy(t.attenuationColor),this.specularIntensity=t.specularIntensity,this.specularIntensityMap=t.specularIntensityMap,this.specularColor.copy(t.specularColor),this.specularColorMap=t.specularColorMap,this}}class sh extends ai{constructor(t){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new ii(16777215),this.specular=new ii(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new ii(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new re(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Mn,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.specular.copy(t.specular),this.shininess=t.shininess,this.map=t.map,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.emissive.copy(t.emissive),this.emissiveMap=t.emissiveMap,this.emissiveIntensity=t.emissiveIntensity,this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.specularMap=t.specularMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.envMapRotation.copy(t.envMapRotation),this.combine=t.combine,this.reflectivity=t.reflectivity,this.refractionRatio=t.refractionRatio,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.flatShading=t.flatShading,this.fog=t.fog,this}}class ah extends ai{constructor(t){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new ii(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new ii(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new re(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.gradientMap=t.gradientMap,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.emissive.copy(t.emissive),this.emissiveMap=t.emissiveMap,this.emissiveIntensity=t.emissiveIntensity,this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.alphaMap=t.alphaMap,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.fog=t.fog,this}}class oh extends ai{constructor(t){super(),this.isMeshNormalMaterial=!0,this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new re(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.setValues(t)}copy(t){return super.copy(t),this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.flatShading=t.flatShading,this}}class lh extends ai{constructor(t){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new ii(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new ii(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new re(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Mn,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.emissive.copy(t.emissive),this.emissiveMap=t.emissiveMap,this.emissiveIntensity=t.emissiveIntensity,this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.specularMap=t.specularMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.envMapRotation.copy(t.envMapRotation),this.combine=t.combine,this.reflectivity=t.reflectivity,this.refractionRatio=t.refractionRatio,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.flatShading=t.flatShading,this.fog=t.fog,this}}class ch extends ai{constructor(t){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new ii(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new re(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.flatShading=!1,this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.defines={MATCAP:""},this.color.copy(t.color),this.matcap=t.matcap,this.map=t.map,this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.alphaMap=t.alphaMap,this.flatShading=t.flatShading,this.fog=t.fog,this}}class hh extends ul{constructor(t){super(),this.isLineDashedMaterial=!0,this.type="LineDashedMaterial",this.scale=1,this.dashSize=3,this.gapSize=1,this.setValues(t)}copy(t){return super.copy(t),this.scale=t.scale,this.dashSize=t.dashSize,this.gapSize=t.gapSize,this}}function uh(t,e,n){return!t||!n&&t.constructor===e?t:"number"==typeof e.BYTES_PER_ELEMENT?new e(t):Array.prototype.slice.call(t)}function dh(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function ph(t){const e=t.length,n=new Array(e);for(let t=0;t!==e;++t)n[t]=t;return n.sort((function(e,n){return t[e]-t[n]})),n}function mh(t,e,n){const i=t.length,r=new t.constructor(i);for(let s=0,a=0;a!==i;++s){const i=n[s]*e;for(let n=0;n!==e;++n)r[a++]=t[i+n]}return r}function fh(t,e,n,i){let r=1,s=t[0];for(;void 0!==s&&void 0===s[i];)s=t[r++];if(void 0===s)return;let a=s[i];if(void 0!==a)if(Array.isArray(a))do{a=s[i],void 0!==a&&(e.push(s.time),n.push.apply(n,a)),s=t[r++]}while(void 0!==s);else if(void 0!==a.toArray)do{a=s[i],void 0!==a&&(e.push(s.time),a.toArray(n,n.length)),s=t[r++]}while(void 0!==s);else do{a=s[i],void 0!==a&&(e.push(s.time),n.push(a)),s=t[r++]}while(void 0!==s)}const gh={convertArray:uh,isTypedArray:dh,getKeyframeOrder:ph,sortedArray:mh,flattenJSON:fh,subclip:function(t,e,n,i,r=30){const s=t.clone();s.name=e;const a=[];for(let t=0;t=i)){l.push(e.times[t]);for(let n=0;ns.tracks[t].times[0]&&(o=s.tracks[t].times[0]);for(let t=0;t=i.times[u]){const t=u*l+o,e=t+l-o;d=i.values.slice(t,e)}else{const t=i.createInterpolant(),e=o,n=l-o;t.evaluate(s),d=t.resultBuffer.slice(e,n)}"quaternion"===r&&(new Ue).fromArray(d).normalize().conjugate().toArray(d);const p=a.times.length;for(let t=0;t=r)break t;{const a=e[1];t=r)break e}s=n,n=0}}for(;n>>1;te;)--s;if(++s,0!==r||s!==i){r>=s&&(s=Math.max(s,1),r=s-1);const t=this.getValueSize();this.times=n.slice(r,s),this.values=this.values.slice(r*t,s*t)}return this}validate(){let t=!0;const e=this.getValueSize();e-Math.floor(e)!=0&&(console.error("THREE.KeyframeTrack: Invalid value size in track.",this),t=!1);const n=this.times,i=this.values,r=n.length;0===r&&(console.error("THREE.KeyframeTrack: Track is empty.",this),t=!1);let s=null;for(let e=0;e!==r;e++){const i=n[e];if("number"==typeof i&&isNaN(i)){console.error("THREE.KeyframeTrack: Time is not a valid number.",this,e,i),t=!1;break}if(null!==s&&s>i){console.error("THREE.KeyframeTrack: Out of order keys.",this,e,i,s),t=!1;break}s=i}if(void 0!==i&&dh(i))for(let e=0,n=i.length;e!==n;++e){const n=i[e];if(isNaN(n)){console.error("THREE.KeyframeTrack: Value is not a valid number.",this,e,n),t=!1;break}}return t}optimize(){const t=this.times.slice(),e=this.values.slice(),n=this.getValueSize(),i=this.getInterpolation()===At,r=t.length-1;let s=1;for(let a=1;a0){t[s]=t[r];for(let t=r*n,i=s*n,a=0;a!==n;++a)e[i+a]=e[t+a];++s}return s!==t.length?(this.times=t.slice(0,s),this.values=e.slice(0,s*n)):(this.times=t,this.values=e),this}clone(){const t=this.times.slice(),e=this.values.slice(),n=new(0,this.constructor)(this.name,t,e);return n.createInterpolant=this.createInterpolant,n}}Mh.prototype.TimeBufferType=Float32Array,Mh.prototype.ValueBufferType=Float32Array,Mh.prototype.DefaultInterpolation=Et;class Sh extends Mh{constructor(t,e,n){super(t,e,n)}}Sh.prototype.ValueTypeName="bool",Sh.prototype.ValueBufferType=Array,Sh.prototype.DefaultInterpolation=Tt,Sh.prototype.InterpolantFactoryMethodLinear=void 0,Sh.prototype.InterpolantFactoryMethodSmooth=void 0;class bh extends Mh{}bh.prototype.ValueTypeName="color";class wh extends Mh{}wh.prototype.ValueTypeName="number";class Th extends vh{constructor(t,e,n,i){super(t,e,n,i)}interpolate_(t,e,n,i){const r=this.resultBuffer,s=this.sampleValues,a=this.valueSize,o=(n-e)/(i-e);let l=t*a;for(let t=l+a;l!==t;l+=4)Ue.slerpFlat(r,0,s,l-a,s,l,o);return r}}class Eh extends Mh{InterpolantFactoryMethodLinear(t){return new Th(this.times,this.values,this.getValueSize(),t)}}Eh.prototype.ValueTypeName="quaternion",Eh.prototype.InterpolantFactoryMethodSmooth=void 0;class Ah extends Mh{constructor(t,e,n){super(t,e,n)}}Ah.prototype.ValueTypeName="string",Ah.prototype.ValueBufferType=Array,Ah.prototype.DefaultInterpolation=Tt,Ah.prototype.InterpolantFactoryMethodLinear=void 0,Ah.prototype.InterpolantFactoryMethodSmooth=void 0;class Ch extends Mh{}Ch.prototype.ValueTypeName="vector";class Rh{constructor(t="",e=-1,n=[],i=2500){this.name=t,this.tracks=n,this.duration=e,this.blendMode=i,this.uuid=Kt(),this.duration<0&&this.resetDuration()}static parse(t){const e=[],n=t.tracks,i=1/(t.fps||1);for(let t=0,r=n.length;t!==r;++t)e.push(Ph(n[t]).scale(i));const r=new this(t.name,t.duration,e,t.blendMode);return r.uuid=t.uuid,r}static toJSON(t){const e=[],n=t.tracks,i={name:t.name,duration:t.duration,tracks:e,uuid:t.uuid,blendMode:t.blendMode};for(let t=0,i=n.length;t!==i;++t)e.push(Mh.toJSON(n[t]));return i}static CreateFromMorphTargetSequence(t,e,n,i){const r=e.length,s=[];for(let t=0;t1){const t=s[1];let e=i[t];e||(i[t]=e=[]),e.push(n)}}const s=[];for(const t in i)s.push(this.CreateFromMorphTargetSequence(t,i[t],e,n));return s}static parseAnimation(t,e){if(!t)return console.error("THREE.AnimationClip: No animation in JSONLoader data."),null;const n=function(t,e,n,i,r){if(0!==n.length){const s=[],a=[];fh(n,s,a,i),0!==s.length&&r.push(new t(e,s,a))}},i=[],r=t.name||"default",s=t.fps||30,a=t.blendMode;let o=t.length||-1;const l=t.hierarchy||[];for(let t=0;t{e&&e(r),this.manager.itemEnd(t)}),0),r;if(void 0!==Nh[t])return void Nh[t].push({onLoad:e,onProgress:n,onError:i});Nh[t]=[],Nh[t].push({onLoad:e,onProgress:n,onError:i});const s=new Request(t,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin"}),a=this.mimeType,o=this.responseType;fetch(s).then((e=>{if(200===e.status||0===e.status){if(0===e.status&&console.warn("THREE.FileLoader: HTTP Status 0 received."),"undefined"==typeof ReadableStream||void 0===e.body||void 0===e.body.getReader)return e;const n=Nh[t],i=e.body.getReader(),r=e.headers.get("X-File-Size")||e.headers.get("Content-Length"),s=r?parseInt(r):0,a=0!==s;let o=0;const l=new ReadableStream({start(t){!function e(){i.read().then((({done:i,value:r})=>{if(i)t.close();else{o+=r.byteLength;const i=new ProgressEvent("progress",{lengthComputable:a,loaded:o,total:s});for(let t=0,e=n.length;t{t.error(e)}))}()}});return new Response(l)}throw new Oh(`fetch for "${e.url}" responded with ${e.status}: ${e.statusText}`,e)})).then((t=>{switch(o){case"arraybuffer":return t.arrayBuffer();case"blob":return t.blob();case"document":return t.text().then((t=>(new DOMParser).parseFromString(t,a)));case"json":return t.json();default:if(void 0===a)return t.text();{const e=/charset="?([^;"\s]*)"?/i.exec(a),n=e&&e[1]?e[1].toLowerCase():void 0,i=new TextDecoder(n);return t.arrayBuffer().then((t=>i.decode(t)))}}})).then((e=>{Ih.add(t,e);const n=Nh[t];delete Nh[t];for(let t=0,i=n.length;t{const n=Nh[t];if(void 0===n)throw this.manager.itemError(t),e;delete Nh[t];for(let t=0,i=n.length;t{this.manager.itemEnd(t)})),this.manager.itemStart(t)}setResponseType(t){return this.responseType=t,this}setMimeType(t){return this.mimeType=t,this}}class Bh extends Dh{constructor(t){super(t)}load(t,e,n,i){void 0!==this.path&&(t=this.path+t),t=this.manager.resolveURL(t);const r=this,s=Ih.get(t);if(void 0!==s)return r.manager.itemStart(t),setTimeout((function(){e&&e(s),r.manager.itemEnd(t)}),0),s;const a=he("img");function o(){c(),Ih.add(t,this),e&&e(this),r.manager.itemEnd(t)}function l(e){c(),i&&i(e),r.manager.itemError(t),r.manager.itemEnd(t)}function c(){a.removeEventListener("load",o,!1),a.removeEventListener("error",l,!1)}return a.addEventListener("load",o,!1),a.addEventListener("error",l,!1),"data:"!==t.slice(0,5)&&void 0!==this.crossOrigin&&(a.crossOrigin=this.crossOrigin),r.manager.itemStart(t),a.src=t,a}}class zh extends Bn{constructor(t,e=1){super(),this.isLight=!0,this.type="Light",this.color=new ii(t),this.intensity=e}dispose(){}copy(t,e){return super.copy(t,e),this.color.copy(t.color),this.intensity=t.intensity,this}toJSON(t){const e=super.toJSON(t);return e.object.color=this.color.getHex(),e.object.intensity=this.intensity,void 0!==this.groundColor&&(e.object.groundColor=this.groundColor.getHex()),void 0!==this.distance&&(e.object.distance=this.distance),void 0!==this.angle&&(e.object.angle=this.angle),void 0!==this.decay&&(e.object.decay=this.decay),void 0!==this.penumbra&&(e.object.penumbra=this.penumbra),void 0!==this.shadow&&(e.object.shadow=this.shadow.toJSON()),void 0!==this.target&&(e.object.target=this.target.uuid),e}}class kh extends zh{constructor(t,e,n){super(t,n),this.isHemisphereLight=!0,this.type="HemisphereLight",this.position.copy(Bn.DEFAULT_UP),this.updateMatrix(),this.groundColor=new ii(e)}copy(t,e){return super.copy(t,e),this.groundColor.copy(t.groundColor),this}}const Vh=new un,Hh=new De,Gh=new De;class Wh{constructor(t){this.camera=t,this.intensity=1,this.bias=0,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new re(512,512),this.map=null,this.mapPass=null,this.matrix=new un,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new or,this._frameExtents=new re(1,1),this._viewportCount=1,this._viewports=[new Ce(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(t){const e=this.camera,n=this.matrix;Hh.setFromMatrixPosition(t.matrixWorld),e.position.copy(Hh),Gh.setFromMatrixPosition(t.target.matrixWorld),e.lookAt(Gh),e.updateMatrixWorld(),Vh.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),this._frustum.setFromProjectionMatrix(Vh),n.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),n.multiply(Vh)}getViewport(t){return this._viewports[t]}getFrameExtents(){return this._frameExtents}dispose(){this.map&&this.map.dispose(),this.mapPass&&this.mapPass.dispose()}copy(t){return this.camera=t.camera.clone(),this.intensity=t.intensity,this.bias=t.bias,this.radius=t.radius,this.mapSize.copy(t.mapSize),this}clone(){return(new this.constructor).copy(this)}toJSON(){const t={};return 1!==this.intensity&&(t.intensity=this.intensity),0!==this.bias&&(t.bias=this.bias),0!==this.normalBias&&(t.normalBias=this.normalBias),1!==this.radius&&(t.radius=this.radius),512===this.mapSize.x&&512===this.mapSize.y||(t.mapSize=this.mapSize.toArray()),t.camera=this.camera.toJSON(!1).object,delete t.camera.matrix,t}}class Xh extends Wh{constructor(){super(new Ji(50,1,.5,500)),this.isSpotLightShadow=!0,this.focus=1}updateMatrices(t){const e=this.camera,n=2*Jt*t.angle*this.focus,i=this.mapSize.width/this.mapSize.height,r=t.distance||e.far;n===e.fov&&i===e.aspect&&r===e.far||(e.fov=n,e.aspect=i,e.far=r,e.updateProjectionMatrix()),super.updateMatrices(t)}copy(t){return super.copy(t),this.focus=t.focus,this}}class jh extends zh{constructor(t,e,n=0,i=Math.PI/3,r=0,s=2){super(t,e),this.isSpotLight=!0,this.type="SpotLight",this.position.copy(Bn.DEFAULT_UP),this.updateMatrix(),this.target=new Bn,this.distance=n,this.angle=i,this.penumbra=r,this.decay=s,this.map=null,this.shadow=new Xh}get power(){return this.intensity*Math.PI}set power(t){this.intensity=t/Math.PI}dispose(){this.shadow.dispose()}copy(t,e){return super.copy(t,e),this.distance=t.distance,this.angle=t.angle,this.penumbra=t.penumbra,this.decay=t.decay,this.target=t.target.clone(),this.shadow=t.shadow.clone(),this}}const qh=new un,Yh=new De,Zh=new De;class Jh extends Wh{constructor(){super(new Ji(90,1,.5,500)),this.isPointLightShadow=!0,this._frameExtents=new re(4,2),this._viewportCount=6,this._viewports=[new Ce(2,1,1,1),new Ce(0,1,1,1),new Ce(3,1,1,1),new Ce(1,1,1,1),new Ce(3,0,1,1),new Ce(1,0,1,1)],this._cubeDirections=[new De(1,0,0),new De(-1,0,0),new De(0,0,1),new De(0,0,-1),new De(0,1,0),new De(0,-1,0)],this._cubeUps=[new De(0,1,0),new De(0,1,0),new De(0,1,0),new De(0,1,0),new De(0,0,1),new De(0,0,-1)]}updateMatrices(t,e=0){const n=this.camera,i=this.matrix,r=t.distance||n.far;r!==n.far&&(n.far=r,n.updateProjectionMatrix()),Yh.setFromMatrixPosition(t.matrixWorld),n.position.copy(Yh),Zh.copy(n.position),Zh.add(this._cubeDirections[e]),n.up.copy(this._cubeUps[e]),n.lookAt(Zh),n.updateMatrixWorld(),i.makeTranslation(-Yh.x,-Yh.y,-Yh.z),qh.multiplyMatrices(n.projectionMatrix,n.matrixWorldInverse),this._frustum.setFromProjectionMatrix(qh)}}class Kh extends zh{constructor(t,e,n=0,i=2){super(t,e),this.isPointLight=!0,this.type="PointLight",this.distance=n,this.decay=i,this.shadow=new Jh}get power(){return 4*this.intensity*Math.PI}set power(t){this.intensity=t/(4*Math.PI)}dispose(){this.shadow.dispose()}copy(t,e){return super.copy(t,e),this.distance=t.distance,this.decay=t.decay,this.shadow=t.shadow.clone(),this}}class $h extends Wh{constructor(){super(new br(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}}class Qh extends zh{constructor(t,e){super(t,e),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(Bn.DEFAULT_UP),this.updateMatrix(),this.target=new Bn,this.shadow=new $h}dispose(){this.shadow.dispose()}copy(t){return super.copy(t),this.target=t.target.clone(),this.shadow=t.shadow.clone(),this}}class tu extends zh{constructor(t,e){super(t,e),this.isAmbientLight=!0,this.type="AmbientLight"}}class eu extends zh{constructor(t,e,n=10,i=10){super(t,e),this.isRectAreaLight=!0,this.type="RectAreaLight",this.width=n,this.height=i}get power(){return this.intensity*this.width*this.height*Math.PI}set power(t){this.intensity=t/(this.width*this.height*Math.PI)}copy(t){return super.copy(t),this.width=t.width,this.height=t.height,this}toJSON(t){const e=super.toJSON(t);return e.object.width=this.width,e.object.height=this.height,e}}class nu{constructor(){this.isSphericalHarmonics3=!0,this.coefficients=[];for(let t=0;t<9;t++)this.coefficients.push(new De)}set(t){for(let e=0;e<9;e++)this.coefficients[e].copy(t[e]);return this}zero(){for(let t=0;t<9;t++)this.coefficients[t].set(0,0,0);return this}getAt(t,e){const n=t.x,i=t.y,r=t.z,s=this.coefficients;return e.copy(s[0]).multiplyScalar(.282095),e.addScaledVector(s[1],.488603*i),e.addScaledVector(s[2],.488603*r),e.addScaledVector(s[3],.488603*n),e.addScaledVector(s[4],n*i*1.092548),e.addScaledVector(s[5],i*r*1.092548),e.addScaledVector(s[6],.315392*(3*r*r-1)),e.addScaledVector(s[7],n*r*1.092548),e.addScaledVector(s[8],.546274*(n*n-i*i)),e}getIrradianceAt(t,e){const n=t.x,i=t.y,r=t.z,s=this.coefficients;return e.copy(s[0]).multiplyScalar(.886227),e.addScaledVector(s[1],1.023328*i),e.addScaledVector(s[2],1.023328*r),e.addScaledVector(s[3],1.023328*n),e.addScaledVector(s[4],.858086*n*i),e.addScaledVector(s[5],.858086*i*r),e.addScaledVector(s[6],.743125*r*r-.247708),e.addScaledVector(s[7],.858086*n*r),e.addScaledVector(s[8],.429043*(n*n-i*i)),e}add(t){for(let e=0;e<9;e++)this.coefficients[e].add(t.coefficients[e]);return this}addScaledSH(t,e){for(let n=0;n<9;n++)this.coefficients[n].addScaledVector(t.coefficients[n],e);return this}scale(t){for(let e=0;e<9;e++)this.coefficients[e].multiplyScalar(t);return this}lerp(t,e){for(let n=0;n<9;n++)this.coefficients[n].lerp(t.coefficients[n],e);return this}equals(t){for(let e=0;e<9;e++)if(!this.coefficients[e].equals(t.coefficients[e]))return!1;return!0}copy(t){return this.set(t.coefficients)}clone(){return(new this.constructor).copy(this)}fromArray(t,e=0){const n=this.coefficients;for(let i=0;i<9;i++)n[i].fromArray(t,e+3*i);return this}toArray(t=[],e=0){const n=this.coefficients;for(let i=0;i<9;i++)n[i].toArray(t,e+3*i);return t}static getBasisAt(t,e){const n=t.x,i=t.y,r=t.z;e[0]=.282095,e[1]=.488603*i,e[2]=.488603*r,e[3]=.488603*n,e[4]=1.092548*n*i,e[5]=1.092548*i*r,e[6]=.315392*(3*r*r-1),e[7]=1.092548*n*r,e[8]=.546274*(n*n-i*i)}}class iu extends zh{constructor(t=new nu,e=1){super(void 0,e),this.isLightProbe=!0,this.sh=t}copy(t){return super.copy(t),this.sh.copy(t.sh),this}fromJSON(t){return this.intensity=t.intensity,this.sh.fromArray(t.sh),this}toJSON(t){const e=super.toJSON(t);return e.object.sh=this.sh.toArray(),e}}class ru extends Dh{constructor(t){super(t),this.textures={}}load(t,e,n,i){const r=this,s=new Fh(r.manager);s.setPath(r.path),s.setRequestHeader(r.requestHeader),s.setWithCredentials(r.withCredentials),s.load(t,(function(n){try{e(r.parse(JSON.parse(n)))}catch(e){i?i(e):console.error(e),r.manager.itemError(t)}}),n,i)}parse(t){const e=this.textures;function n(t){return void 0===e[t]&&console.warn("THREE.MaterialLoader: Undefined texture",t),e[t]}const i=this.createMaterialFromType(t.type);if(void 0!==t.uuid&&(i.uuid=t.uuid),void 0!==t.name&&(i.name=t.name),void 0!==t.color&&void 0!==i.color&&i.color.setHex(t.color),void 0!==t.roughness&&(i.roughness=t.roughness),void 0!==t.metalness&&(i.metalness=t.metalness),void 0!==t.sheen&&(i.sheen=t.sheen),void 0!==t.sheenColor&&(i.sheenColor=(new ii).setHex(t.sheenColor)),void 0!==t.sheenRoughness&&(i.sheenRoughness=t.sheenRoughness),void 0!==t.emissive&&void 0!==i.emissive&&i.emissive.setHex(t.emissive),void 0!==t.specular&&void 0!==i.specular&&i.specular.setHex(t.specular),void 0!==t.specularIntensity&&(i.specularIntensity=t.specularIntensity),void 0!==t.specularColor&&void 0!==i.specularColor&&i.specularColor.setHex(t.specularColor),void 0!==t.shininess&&(i.shininess=t.shininess),void 0!==t.clearcoat&&(i.clearcoat=t.clearcoat),void 0!==t.clearcoatRoughness&&(i.clearcoatRoughness=t.clearcoatRoughness),void 0!==t.dispersion&&(i.dispersion=t.dispersion),void 0!==t.iridescence&&(i.iridescence=t.iridescence),void 0!==t.iridescenceIOR&&(i.iridescenceIOR=t.iridescenceIOR),void 0!==t.iridescenceThicknessRange&&(i.iridescenceThicknessRange=t.iridescenceThicknessRange),void 0!==t.transmission&&(i.transmission=t.transmission),void 0!==t.thickness&&(i.thickness=t.thickness),void 0!==t.attenuationDistance&&(i.attenuationDistance=t.attenuationDistance),void 0!==t.attenuationColor&&void 0!==i.attenuationColor&&i.attenuationColor.setHex(t.attenuationColor),void 0!==t.anisotropy&&(i.anisotropy=t.anisotropy),void 0!==t.anisotropyRotation&&(i.anisotropyRotation=t.anisotropyRotation),void 0!==t.fog&&(i.fog=t.fog),void 0!==t.flatShading&&(i.flatShading=t.flatShading),void 0!==t.blending&&(i.blending=t.blending),void 0!==t.combine&&(i.combine=t.combine),void 0!==t.side&&(i.side=t.side),void 0!==t.shadowSide&&(i.shadowSide=t.shadowSide),void 0!==t.opacity&&(i.opacity=t.opacity),void 0!==t.transparent&&(i.transparent=t.transparent),void 0!==t.alphaTest&&(i.alphaTest=t.alphaTest),void 0!==t.alphaHash&&(i.alphaHash=t.alphaHash),void 0!==t.depthFunc&&(i.depthFunc=t.depthFunc),void 0!==t.depthTest&&(i.depthTest=t.depthTest),void 0!==t.depthWrite&&(i.depthWrite=t.depthWrite),void 0!==t.colorWrite&&(i.colorWrite=t.colorWrite),void 0!==t.blendSrc&&(i.blendSrc=t.blendSrc),void 0!==t.blendDst&&(i.blendDst=t.blendDst),void 0!==t.blendEquation&&(i.blendEquation=t.blendEquation),void 0!==t.blendSrcAlpha&&(i.blendSrcAlpha=t.blendSrcAlpha),void 0!==t.blendDstAlpha&&(i.blendDstAlpha=t.blendDstAlpha),void 0!==t.blendEquationAlpha&&(i.blendEquationAlpha=t.blendEquationAlpha),void 0!==t.blendColor&&void 0!==i.blendColor&&i.blendColor.setHex(t.blendColor),void 0!==t.blendAlpha&&(i.blendAlpha=t.blendAlpha),void 0!==t.stencilWriteMask&&(i.stencilWriteMask=t.stencilWriteMask),void 0!==t.stencilFunc&&(i.stencilFunc=t.stencilFunc),void 0!==t.stencilRef&&(i.stencilRef=t.stencilRef),void 0!==t.stencilFuncMask&&(i.stencilFuncMask=t.stencilFuncMask),void 0!==t.stencilFail&&(i.stencilFail=t.stencilFail),void 0!==t.stencilZFail&&(i.stencilZFail=t.stencilZFail),void 0!==t.stencilZPass&&(i.stencilZPass=t.stencilZPass),void 0!==t.stencilWrite&&(i.stencilWrite=t.stencilWrite),void 0!==t.wireframe&&(i.wireframe=t.wireframe),void 0!==t.wireframeLinewidth&&(i.wireframeLinewidth=t.wireframeLinewidth),void 0!==t.wireframeLinecap&&(i.wireframeLinecap=t.wireframeLinecap),void 0!==t.wireframeLinejoin&&(i.wireframeLinejoin=t.wireframeLinejoin),void 0!==t.rotation&&(i.rotation=t.rotation),void 0!==t.linewidth&&(i.linewidth=t.linewidth),void 0!==t.dashSize&&(i.dashSize=t.dashSize),void 0!==t.gapSize&&(i.gapSize=t.gapSize),void 0!==t.scale&&(i.scale=t.scale),void 0!==t.polygonOffset&&(i.polygonOffset=t.polygonOffset),void 0!==t.polygonOffsetFactor&&(i.polygonOffsetFactor=t.polygonOffsetFactor),void 0!==t.polygonOffsetUnits&&(i.polygonOffsetUnits=t.polygonOffsetUnits),void 0!==t.dithering&&(i.dithering=t.dithering),void 0!==t.alphaToCoverage&&(i.alphaToCoverage=t.alphaToCoverage),void 0!==t.premultipliedAlpha&&(i.premultipliedAlpha=t.premultipliedAlpha),void 0!==t.forceSinglePass&&(i.forceSinglePass=t.forceSinglePass),void 0!==t.visible&&(i.visible=t.visible),void 0!==t.toneMapped&&(i.toneMapped=t.toneMapped),void 0!==t.userData&&(i.userData=t.userData),void 0!==t.vertexColors&&("number"==typeof t.vertexColors?i.vertexColors=t.vertexColors>0:i.vertexColors=t.vertexColors),void 0!==t.uniforms)for(const e in t.uniforms){const r=t.uniforms[e];switch(i.uniforms[e]={},r.type){case"t":i.uniforms[e].value=n(r.value);break;case"c":i.uniforms[e].value=(new ii).setHex(r.value);break;case"v2":i.uniforms[e].value=(new re).fromArray(r.value);break;case"v3":i.uniforms[e].value=(new De).fromArray(r.value);break;case"v4":i.uniforms[e].value=(new Ce).fromArray(r.value);break;case"m3":i.uniforms[e].value=(new se).fromArray(r.value);break;case"m4":i.uniforms[e].value=(new un).fromArray(r.value);break;default:i.uniforms[e].value=r.value}}if(void 0!==t.defines&&(i.defines=t.defines),void 0!==t.vertexShader&&(i.vertexShader=t.vertexShader),void 0!==t.fragmentShader&&(i.fragmentShader=t.fragmentShader),void 0!==t.glslVersion&&(i.glslVersion=t.glslVersion),void 0!==t.extensions)for(const e in t.extensions)i.extensions[e]=t.extensions[e];if(void 0!==t.lights&&(i.lights=t.lights),void 0!==t.clipping&&(i.clipping=t.clipping),void 0!==t.size&&(i.size=t.size),void 0!==t.sizeAttenuation&&(i.sizeAttenuation=t.sizeAttenuation),void 0!==t.map&&(i.map=n(t.map)),void 0!==t.matcap&&(i.matcap=n(t.matcap)),void 0!==t.alphaMap&&(i.alphaMap=n(t.alphaMap)),void 0!==t.bumpMap&&(i.bumpMap=n(t.bumpMap)),void 0!==t.bumpScale&&(i.bumpScale=t.bumpScale),void 0!==t.normalMap&&(i.normalMap=n(t.normalMap)),void 0!==t.normalMapType&&(i.normalMapType=t.normalMapType),void 0!==t.normalScale){let e=t.normalScale;!1===Array.isArray(e)&&(e=[e,e]),i.normalScale=(new re).fromArray(e)}return void 0!==t.displacementMap&&(i.displacementMap=n(t.displacementMap)),void 0!==t.displacementScale&&(i.displacementScale=t.displacementScale),void 0!==t.displacementBias&&(i.displacementBias=t.displacementBias),void 0!==t.roughnessMap&&(i.roughnessMap=n(t.roughnessMap)),void 0!==t.metalnessMap&&(i.metalnessMap=n(t.metalnessMap)),void 0!==t.emissiveMap&&(i.emissiveMap=n(t.emissiveMap)),void 0!==t.emissiveIntensity&&(i.emissiveIntensity=t.emissiveIntensity),void 0!==t.specularMap&&(i.specularMap=n(t.specularMap)),void 0!==t.specularIntensityMap&&(i.specularIntensityMap=n(t.specularIntensityMap)),void 0!==t.specularColorMap&&(i.specularColorMap=n(t.specularColorMap)),void 0!==t.envMap&&(i.envMap=n(t.envMap)),void 0!==t.envMapRotation&&i.envMapRotation.fromArray(t.envMapRotation),void 0!==t.envMapIntensity&&(i.envMapIntensity=t.envMapIntensity),void 0!==t.reflectivity&&(i.reflectivity=t.reflectivity),void 0!==t.refractionRatio&&(i.refractionRatio=t.refractionRatio),void 0!==t.lightMap&&(i.lightMap=n(t.lightMap)),void 0!==t.lightMapIntensity&&(i.lightMapIntensity=t.lightMapIntensity),void 0!==t.aoMap&&(i.aoMap=n(t.aoMap)),void 0!==t.aoMapIntensity&&(i.aoMapIntensity=t.aoMapIntensity),void 0!==t.gradientMap&&(i.gradientMap=n(t.gradientMap)),void 0!==t.clearcoatMap&&(i.clearcoatMap=n(t.clearcoatMap)),void 0!==t.clearcoatRoughnessMap&&(i.clearcoatRoughnessMap=n(t.clearcoatRoughnessMap)),void 0!==t.clearcoatNormalMap&&(i.clearcoatNormalMap=n(t.clearcoatNormalMap)),void 0!==t.clearcoatNormalScale&&(i.clearcoatNormalScale=(new re).fromArray(t.clearcoatNormalScale)),void 0!==t.iridescenceMap&&(i.iridescenceMap=n(t.iridescenceMap)),void 0!==t.iridescenceThicknessMap&&(i.iridescenceThicknessMap=n(t.iridescenceThicknessMap)),void 0!==t.transmissionMap&&(i.transmissionMap=n(t.transmissionMap)),void 0!==t.thicknessMap&&(i.thicknessMap=n(t.thicknessMap)),void 0!==t.anisotropyMap&&(i.anisotropyMap=n(t.anisotropyMap)),void 0!==t.sheenColorMap&&(i.sheenColorMap=n(t.sheenColorMap)),void 0!==t.sheenRoughnessMap&&(i.sheenRoughnessMap=n(t.sheenRoughnessMap)),i}setTextures(t){return this.textures=t,this}createMaterialFromType(t){return ru.createMaterialFromType(t)}static createMaterialFromType(t){return new{ShadowMaterial:eh,SpriteMaterial:no,RawShaderMaterial:nh,ShaderMaterial:Xi,PointsMaterial:Tl,MeshPhysicalMaterial:rh,MeshStandardMaterial:ih,MeshPhongMaterial:sh,MeshToonMaterial:ah,MeshNormalMaterial:oh,MeshLambertMaterial:lh,MeshDepthMaterial:Ia,MeshDistanceMaterial:La,MeshBasicMaterial:oi,MeshMatcapMaterial:ch,LineDashedMaterial:hh,LineBasicMaterial:ul,Material:ai}[t]}}class su{static decodeText(t){if(console.warn("THREE.LoaderUtils: decodeText() has been deprecated with r165 and will be removed with r175. Use TextDecoder instead."),"undefined"!=typeof TextDecoder)return(new TextDecoder).decode(t);let e="";for(let n=0,i=t.length;n0){this.source.connect(this.filters[0]);for(let t=1,e=this.filters.length;t0){this.source.disconnect(this.filters[0]);for(let t=1,e=this.filters.length;t0&&this._mixBufferRegionAdditive(n,i,this._addIndex*e,1,e);for(let t=e,r=e+e;t!==r;++t)if(n[t]!==n[t+e]){a.setValue(n,i);break}}saveOriginalState(){const t=this.binding,e=this.buffer,n=this.valueSize,i=n*this._origIndex;t.getValue(e,i);for(let t=n,r=i;t!==r;++t)e[t]=e[i+t%n];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0}restoreOriginalState(){const t=3*this.valueSize;this.binding.setValue(this.buffer,t)}_setAdditiveIdentityNumeric(){const t=this._addIndex*this.valueSize,e=t+this.valueSize;for(let n=t;n=.5)for(let i=0;i!==r;++i)t[e+i]=t[n+i]}_slerp(t,e,n,i){Ue.slerpFlat(t,e,t,e,t,n,i)}_slerpAdditive(t,e,n,i,r){const s=this._workIndex*r;Ue.multiplyQuaternionsFlat(t,s,t,e,t,n),Ue.slerpFlat(t,e,t,e,t,s,i)}_lerp(t,e,n,i,r){const s=1-i;for(let a=0;a!==r;++a){const r=e+a;t[r]=t[r]*s+t[n+a]*i}}_lerpAdditive(t,e,n,i,r){for(let s=0;s!==r;++s){const r=e+s;t[r]=t[r]+t[n+s]*i}}}const Cu="\\[\\]\\.:\\/",Ru=new RegExp("["+Cu+"]","g"),Pu="[^"+Cu+"]",Iu="[^"+Cu.replace("\\.","")+"]",Lu=new RegExp("^"+/((?:WC+[\/:])*)/.source.replace("WC",Pu)+/(WCOD+)?/.source.replace("WCOD",Iu)+/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",Pu)+/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",Pu)+"$"),Uu=["material","materials","bones","map"];class Du{constructor(t,e,n){this.path=e,this.parsedPath=n||Du.parseTrackName(e),this.node=Du.findNode(t,this.parsedPath.nodeName),this.rootNode=t,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(t,e,n){return t&&t.isAnimationObjectGroup?new Du.Composite(t,e,n):new Du(t,e,n)}static sanitizeNodeName(t){return t.replace(/\s/g,"_").replace(Ru,"")}static parseTrackName(t){const e=Lu.exec(t);if(null===e)throw new Error("PropertyBinding: Cannot parse trackName: "+t);const n={nodeName:e[2],objectName:e[3],objectIndex:e[4],propertyName:e[5],propertyIndex:e[6]},i=n.nodeName&&n.nodeName.lastIndexOf(".");if(void 0!==i&&-1!==i){const t=n.nodeName.substring(i+1);-1!==Uu.indexOf(t)&&(n.nodeName=n.nodeName.substring(0,i),n.objectName=t)}if(null===n.propertyName||0===n.propertyName.length)throw new Error("PropertyBinding: can not parse propertyName from trackName: "+t);return n}static findNode(t,e){if(void 0===e||""===e||"."===e||-1===e||e===t.name||e===t.uuid)return t;if(t.skeleton){const n=t.skeleton.getBoneByName(e);if(void 0!==n)return n}if(t.children){const n=function(t){for(let i=0;i0){const t=this._interpolants,e=this._propertyBindings;if(this.blendMode===It)for(let n=0,i=t.length;n!==i;++n)t[n].evaluate(s),e[n].accumulateAdditive(a);else for(let n=0,r=t.length;n!==r;++n)t[n].evaluate(s),e[n].accumulate(i,a)}}_updateWeight(t){let e=0;if(this.enabled){e=this.weight;const n=this._weightInterpolant;if(null!==n){const i=n.evaluate(t)[0];e*=i,t>n.parameterPositions[1]&&(this.stopFading(),0===i&&(this.enabled=!1))}}return this._effectiveWeight=e,e}_updateTimeScale(t){let e=0;if(!this.paused){e=this.timeScale;const n=this._timeScaleInterpolant;null!==n&&(e*=n.evaluate(t)[0],t>n.parameterPositions[1]&&(this.stopWarping(),0===e?this.paused=!0:this.timeScale=e))}return this._effectiveTimeScale=e,e}_updateTime(t){const e=this._clip.duration,n=this.loop;let i=this.time+t,r=this._loopCount;const s=2202===n;if(0===t)return-1===r?i:s&&1==(1&r)?e-i:i;if(2200===n){-1===r&&(this._loopCount=0,this._setEndings(!0,!0,!1));t:{if(i>=e)i=e;else{if(!(i<0)){this.time=i;break t}i=0}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this.time=i,this._mixer.dispatchEvent({type:"finished",action:this,direction:t<0?-1:1})}}else{if(-1===r&&(t>=0?(r=0,this._setEndings(!0,0===this.repetitions,s)):this._setEndings(0===this.repetitions,!0,s)),i>=e||i<0){const n=Math.floor(i/e);i-=e*n,r+=Math.abs(n);const a=this.repetitions-r;if(a<=0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,i=t>0?e:0,this.time=i,this._mixer.dispatchEvent({type:"finished",action:this,direction:t>0?1:-1});else{if(1===a){const e=t<0;this._setEndings(e,!e,s)}else this._setEndings(!1,!1,s);this._loopCount=r,this.time=i,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:n})}}else this.time=i;if(s&&1==(1&r))return e-i}return i}_setEndings(t,e,n){const i=this._interpolantSettings;n?(i.endingStart=Rt,i.endingEnd=Rt):(i.endingStart=t?this.zeroSlopeAtStart?Rt:Ct:Pt,i.endingEnd=e?this.zeroSlopeAtEnd?Rt:Ct:Pt)}_scheduleFading(t,e,n){const i=this._mixer,r=i.time;let s=this._weightInterpolant;null===s&&(s=i._lendControlInterpolant(),this._weightInterpolant=s);const a=s.parameterPositions,o=s.sampleValues;return a[0]=r,o[0]=e,a[1]=r+t,o[1]=n,this}}const Ou=new Float32Array(1);class Fu{constructor(t){this.value=t}clone(){return new Fu(void 0===this.value.clone?this.value:this.value.clone())}}let Bu=0;const zu=new un;function ku(t,e){return t.distance-e.distance}function Vu(t,e,n,i){let r=!0;if(t.layers.test(e.layers)&&!1===t.raycast(e,n)&&(r=!1),!0===r&&!0===i){const i=t.children;for(let t=0,r=i.length;t=0;--e)t[e].stop();return this}update(t){t*=this.timeScale;const e=this._actions,n=this._nActiveActions,i=this.time+=t,r=Math.sign(t),s=this._accuIndex^=1;for(let a=0;a!==n;++a)e[a]._update(i,t,r,s);const a=this._bindings,o=this._nActiveBindings;for(let t=0;t!==o;++t)a[t].apply(s);return this}setTime(t){this.time=0;for(let t=0;t=r){const s=r++,c=t[s];e[c.uuid]=l,t[l]=c,e[o]=s,t[s]=a;for(let t=0,e=i;t!==e;++t){const e=n[t],i=e[s],r=e[l];e[l]=i,e[s]=r}}}this.nCachedObjects_=r}uncache(){const t=this._objects,e=this._indicesByUUID,n=this._bindings,i=n.length;let r=this.nCachedObjects_,s=t.length;for(let a=0,o=arguments.length;a!==o;++a){const o=arguments[a].uuid,l=e[o];if(void 0!==l)if(delete e[o],l0&&(e[a.uuid]=l),t[l]=a,t.pop();for(let t=0,e=i;t!==e;++t){const e=n[t];e[l]=e[r],e.pop()}}}this.nCachedObjects_=r}subscribe_(t,e){const n=this._bindingsIndicesByPath;let i=n[t];const r=this._bindings;if(void 0!==i)return r[i];const s=this._paths,a=this._parsedPaths,o=this._objects,l=o.length,c=this.nCachedObjects_,h=new Array(l);i=r.length,n[t]=i,s.push(t),a.push(e),r.push(h);for(let n=c,i=o.length;n!==i;++n){const i=o[n];h[n]=new Du(i,t,e)}return h}unsubscribe_(t){const e=this._bindingsIndicesByPath,n=e[t];if(void 0!==n){const i=this._paths,r=this._parsedPaths,s=this._bindings,a=s.length-1,o=s[a];e[t[a]]=n,s[n]=o,s.pop(),r[n]=r[a],r.pop(),i[n]=i[a],i.pop()}}},e.AnimationUtils=gh,e.ArcCurve=Nl,e.ArrayCamera=ka,e.ArrowHelper=class extends Bn{constructor(t=new De(0,0,1),e=new De(0,0,0),n=1,i=16776960,r=.2*n,s=.2*r){super(),this.type="ArrowHelper",void 0===ld&&(ld=new Ei,ld.setAttribute("position",new _i([0,0,0,0,1,0],3)),cd=new rc(0,.5,1,5,1),cd.translate(0,-.5,0)),this.position.copy(e),this.line=new yl(ld,new ul({color:i,toneMapped:!1})),this.line.matrixAutoUpdate=!1,this.add(this.line),this.cone=new Bi(cd,new oi({color:i,toneMapped:!1})),this.cone.matrixAutoUpdate=!1,this.add(this.cone),this.setDirection(t),this.setLength(n,r,s)}setDirection(t){if(t.y>.99999)this.quaternion.set(0,0,0,1);else if(t.y<-.99999)this.quaternion.set(1,0,0,0);else{od.set(t.z,0,-t.x).normalize();const e=Math.acos(t.y);this.quaternion.setFromAxisAngle(od,e)}}setLength(t,e=.2*t,n=.2*e){this.line.scale.set(1,Math.max(1e-4,t-e),1),this.line.updateMatrix(),this.cone.scale.set(n,e,n),this.cone.position.y=t,this.cone.updateMatrix()}setColor(t){this.line.material.color.set(t),this.cone.material.color.set(t)}copy(t){return super.copy(t,!1),this.line.copy(t.line),this.cone.copy(t.cone),this}dispose(){this.line.geometry.dispose(),this.line.material.dispose(),this.cone.geometry.dispose(),this.cone.material.dispose()}},e.AttachedBindMode=a,e.Audio=Su,e.AudioAnalyser=class{constructor(t,e=2048){this.analyser=t.context.createAnalyser(),this.analyser.fftSize=e,this.data=new Uint8Array(this.analyser.frequencyBinCount),t.getOutput().connect(this.analyser)}getFrequencyData(){return this.analyser.getByteFrequencyData(this.data),this.data}getAverageFrequency(){let t=0;const e=this.getFrequencyData();for(let n=0;n=this.min.x&&t.x<=this.max.x&&t.y>=this.min.y&&t.y<=this.max.y}containsBox(t){return this.min.x<=t.min.x&&t.max.x<=this.max.x&&this.min.y<=t.min.y&&t.max.y<=this.max.y}getParameter(t,e){return e.set((t.x-this.min.x)/(this.max.x-this.min.x),(t.y-this.min.y)/(this.max.y-this.min.y))}intersectsBox(t){return t.max.x>=this.min.x&&t.min.x<=this.max.x&&t.max.y>=this.min.y&&t.min.y<=this.max.y}clampPoint(t,e){return e.copy(t).clamp(this.min,this.max)}distanceToPoint(t){return this.clampPoint(t,Gu).distanceTo(t)}intersect(t){return this.min.max(t.min),this.max.min(t.max),this.isEmpty()&&this.makeEmpty(),this}union(t){return this.min.min(t.min),this.max.max(t.max),this}translate(t){return this.min.add(t),this.max.add(t),this}equals(t){return t.min.equals(this.min)&&t.max.equals(this.max)}},e.Box3=Fe,e.Box3Helper=class extends bl{constructor(t,e=16776960){const n=new Uint16Array([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,4,1,5,2,6,3,7]),i=new Ei;i.setIndex(new fi(n,1)),i.setAttribute("position",new _i([1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1],3)),super(i,new ul({color:e,toneMapped:!1})),this.box=t,this.type="Box3Helper",this.geometry.computeBoundingSphere()}updateMatrixWorld(t){const e=this.box;e.isEmpty()||(e.getCenter(this.position),e.getSize(this.scale),this.scale.multiplyScalar(.5),super.updateMatrixWorld(t))}dispose(){this.geometry.dispose(),this.material.dispose()}},e.BoxGeometry=ki,e.BoxHelper=class extends bl{constructor(t,e=16776960){const n=new Uint16Array([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,4,1,5,2,6,3,7]),i=new Float32Array(24),r=new Ei;r.setIndex(new fi(n,1)),r.setAttribute("position",new fi(i,3)),super(r,new ul({color:e,toneMapped:!1})),this.object=t,this.type="BoxHelper",this.matrixAutoUpdate=!1,this.update()}update(t){if(void 0!==t&&console.warn("THREE.BoxHelper: .update() has no longer arguments."),void 0!==this.object&&ad.setFromObject(this.object),ad.isEmpty())return;const e=ad.min,n=ad.max,i=this.geometry.attributes.position,r=i.array;r[0]=n.x,r[1]=n.y,r[2]=n.z,r[3]=e.x,r[4]=n.y,r[5]=n.z,r[6]=e.x,r[7]=e.y,r[8]=n.z,r[9]=n.x,r[10]=e.y,r[11]=n.z,r[12]=n.x,r[13]=n.y,r[14]=e.z,r[15]=e.x,r[16]=n.y,r[17]=e.z,r[18]=e.x,r[19]=e.y,r[20]=e.z,r[21]=n.x,r[22]=e.y,r[23]=e.z,i.needsUpdate=!0,this.geometry.computeBoundingSphere()}setFromObject(t){return this.object=t,this.update(),this}copy(t,e){return super.copy(t,e),this.object=t.object,this}dispose(){this.geometry.dispose(),this.material.dispose()}},e.BufferAttribute=fi,e.BufferGeometry=Ei,e.BufferGeometryLoader=ou,e.ByteType=w,e.Cache=Ih,e.Camera=ji,e.CameraHelper=class extends bl{constructor(t){const e=new Ei,n=new ul({color:16777215,vertexColors:!0,toneMapped:!1}),i=[],r=[],s={};function a(t,e){o(t),o(e)}function o(t){i.push(0,0,0),r.push(0,0,0),void 0===s[t]&&(s[t]=[]),s[t].push(i.length/3-1)}a("n1","n2"),a("n2","n4"),a("n4","n3"),a("n3","n1"),a("f1","f2"),a("f2","f4"),a("f4","f3"),a("f3","f1"),a("n1","f1"),a("n2","f2"),a("n3","f3"),a("n4","f4"),a("p","n1"),a("p","n2"),a("p","n3"),a("p","n4"),a("u1","u2"),a("u2","u3"),a("u3","u1"),a("c","t"),a("p","c"),a("cn1","cn2"),a("cn3","cn4"),a("cf1","cf2"),a("cf3","cf4"),e.setAttribute("position",new _i(i,3)),e.setAttribute("color",new _i(r,3)),super(e,n),this.type="CameraHelper",this.camera=t,this.camera.updateProjectionMatrix&&this.camera.updateProjectionMatrix(),this.matrix=t.matrixWorld,this.matrixAutoUpdate=!1,this.pointMap=s,this.update();const l=new ii(16755200),c=new ii(16711680),h=new ii(43775),u=new ii(16777215),d=new ii(3355443);this.setColors(l,c,h,u,d)}setColors(t,e,n,i,r){const s=this.geometry.getAttribute("color");s.setXYZ(0,t.r,t.g,t.b),s.setXYZ(1,t.r,t.g,t.b),s.setXYZ(2,t.r,t.g,t.b),s.setXYZ(3,t.r,t.g,t.b),s.setXYZ(4,t.r,t.g,t.b),s.setXYZ(5,t.r,t.g,t.b),s.setXYZ(6,t.r,t.g,t.b),s.setXYZ(7,t.r,t.g,t.b),s.setXYZ(8,t.r,t.g,t.b),s.setXYZ(9,t.r,t.g,t.b),s.setXYZ(10,t.r,t.g,t.b),s.setXYZ(11,t.r,t.g,t.b),s.setXYZ(12,t.r,t.g,t.b),s.setXYZ(13,t.r,t.g,t.b),s.setXYZ(14,t.r,t.g,t.b),s.setXYZ(15,t.r,t.g,t.b),s.setXYZ(16,t.r,t.g,t.b),s.setXYZ(17,t.r,t.g,t.b),s.setXYZ(18,t.r,t.g,t.b),s.setXYZ(19,t.r,t.g,t.b),s.setXYZ(20,t.r,t.g,t.b),s.setXYZ(21,t.r,t.g,t.b),s.setXYZ(22,t.r,t.g,t.b),s.setXYZ(23,t.r,t.g,t.b),s.setXYZ(24,e.r,e.g,e.b),s.setXYZ(25,e.r,e.g,e.b),s.setXYZ(26,e.r,e.g,e.b),s.setXYZ(27,e.r,e.g,e.b),s.setXYZ(28,e.r,e.g,e.b),s.setXYZ(29,e.r,e.g,e.b),s.setXYZ(30,e.r,e.g,e.b),s.setXYZ(31,e.r,e.g,e.b),s.setXYZ(32,n.r,n.g,n.b),s.setXYZ(33,n.r,n.g,n.b),s.setXYZ(34,n.r,n.g,n.b),s.setXYZ(35,n.r,n.g,n.b),s.setXYZ(36,n.r,n.g,n.b),s.setXYZ(37,n.r,n.g,n.b),s.setXYZ(38,i.r,i.g,i.b),s.setXYZ(39,i.r,i.g,i.b),s.setXYZ(40,r.r,r.g,r.b),s.setXYZ(41,r.r,r.g,r.b),s.setXYZ(42,r.r,r.g,r.b),s.setXYZ(43,r.r,r.g,r.b),s.setXYZ(44,r.r,r.g,r.b),s.setXYZ(45,r.r,r.g,r.b),s.setXYZ(46,r.r,r.g,r.b),s.setXYZ(47,r.r,r.g,r.b),s.setXYZ(48,r.r,r.g,r.b),s.setXYZ(49,r.r,r.g,r.b),s.needsUpdate=!0}update(){const t=this.geometry,e=this.pointMap;rd.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse),sd("c",e,t,rd,0,0,-1),sd("t",e,t,rd,0,0,1),sd("n1",e,t,rd,-1,-1,-1),sd("n2",e,t,rd,1,-1,-1),sd("n3",e,t,rd,-1,1,-1),sd("n4",e,t,rd,1,1,-1),sd("f1",e,t,rd,-1,-1,1),sd("f2",e,t,rd,1,-1,1),sd("f3",e,t,rd,-1,1,1),sd("f4",e,t,rd,1,1,1),sd("u1",e,t,rd,.7,1.1,-1),sd("u2",e,t,rd,-.7,1.1,-1),sd("u3",e,t,rd,0,2,-1),sd("cf1",e,t,rd,-1,0,1),sd("cf2",e,t,rd,1,0,1),sd("cf3",e,t,rd,0,-1,1),sd("cf4",e,t,rd,0,1,1),sd("cn1",e,t,rd,-1,0,-1),sd("cn2",e,t,rd,1,0,-1),sd("cn3",e,t,rd,0,-1,-1),sd("cn4",e,t,rd,0,1,-1),t.getAttribute("position").needsUpdate=!0}dispose(){this.geometry.dispose(),this.material.dispose()}},e.CanvasTexture=class extends Ae{constructor(t,e,n,i,r,s,a,o,l){super(t,e,n,i,r,s,a,o,l),this.isCanvasTexture=!0,this.needsUpdate=!0}},e.CapsuleGeometry=nc,e.CatmullRomCurve3=Vl,e.CineonToneMapping=3,e.CircleGeometry=ic,e.ClampToEdgeWrapping=f,e.Clock=gu,e.Color=ii,e.ColorKeyframeTrack=bh,e.ColorManagement=_e,e.CompressedArrayTexture=class extends Ll{constructor(t,e,n,i,r,s){super(t,e,n,r,s),this.isCompressedArrayTexture=!0,this.image.depth=i,this.wrapR=f,this.layerUpdates=new Set}addLayerUpdate(t){this.layerUpdates.add(t)}clearLayerUpdates(){this.layerUpdates.clear()}},e.CompressedCubeTexture=class extends Ll{constructor(t,e,n){super(void 0,t[0].width,t[0].height,e,n,c),this.isCompressedCubeTexture=!0,this.isCubeTexture=!0,this.image=t}},e.CompressedTexture=Ll,e.CompressedTextureLoader=class extends Dh{constructor(t){super(t)}load(t,e,n,i){const r=this,s=[],a=new Ll,o=new Fh(this.manager);o.setPath(this.path),o.setResponseType("arraybuffer"),o.setRequestHeader(this.requestHeader),o.setWithCredentials(r.withCredentials);let l=0;function c(c){o.load(t[c],(function(t){const n=r.parse(t,!0);s[c]={width:n.width,height:n.height,format:n.format,mipmaps:n.mipmaps},l+=1,6===l&&(1===n.mipmapCount&&(a.minFilter=x),a.image=s,a.format=n.format,a.needsUpdate=!0,e&&e(a))}),n,i)}if(Array.isArray(t))for(let e=0,n=t.length;e{e&&e(n),r.manager.itemEnd(t)})).catch((t=>{i&&i(t)})):(setTimeout((function(){e&&e(s),r.manager.itemEnd(t)}),0),s);const a={};a.credentials="anonymous"===this.crossOrigin?"same-origin":"include",a.headers=this.requestHeader;const o=fetch(t,a).then((function(t){return t.blob()})).then((function(t){return createImageBitmap(t,Object.assign(r.options,{colorSpaceConversion:"none"}))})).then((function(n){return Ih.add(t,n),e&&e(n),r.manager.itemEnd(t),n})).catch((function(e){i&&i(e),Ih.remove(t),r.manager.itemError(t),r.manager.itemEnd(t)}));Ih.add(t,o),r.manager.itemStart(t)}},e.ImageLoader=Bh,e.ImageUtils=Se,e.IncrementStencilOp=7682,e.IncrementWrapStencilOp=34055,e.InstancedBufferAttribute=Fo,e.InstancedBufferGeometry=au,e.InstancedInterleavedBuffer=class extends Qa{constructor(t,e,n=1){super(t,e),this.isInstancedInterleavedBuffer=!0,this.meshPerAttribute=n}copy(t){return super.copy(t),this.meshPerAttribute=t.meshPerAttribute,this}clone(t){const e=super.clone(t);return e.meshPerAttribute=this.meshPerAttribute,e}toJSON(t){const e=super.toJSON(t);return e.isInstancedInterleavedBuffer=!0,e.meshPerAttribute=this.meshPerAttribute,e}},e.InstancedMesh=Xo,e.Int16BufferAttribute=class extends fi{constructor(t,e,n){super(new Int16Array(t),e,n)}},e.Int32BufferAttribute=class extends fi{constructor(t,e,n){super(new Int32Array(t),e,n)}},e.Int8BufferAttribute=class extends fi{constructor(t,e,n){super(new Int8Array(t),e,n)}},e.IntType=A,e.InterleavedBuffer=Qa,e.InterleavedBufferAttribute=eo,e.Interpolant=vh,e.InterpolateDiscrete=Tt,e.InterpolateLinear=Et,e.InterpolateSmooth=At,e.InvertStencilOp=5386,e.KeepStencilOp=Vt,e.KeyframeTrack=Mh,e.LOD=Mo,e.LatheGeometry=ec,e.Layers=Sn,e.LessCompare=513,e.LessDepth=2,e.LessEqualCompare=515,e.LessEqualDepth=3,e.LessEqualStencilFunc=515,e.LessStencilFunc=513,e.Light=zh,e.LightProbe=iu,e.Line=yl,e.Line3=class{constructor(t=new De,e=new De){this.start=t,this.end=e}set(t,e){return this.start.copy(t),this.end.copy(e),this}copy(t){return this.start.copy(t.start),this.end.copy(t.end),this}getCenter(t){return t.addVectors(this.start,this.end).multiplyScalar(.5)}delta(t){return t.subVectors(this.end,this.start)}distanceSq(){return this.start.distanceToSquared(this.end)}distance(){return this.start.distanceTo(this.end)}at(t,e){return this.delta(e).multiplyScalar(t).add(this.start)}closestPointToPointParameter(t,e){Wu.subVectors(t,this.start),Xu.subVectors(this.end,this.start);const n=Xu.dot(Xu);let i=Xu.dot(Wu)/n;return e&&(i=$t(i,0,1)),i}closestPointToPoint(t,e,n){const i=this.closestPointToPointParameter(t,e);return this.delta(n).multiplyScalar(i).add(this.start)}applyMatrix4(t){return this.start.applyMatrix4(t),this.end.applyMatrix4(t),this}equals(t){return t.start.equals(this.start)&&t.end.equals(this.end)}clone(){return(new this.constructor).copy(this)}},e.LineBasicMaterial=ul,e.LineCurve=ql,e.LineCurve3=Yl,e.LineDashedMaterial=hh,e.LineLoop=wl,e.LineSegments=bl,e.LinearDisplayP3ColorSpace=Ot,e.LinearFilter=x,e.LinearInterpolant=yh,e.LinearMipMapLinearFilter=1008,e.LinearMipMapNearestFilter=1007,e.LinearMipmapLinearFilter=S,e.LinearMipmapNearestFilter=M,e.LinearSRGBColorSpace=Dt,e.LinearToneMapping=1,e.LinearTransfer=Ft,e.Loader=Dh,e.LoaderUtils=su,e.LoadingManager=Lh,e.LoopOnce=2200,e.LoopPingPong=2202,e.LoopRepeat=2201,e.LuminanceAlphaFormat=z,e.LuminanceFormat=B,e.MOUSE={LEFT:0,MIDDLE:1,RIGHT:2,ROTATE:0,DOLLY:1,PAN:2},e.Material=ai,e.MaterialLoader=ru,e.MathUtils=ie,e.Matrix2=Hu,e.Matrix3=se,e.Matrix4=un,e.MaxEquation=104,e.Mesh=Bi,e.MeshBasicMaterial=oi,e.MeshDepthMaterial=Ia,e.MeshDistanceMaterial=La,e.MeshLambertMaterial=lh,e.MeshMatcapMaterial=ch,e.MeshNormalMaterial=oh,e.MeshPhongMaterial=sh,e.MeshPhysicalMaterial=rh,e.MeshStandardMaterial=ih,e.MeshToonMaterial=ah,e.MinEquation=103,e.MirroredRepeatWrapping=g,e.MixOperation=1,e.MultiplyBlending=4,e.MultiplyOperation=0,e.NearestFilter=v,e.NearestMipMapLinearFilter=1005,e.NearestMipMapNearestFilter=1004,e.NearestMipmapLinearFilter=y,e.NearestMipmapNearestFilter=_,e.NeutralToneMapping=7,e.NeverCompare=512,e.NeverDepth=0,e.NeverStencilFunc=512,e.NoBlending=0,e.NoColorSpace=Lt,e.NoToneMapping=0,e.NormalAnimationBlendMode=2500,e.NormalBlending=1,e.NotEqualCompare=517,e.NotEqualDepth=7,e.NotEqualStencilFunc=517,e.NumberKeyframeTrack=wh,e.Object3D=Bn,e.ObjectLoader=class extends Dh{constructor(t){super(t)}load(t,e,n,i){const r=this,s=""===this.path?su.extractUrlBase(t):this.path;this.resourcePath=this.resourcePath||s;const a=new Fh(this.manager);a.setPath(this.path),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials),a.load(t,(function(n){let s=null;try{s=JSON.parse(n)}catch(e){return void 0!==i&&i(e),void console.error("THREE:ObjectLoader: Can't parse "+t+".",e.message)}const a=s.metadata;if(void 0===a||void 0===a.type||"geometry"===a.type.toLowerCase())return void 0!==i&&i(new Error("THREE.ObjectLoader: Can't load "+t)),void console.error("THREE.ObjectLoader: Can't load "+t);r.parse(s,e)}),n,i)}async loadAsync(t,e){const n=""===this.path?su.extractUrlBase(t):this.path;this.resourcePath=this.resourcePath||n;const i=new Fh(this.manager);i.setPath(this.path),i.setRequestHeader(this.requestHeader),i.setWithCredentials(this.withCredentials);const r=await i.loadAsync(t,e),s=JSON.parse(r),a=s.metadata;if(void 0===a||void 0===a.type||"geometry"===a.type.toLowerCase())throw new Error("THREE.ObjectLoader: Can't load "+t);return await this.parseAsync(s)}parse(t,e){const n=this.parseAnimations(t.animations),i=this.parseShapes(t.shapes),r=this.parseGeometries(t.geometries,i),s=this.parseImages(t.images,(function(){void 0!==e&&e(l)})),a=this.parseTextures(t.textures,s),o=this.parseMaterials(t.materials,a),l=this.parseObject(t.object,r,o,a,n),c=this.parseSkeletons(t.skeletons,l);if(this.bindSkeletons(l,c),this.bindLightTargets(l),void 0!==e){let t=!1;for(const e in s)if(s[e].data instanceof HTMLImageElement){t=!0;break}!1===t&&e(l)}return l}async parseAsync(t){const e=this.parseAnimations(t.animations),n=this.parseShapes(t.shapes),i=this.parseGeometries(t.geometries,n),r=await this.parseImagesAsync(t.images),s=this.parseTextures(t.textures,r),a=this.parseMaterials(t.materials,s),o=this.parseObject(t.object,i,a,s,e),l=this.parseSkeletons(t.skeletons,o);return this.bindSkeletons(o,l),this.bindLightTargets(o),o}parseShapes(t){const e={};if(void 0!==t)for(let n=0,i=t.length;n0){const n=new Lh(e);r=new Bh(n),r.setCrossOrigin(this.crossOrigin);for(let e=0,n=t.length;e0){i=new Bh(this.manager),i.setCrossOrigin(this.crossOrigin);for(let e=0,i=t.length;e{const e=new Fe;e.min.fromArray(t.boxMin),e.max.fromArray(t.boxMax);const n=new en;return n.radius=t.sphereRadius,n.center.fromArray(t.sphereCenter),{boxInitialized:t.boxInitialized,box:e,sphereInitialized:t.sphereInitialized,sphere:n}})),s._maxInstanceCount=t.maxInstanceCount,s._maxVertexCount=t.maxVertexCount,s._maxIndexCount=t.maxIndexCount,s._geometryInitialized=t.geometryInitialized,s._geometryCount=t.geometryCount,s._matricesTexture=h(t.matricesTexture.uuid),void 0!==t.colorsTexture&&(s._colorsTexture=h(t.colorsTexture.uuid));break;case"LOD":s=new Mo;break;case"Line":s=new yl(l(t.geometry),c(t.material));break;case"LineLoop":s=new wl(l(t.geometry),c(t.material));break;case"LineSegments":s=new bl(l(t.geometry),c(t.material));break;case"PointCloud":case"Points":s=new Pl(l(t.geometry),c(t.material));break;case"Sprite":s=new vo(c(t.material));break;case"Group":s=new Va;break;case"Bone":s=new Lo;break;default:s=new Bn}if(s.uuid=t.uuid,void 0!==t.name&&(s.name=t.name),void 0!==t.matrix?(s.matrix.fromArray(t.matrix),void 0!==t.matrixAutoUpdate&&(s.matrixAutoUpdate=t.matrixAutoUpdate),s.matrixAutoUpdate&&s.matrix.decompose(s.position,s.quaternion,s.scale)):(void 0!==t.position&&s.position.fromArray(t.position),void 0!==t.rotation&&s.rotation.fromArray(t.rotation),void 0!==t.quaternion&&s.quaternion.fromArray(t.quaternion),void 0!==t.scale&&s.scale.fromArray(t.scale)),void 0!==t.up&&s.up.fromArray(t.up),void 0!==t.castShadow&&(s.castShadow=t.castShadow),void 0!==t.receiveShadow&&(s.receiveShadow=t.receiveShadow),t.shadow&&(void 0!==t.shadow.intensity&&(s.shadow.intensity=t.shadow.intensity),void 0!==t.shadow.bias&&(s.shadow.bias=t.shadow.bias),void 0!==t.shadow.normalBias&&(s.shadow.normalBias=t.shadow.normalBias),void 0!==t.shadow.radius&&(s.shadow.radius=t.shadow.radius),void 0!==t.shadow.mapSize&&s.shadow.mapSize.fromArray(t.shadow.mapSize),void 0!==t.shadow.camera&&(s.shadow.camera=this.parseObject(t.shadow.camera))),void 0!==t.visible&&(s.visible=t.visible),void 0!==t.frustumCulled&&(s.frustumCulled=t.frustumCulled),void 0!==t.renderOrder&&(s.renderOrder=t.renderOrder),void 0!==t.userData&&(s.userData=t.userData),void 0!==t.layers&&(s.layers.mask=t.layers),void 0!==t.children){const a=t.children;for(let t=0;t1)for(let n=0;nNumber.EPSILON){if(l<0&&(n=e[s],o=-o,a=e[r],l=-l),t.ya.y)continue;if(t.y===n.y){if(t.x===n.x)return!0}else{const e=l*(t.x-n.x)-o*(t.y-n.y);if(0===e)return!0;if(e<0)continue;i=!i}}else{if(t.y!==n.y)continue;if(a.x<=t.x&&t.x<=n.x||n.x<=t.x&&t.x<=a.x)return!0}}return i}const n=Bc.isClockWise,i=this.subPaths;if(0===i.length)return[];let r,s,a;const o=[];if(1===i.length)return s=i[0],a=new pc,a.curves=s.curves,o.push(a),o;let l=!n(i[0].getPoints());l=t?!l:l;const c=[],h=[];let u,d,p=[],m=0;h[m]=void 0,p[m]=[];for(let e=0,a=i.length;e1){let t=!1,n=0;for(let t=0,e=h.length;t0&&!1===t&&(p=c)}for(let t=0,e=h.length;t=t.HAVE_CURRENT_DATA&&(this.needsUpdate=!0)}},e.WebGL3DRenderTarget=class extends Pe{constructor(t=1,e=1,n=1,i={}){super(t,e,i),this.isWebGL3DRenderTarget=!0,this.depth=n,this.texture=new Le(null,t,e,n),this.texture.isRenderTargetTexture=!0}},e.WebGLArrayRenderTarget=class extends Pe{constructor(t=1,e=1,n=1,i={}){super(t,e,i),this.isWebGLArrayRenderTarget=!0,this.depth=n,this.texture=new Ie(null,t,e,n),this.texture.isRenderTargetTexture=!0}},e.WebGLCoordinateSystem=Wt,e.WebGLCubeRenderTarget=tr,e.WebGLMultipleRenderTargets=class extends Pe{constructor(t=1,e=1,n=1,i={}){console.warn('THREE.WebGLMultipleRenderTargets has been deprecated and will be removed in r172. Use THREE.WebGLRenderTarget and set the "count" parameter to enable MRT.'),super(t,e,{...i,count:n}),this.isWebGLMultipleRenderTargets=!0}get texture(){return this.textures}},e.WebGLRenderTarget=Pe,e.WebGLRenderer=class{constructor(t={}){const{canvas:e=ue(),context:i=null,depth:r=!0,stencil:s=!1,alpha:a=!1,antialias:o=!1,premultipliedAlpha:l=!0,preserveDrawingBuffer:c=!1,powerPreference:h="default",failIfMajorPerformanceCaveat:u=!1}=t;let d;if(this.isWebGLRenderer=!0,null!==i){if("undefined"!=typeof WebGLRenderingContext&&i instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");d=i.getContextAttributes().alpha}else d=a;const p=new Uint32Array(4),m=new Int32Array(4);let f=null,g=null;const v=[],_=[];this.domElement=e,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this._outputColorSpace=Ut,this.toneMapping=0,this.toneMappingExposure=1;const y=this;let x=!1,M=0,w=0,T=null,A=-1,R=null;const D=new Ce,N=new Ce;let O=null;const F=new ii(0);let B=0,z=e.width,k=e.height,V=1,H=null,W=null;const q=new Ce(0,0,z,k),Y=new Ce(0,0,z,k);let Z=!1;const J=new or;let K=!1,$=!1;const Q=new un,tt=new un,et=new De,nt=new Ce,it={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let rt=!1;function st(){return null===T?V:1}let at,ot,lt,ct,ht,ut,dt,pt,mt,ft,gt,vt,_t,yt,xt,Mt,St,bt,wt,Tt,Et,At,Ct,Rt,Pt=i;function It(t,n){return e.getContext(t,n)}try{const t={alpha:!0,depth:r,stencil:s,antialias:o,premultipliedAlpha:l,preserveDrawingBuffer:c,powerPreference:h,failIfMajorPerformanceCaveat:u};if("setAttribute"in e&&e.setAttribute("data-engine",`three.js r${n}`),e.addEventListener("webglcontextlost",Ot,!1),e.addEventListener("webglcontextrestored",Ft,!1),e.addEventListener("webglcontextcreationerror",Bt,!1),null===Pt){const e="webgl2";if(Pt=It(e,t),null===Pt)throw It(e)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}}catch(t){throw console.error("THREE.WebGLRenderer: "+t.message),t}function Lt(){at=new kr(Pt),at.init(),At=new za(Pt,at),ot=new xr(Pt,at,t,At),lt=new Na(Pt),ot.reverseDepthBuffer&<.buffers.depth.setReversed(!0),ct=new Gr(Pt),ht=new xa,ut=new Ba(Pt,at,lt,ht,ot,At,ct),dt=new Sr(y),pt=new zr(y),mt=new cr(Pt),Ct=new _r(Pt,mt),ft=new Vr(Pt,mt,ct,Ct),gt=new Xr(Pt,ft,mt,ct),wt=new Wr(Pt,ot,ut),Mt=new Mr(ht),vt=new ya(y,dt,pt,at,ot,Ct,Mt),_t=new Ya(y,ht),yt=new wa,xt=new Pa(at),bt=new vr(y,dt,pt,lt,gt,d,l),St=new Ua(y,gt,ot),Rt=new Za(Pt,ct,ot,lt),Tt=new yr(Pt,at,ct),Et=new Hr(Pt,at,ct),ct.programs=vt.programs,y.capabilities=ot,y.extensions=at,y.properties=ht,y.renderLists=yt,y.shadowMap=St,y.state=lt,y.info=ct}Lt();const Nt=new Xa(y,Pt);function Ot(t){t.preventDefault(),console.log("THREE.WebGLRenderer: Context Lost."),x=!0}function Ft(){console.log("THREE.WebGLRenderer: Context Restored."),x=!1;const t=ct.autoReset,e=St.enabled,n=St.autoUpdate,i=St.needsUpdate,r=St.type;Lt(),ct.autoReset=t,St.enabled=e,St.autoUpdate=n,St.needsUpdate=i,St.type=r}function Bt(t){console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ",t.statusMessage)}function zt(t){const e=t.target;e.removeEventListener("dispose",zt),function(t){(function(t){const e=ht.get(t).programs;void 0!==e&&(e.forEach((function(t){vt.releaseProgram(t)})),t.isShaderMaterial&&vt.releaseShaderCache(t))})(t),ht.remove(t)}(e)}function kt(t,e,n){!0===t.transparent&&2===t.side&&!1===t.forceSinglePass?(t.side=1,t.needsUpdate=!0,Jt(t,e,n),t.side=0,t.needsUpdate=!0,Jt(t,e,n),t.side=2):Jt(t,e,n)}this.xr=Nt,this.getContext=function(){return Pt},this.getContextAttributes=function(){return Pt.getContextAttributes()},this.forceContextLoss=function(){const t=at.get("WEBGL_lose_context");t&&t.loseContext()},this.forceContextRestore=function(){const t=at.get("WEBGL_lose_context");t&&t.restoreContext()},this.getPixelRatio=function(){return V},this.setPixelRatio=function(t){void 0!==t&&(V=t,this.setSize(z,k,!1))},this.getSize=function(t){return t.set(z,k)},this.setSize=function(t,n,i=!0){Nt.isPresenting?console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting."):(z=t,k=n,e.width=Math.floor(t*V),e.height=Math.floor(n*V),!0===i&&(e.style.width=t+"px",e.style.height=n+"px"),this.setViewport(0,0,t,n))},this.getDrawingBufferSize=function(t){return t.set(z*V,k*V).floor()},this.setDrawingBufferSize=function(t,n,i){z=t,k=n,V=i,e.width=Math.floor(t*i),e.height=Math.floor(n*i),this.setViewport(0,0,t,n)},this.getCurrentViewport=function(t){return t.copy(D)},this.getViewport=function(t){return t.copy(q)},this.setViewport=function(t,e,n,i){t.isVector4?q.set(t.x,t.y,t.z,t.w):q.set(t,e,n,i),lt.viewport(D.copy(q).multiplyScalar(V).round())},this.getScissor=function(t){return t.copy(Y)},this.setScissor=function(t,e,n,i){t.isVector4?Y.set(t.x,t.y,t.z,t.w):Y.set(t,e,n,i),lt.scissor(N.copy(Y).multiplyScalar(V).round())},this.getScissorTest=function(){return Z},this.setScissorTest=function(t){lt.setScissorTest(Z=t)},this.setOpaqueSort=function(t){H=t},this.setTransparentSort=function(t){W=t},this.getClearColor=function(t){return t.copy(bt.getClearColor())},this.setClearColor=function(){bt.setClearColor.apply(bt,arguments)},this.getClearAlpha=function(){return bt.getClearAlpha()},this.setClearAlpha=function(){bt.setClearAlpha.apply(bt,arguments)},this.clear=function(t=!0,e=!0,n=!0){let i=0;if(t){let t=!1;if(null!==T){const e=T.texture.format;t=e===j||e===X||e===G}if(t){const t=T.texture.type,e=t===b||t===C||t===E||t===U||t===I||t===L,n=bt.getClearColor(),i=bt.getClearAlpha(),r=n.r,s=n.g,a=n.b;e?(p[0]=r,p[1]=s,p[2]=a,p[3]=i,Pt.clearBufferuiv(Pt.COLOR,0,p)):(m[0]=r,m[1]=s,m[2]=a,m[3]=i,Pt.clearBufferiv(Pt.COLOR,0,m))}else i|=Pt.COLOR_BUFFER_BIT}e&&(i|=Pt.DEPTH_BUFFER_BIT,Pt.clearDepth(this.capabilities.reverseDepthBuffer?0:1)),n&&(i|=Pt.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),Pt.clear(i)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.dispose=function(){e.removeEventListener("webglcontextlost",Ot,!1),e.removeEventListener("webglcontextrestored",Ft,!1),e.removeEventListener("webglcontextcreationerror",Bt,!1),yt.dispose(),xt.dispose(),ht.dispose(),dt.dispose(),pt.dispose(),gt.dispose(),Ct.dispose(),Rt.dispose(),vt.dispose(),Nt.dispose(),Nt.removeEventListener("sessionstart",Ht),Nt.removeEventListener("sessionend",Gt),Wt.stop()},this.renderBufferDirect=function(t,e,n,i,r,s){null===e&&(e=it);const a=r.isMesh&&r.matrixWorld.determinant()<0,o=function(t,e,n,i,r){!0!==e.isScene&&(e=it),ut.resetTextureUnits();const s=e.fog,a=i.isMeshStandardMaterial?e.environment:null,o=null===T?y.outputColorSpace:!0===T.isXRRenderTarget?T.texture.colorSpace:Dt,l=(i.isMeshStandardMaterial?pt:dt).get(i.envMap||a),c=!0===i.vertexColors&&!!n.attributes.color&&4===n.attributes.color.itemSize,h=!!n.attributes.tangent&&(!!i.normalMap||i.anisotropy>0),u=!!n.morphAttributes.position,d=!!n.morphAttributes.normal,p=!!n.morphAttributes.color;let m=0;i.toneMapped&&(null!==T&&!0!==T.isXRRenderTarget||(m=y.toneMapping));const f=n.morphAttributes.position||n.morphAttributes.normal||n.morphAttributes.color,v=void 0!==f?f.length:0,_=ht.get(i),x=g.state.lights;if(!0===K&&(!0===$||t!==R)){const e=t===R&&i.id===A;Mt.setState(i,t,e)}let M=!1;i.version===_.__version?_.needsLights&&_.lightsStateVersion!==x.state.version||_.outputColorSpace!==o||r.isBatchedMesh&&!1===_.batching?M=!0:r.isBatchedMesh||!0!==_.batching?r.isBatchedMesh&&!0===_.batchingColor&&null===r.colorTexture||r.isBatchedMesh&&!1===_.batchingColor&&null!==r.colorTexture||r.isInstancedMesh&&!1===_.instancing?M=!0:r.isInstancedMesh||!0!==_.instancing?r.isSkinnedMesh&&!1===_.skinning?M=!0:r.isSkinnedMesh||!0!==_.skinning?r.isInstancedMesh&&!0===_.instancingColor&&null===r.instanceColor||r.isInstancedMesh&&!1===_.instancingColor&&null!==r.instanceColor||r.isInstancedMesh&&!0===_.instancingMorph&&null===r.morphTexture||r.isInstancedMesh&&!1===_.instancingMorph&&null!==r.morphTexture||_.envMap!==l||!0===i.fog&&_.fog!==s?M=!0:void 0===_.numClippingPlanes||_.numClippingPlanes===Mt.numPlanes&&_.numIntersection===Mt.numIntersection?(_.vertexAlphas!==c||_.vertexTangents!==h||_.morphTargets!==u||_.morphNormals!==d||_.morphColors!==p||_.toneMapping!==m||_.morphTargetsCount!==v)&&(M=!0):M=!0:M=!0:M=!0:M=!0:(M=!0,_.__version=i.version);let S=_.currentProgram;!0===M&&(S=Jt(i,e,r));let b=!1,w=!1,E=!1;const C=S.getUniforms(),P=_.uniforms;if(lt.useProgram(S.program)&&(b=!0,w=!0,E=!0),i.id!==A&&(A=i.id,w=!0),b||R!==t){ot.reverseDepthBuffer?(Q.copy(t.projectionMatrix),function(t){const e=t.elements;e[2]=.5*e[2]+.5*e[3],e[6]=.5*e[6]+.5*e[7],e[10]=.5*e[10]+.5*e[11],e[14]=.5*e[14]+.5*e[15]}(Q),function(t){const e=t.elements;-1===e[11]?(e[10]=-e[10]-1,e[14]=-e[14]):(e[10]=-e[10],e[14]=1-e[14])}(Q),C.setValue(Pt,"projectionMatrix",Q)):C.setValue(Pt,"projectionMatrix",t.projectionMatrix),C.setValue(Pt,"viewMatrix",t.matrixWorldInverse);const e=C.map.cameraPosition;void 0!==e&&e.setValue(Pt,et.setFromMatrixPosition(t.matrixWorld)),ot.logarithmicDepthBuffer&&C.setValue(Pt,"logDepthBufFC",2/(Math.log(t.far+1)/Math.LN2)),(i.isMeshPhongMaterial||i.isMeshToonMaterial||i.isMeshLambertMaterial||i.isMeshBasicMaterial||i.isMeshStandardMaterial||i.isShaderMaterial)&&C.setValue(Pt,"isOrthographic",!0===t.isOrthographicCamera),R!==t&&(R=t,w=!0,E=!0)}if(r.isSkinnedMesh){C.setOptional(Pt,r,"bindMatrix"),C.setOptional(Pt,r,"bindMatrixInverse");const t=r.skeleton;t&&(null===t.boneTexture&&t.computeBoneTexture(),C.setValue(Pt,"boneTexture",t.boneTexture,ut))}r.isBatchedMesh&&(C.setOptional(Pt,r,"batchingTexture"),C.setValue(Pt,"batchingTexture",r._matricesTexture,ut),C.setOptional(Pt,r,"batchingIdTexture"),C.setValue(Pt,"batchingIdTexture",r._indirectTexture,ut),C.setOptional(Pt,r,"batchingColorTexture"),null!==r._colorsTexture&&C.setValue(Pt,"batchingColorTexture",r._colorsTexture,ut));const I=n.morphAttributes;var L,U;if(void 0===I.position&&void 0===I.normal&&void 0===I.color||wt.update(r,n,S),(w||_.receiveShadow!==r.receiveShadow)&&(_.receiveShadow=r.receiveShadow,C.setValue(Pt,"receiveShadow",r.receiveShadow)),i.isMeshGouraudMaterial&&null!==i.envMap&&(P.envMap.value=l,P.flipEnvMap.value=l.isCubeTexture&&!1===l.isRenderTargetTexture?-1:1),i.isMeshStandardMaterial&&null===i.envMap&&null!==e.environment&&(P.envMapIntensity.value=e.environmentIntensity),w&&(C.setValue(Pt,"toneMappingExposure",y.toneMappingExposure),_.needsLights&&(U=E,(L=P).ambientLightColor.needsUpdate=U,L.lightProbe.needsUpdate=U,L.directionalLights.needsUpdate=U,L.directionalLightShadows.needsUpdate=U,L.pointLights.needsUpdate=U,L.pointLightShadows.needsUpdate=U,L.spotLights.needsUpdate=U,L.spotLightShadows.needsUpdate=U,L.rectAreaLights.needsUpdate=U,L.hemisphereLights.needsUpdate=U),s&&!0===i.fog&&_t.refreshFogUniforms(P,s),_t.refreshMaterialUniforms(P,i,V,k,g.state.transmissionRenderTarget[t.id]),Ks.upload(Pt,Kt(_),P,ut)),i.isShaderMaterial&&!0===i.uniformsNeedUpdate&&(Ks.upload(Pt,Kt(_),P,ut),i.uniformsNeedUpdate=!1),i.isSpriteMaterial&&C.setValue(Pt,"center",r.center),C.setValue(Pt,"modelViewMatrix",r.modelViewMatrix),C.setValue(Pt,"normalMatrix",r.normalMatrix),C.setValue(Pt,"modelMatrix",r.matrixWorld),i.isShaderMaterial||i.isRawShaderMaterial){const t=i.uniformsGroups;for(let e=0,n=t.length;e{function n(){i.forEach((function(t){ht.get(t).currentProgram.isReady()&&i.delete(t)})),0!==i.size?setTimeout(n,10):e(t)}null!==at.get("KHR_parallel_shader_compile")?n():setTimeout(n,10)}))};let Vt=null;function Ht(){Wt.stop()}function Gt(){Wt.start()}const Wt=new lr;function Xt(t,e,n,i){if(!1===t.visible)return;if(t.layers.test(e.layers))if(t.isGroup)n=t.renderOrder;else if(t.isLOD)!0===t.autoUpdate&&t.update(e);else if(t.isLight)g.pushLight(t),t.castShadow&&g.pushShadow(t);else if(t.isSprite){if(!t.frustumCulled||J.intersectsSprite(t)){i&&nt.setFromMatrixPosition(t.matrixWorld).applyMatrix4(tt);const e=gt.update(t),r=t.material;r.visible&&f.push(t,e,r,n,nt.z,null)}}else if((t.isMesh||t.isLine||t.isPoints)&&(!t.frustumCulled||J.intersectsObject(t))){const e=gt.update(t),r=t.material;if(i&&(void 0!==t.boundingSphere?(null===t.boundingSphere&&t.computeBoundingSphere(),nt.copy(t.boundingSphere.center)):(null===e.boundingSphere&&e.computeBoundingSphere(),nt.copy(e.boundingSphere.center)),nt.applyMatrix4(t.matrixWorld).applyMatrix4(tt)),Array.isArray(r)){const i=e.groups;for(let s=0,a=i.length;s0&&Yt(r,e,n),s.length>0&&Yt(s,e,n),a.length>0&&Yt(a,e,n),lt.buffers.depth.setTest(!0),lt.buffers.depth.setMask(!0),lt.buffers.color.setMask(!0),lt.setPolygonOffset(!1)}function qt(t,e,n,i){if(null!==(!0===n.isScene?n.overrideMaterial:null))return;void 0===g.state.transmissionRenderTarget[i.id]&&(g.state.transmissionRenderTarget[i.id]=new Pe(1,1,{generateMipmaps:!0,type:at.has("EXT_color_buffer_half_float")||at.has("EXT_color_buffer_float")?P:b,minFilter:S,samples:4,stencilBuffer:s,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:_e.workingColorSpace}));const r=g.state.transmissionRenderTarget[i.id],a=i.viewport||D;r.setSize(a.z,a.w);const o=y.getRenderTarget();y.setRenderTarget(r),y.getClearColor(F),B=y.getClearAlpha(),B<1&&y.setClearColor(16777215,.5),y.clear(),rt&&bt.render(n);const l=y.toneMapping;y.toneMapping=0;const c=i.viewport;if(void 0!==i.viewport&&(i.viewport=void 0),g.setupLightsView(i),!0===K&&Mt.setGlobalState(y.clippingPlanes,i),Yt(t,n,i),ut.updateMultisampleRenderTarget(r),ut.updateRenderTargetMipmap(r),!1===at.has("WEBGL_multisampled_render_to_texture")){let t=!1;for(let r=0,s=e.length;r0)for(let e=0,s=n.length;e0&&qt(i,r,t,e),rt&&bt.render(t),jt(f,t,e);null!==T&&(ut.updateMultisampleRenderTarget(T),ut.updateRenderTargetMipmap(T)),!0===t.isScene&&t.onAfterRender(y,t,e),Ct.resetDefaultState(),A=-1,R=null,_.pop(),_.length>0?(g=_[_.length-1],!0===K&&Mt.setGlobalState(y.clippingPlanes,g.state.camera)):g=null,v.pop(),f=v.length>0?v[v.length-1]:null},this.getActiveCubeFace=function(){return M},this.getActiveMipmapLevel=function(){return w},this.getRenderTarget=function(){return T},this.setRenderTargetTextures=function(t,e,n){ht.get(t.texture).__webglTexture=e,ht.get(t.depthTexture).__webglTexture=n;const i=ht.get(t);i.__hasExternalTextures=!0,i.__autoAllocateDepthBuffer=void 0===n,i.__autoAllocateDepthBuffer||!0===at.has("WEBGL_multisampled_render_to_texture")&&(console.warn("THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided"),i.__useRenderToTexture=!1)},this.setRenderTargetFramebuffer=function(t,e){const n=ht.get(t);n.__webglFramebuffer=e,n.__useDefaultFramebuffer=void 0===e},this.setRenderTarget=function(t,e=0,n=0){T=t,M=e,w=n;let i=!0,r=null,s=!1,a=!1;if(t){const o=ht.get(t);if(void 0!==o.__useDefaultFramebuffer)lt.bindFramebuffer(Pt.FRAMEBUFFER,null),i=!1;else if(void 0===o.__webglFramebuffer)ut.setupRenderTarget(t);else if(o.__hasExternalTextures)ut.rebindTextures(t,ht.get(t.texture).__webglTexture,ht.get(t.depthTexture).__webglTexture);else if(t.depthBuffer){const e=t.depthTexture;if(o.__boundDepthTexture!==e){if(null!==e&&ht.has(e)&&(t.width!==e.image.width||t.height!==e.image.height))throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.");ut.setupDepthRenderbuffer(t)}}const l=t.texture;(l.isData3DTexture||l.isDataArrayTexture||l.isCompressedArrayTexture)&&(a=!0);const c=ht.get(t).__webglFramebuffer;t.isWebGLCubeRenderTarget?(r=Array.isArray(c[e])?c[e][n]:c[e],s=!0):r=t.samples>0&&!1===ut.useMultisampledRTT(t)?ht.get(t).__webglMultisampledFramebuffer:Array.isArray(c)?c[n]:c,D.copy(t.viewport),N.copy(t.scissor),O=t.scissorTest}else D.copy(q).multiplyScalar(V).floor(),N.copy(Y).multiplyScalar(V).floor(),O=Z;if(lt.bindFramebuffer(Pt.FRAMEBUFFER,r)&&i&<.drawBuffers(t,r),lt.viewport(D),lt.scissor(N),lt.setScissorTest(O),s){const i=ht.get(t.texture);Pt.framebufferTexture2D(Pt.FRAMEBUFFER,Pt.COLOR_ATTACHMENT0,Pt.TEXTURE_CUBE_MAP_POSITIVE_X+e,i.__webglTexture,n)}else if(a){const i=ht.get(t.texture),r=e||0;Pt.framebufferTextureLayer(Pt.FRAMEBUFFER,Pt.COLOR_ATTACHMENT0,i.__webglTexture,n||0,r)}A=-1},this.readRenderTargetPixels=function(t,e,n,i,r,s,a){if(!t||!t.isWebGLRenderTarget)return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let o=ht.get(t).__webglFramebuffer;if(t.isWebGLCubeRenderTarget&&void 0!==a&&(o=o[a]),o){lt.bindFramebuffer(Pt.FRAMEBUFFER,o);try{const a=t.texture,o=a.format,l=a.type;if(!ot.textureFormatReadable(o))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");if(!ot.textureTypeReadable(l))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");e>=0&&e<=t.width-i&&n>=0&&n<=t.height-r&&Pt.readPixels(e,n,i,r,At.convert(o),At.convert(l),s)}finally{const t=null!==T?ht.get(T).__webglFramebuffer:null;lt.bindFramebuffer(Pt.FRAMEBUFFER,t)}}},this.readRenderTargetPixelsAsync=async function(t,e,n,i,r,s,a){if(!t||!t.isWebGLRenderTarget)throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let o=ht.get(t).__webglFramebuffer;if(t.isWebGLCubeRenderTarget&&void 0!==a&&(o=o[a]),o){const a=t.texture,l=a.format,c=a.type;if(!ot.textureFormatReadable(l))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!ot.textureTypeReadable(c))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");if(e>=0&&e<=t.width-i&&n>=0&&n<=t.height-r){lt.bindFramebuffer(Pt.FRAMEBUFFER,o);const t=Pt.createBuffer();Pt.bindBuffer(Pt.PIXEL_PACK_BUFFER,t),Pt.bufferData(Pt.PIXEL_PACK_BUFFER,s.byteLength,Pt.STREAM_READ),Pt.readPixels(e,n,i,r,At.convert(l),At.convert(c),0);const a=null!==T?ht.get(T).__webglFramebuffer:null;lt.bindFramebuffer(Pt.FRAMEBUFFER,a);const h=Pt.fenceSync(Pt.SYNC_GPU_COMMANDS_COMPLETE,0);return Pt.flush(),await function(t,e,n){return new Promise((function(n,i){setTimeout((function r(){switch(t.clientWaitSync(e,t.SYNC_FLUSH_COMMANDS_BIT,0)){case t.WAIT_FAILED:i();break;case t.TIMEOUT_EXPIRED:setTimeout(r,4);break;default:n()}}),4)}))}(Pt,h),Pt.bindBuffer(Pt.PIXEL_PACK_BUFFER,t),Pt.getBufferSubData(Pt.PIXEL_PACK_BUFFER,0,s),Pt.deleteBuffer(t),Pt.deleteSync(h),s}throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")}},this.copyFramebufferToTexture=function(t,e=null,n=0){!0!==t.isTexture&&(pe("WebGLRenderer: copyFramebufferToTexture function signature has changed."),e=arguments[0]||null,t=arguments[1]);const i=Math.pow(2,-n),r=Math.floor(t.image.width*i),s=Math.floor(t.image.height*i),a=null!==e?e.x:0,o=null!==e?e.y:0;ut.setTexture2D(t,0),Pt.copyTexSubImage2D(Pt.TEXTURE_2D,n,0,0,a,o,r,s),lt.unbindTexture()},this.copyTextureToTexture=function(t,e,n=null,i=null,r=0){let s,a,o,l,c,h;!0!==t.isTexture&&(pe("WebGLRenderer: copyTextureToTexture function signature has changed."),i=arguments[0]||null,t=arguments[1],e=arguments[2],r=arguments[3]||0,n=null),null!==n?(s=n.max.x-n.min.x,a=n.max.y-n.min.y,o=n.min.x,l=n.min.y):(s=t.image.width,a=t.image.height,o=0,l=0),null!==i?(c=i.x,h=i.y):(c=0,h=0);const u=At.convert(e.format),d=At.convert(e.type);ut.setTexture2D(e,0),Pt.pixelStorei(Pt.UNPACK_FLIP_Y_WEBGL,e.flipY),Pt.pixelStorei(Pt.UNPACK_PREMULTIPLY_ALPHA_WEBGL,e.premultiplyAlpha),Pt.pixelStorei(Pt.UNPACK_ALIGNMENT,e.unpackAlignment);const p=Pt.getParameter(Pt.UNPACK_ROW_LENGTH),m=Pt.getParameter(Pt.UNPACK_IMAGE_HEIGHT),f=Pt.getParameter(Pt.UNPACK_SKIP_PIXELS),g=Pt.getParameter(Pt.UNPACK_SKIP_ROWS),v=Pt.getParameter(Pt.UNPACK_SKIP_IMAGES),_=t.isCompressedTexture?t.mipmaps[r]:t.image;Pt.pixelStorei(Pt.UNPACK_ROW_LENGTH,_.width),Pt.pixelStorei(Pt.UNPACK_IMAGE_HEIGHT,_.height),Pt.pixelStorei(Pt.UNPACK_SKIP_PIXELS,o),Pt.pixelStorei(Pt.UNPACK_SKIP_ROWS,l),t.isDataTexture?Pt.texSubImage2D(Pt.TEXTURE_2D,r,c,h,s,a,u,d,_.data):t.isCompressedTexture?Pt.compressedTexSubImage2D(Pt.TEXTURE_2D,r,c,h,_.width,_.height,u,_.data):Pt.texSubImage2D(Pt.TEXTURE_2D,r,c,h,s,a,u,d,_),Pt.pixelStorei(Pt.UNPACK_ROW_LENGTH,p),Pt.pixelStorei(Pt.UNPACK_IMAGE_HEIGHT,m),Pt.pixelStorei(Pt.UNPACK_SKIP_PIXELS,f),Pt.pixelStorei(Pt.UNPACK_SKIP_ROWS,g),Pt.pixelStorei(Pt.UNPACK_SKIP_IMAGES,v),0===r&&e.generateMipmaps&&Pt.generateMipmap(Pt.TEXTURE_2D),lt.unbindTexture()},this.copyTextureToTexture3D=function(t,e,n=null,i=null,r=0){let s,a,o,l,c,h,u,d,p;!0!==t.isTexture&&(pe("WebGLRenderer: copyTextureToTexture3D function signature has changed."),n=arguments[0]||null,i=arguments[1]||null,t=arguments[2],e=arguments[3],r=arguments[4]||0);const m=t.isCompressedTexture?t.mipmaps[r]:t.image;null!==n?(s=n.max.x-n.min.x,a=n.max.y-n.min.y,o=n.max.z-n.min.z,l=n.min.x,c=n.min.y,h=n.min.z):(s=m.width,a=m.height,o=m.depth,l=0,c=0,h=0),null!==i?(u=i.x,d=i.y,p=i.z):(u=0,d=0,p=0);const f=At.convert(e.format),g=At.convert(e.type);let v;if(e.isData3DTexture)ut.setTexture3D(e,0),v=Pt.TEXTURE_3D;else{if(!e.isDataArrayTexture&&!e.isCompressedArrayTexture)return void console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.");ut.setTexture2DArray(e,0),v=Pt.TEXTURE_2D_ARRAY}Pt.pixelStorei(Pt.UNPACK_FLIP_Y_WEBGL,e.flipY),Pt.pixelStorei(Pt.UNPACK_PREMULTIPLY_ALPHA_WEBGL,e.premultiplyAlpha),Pt.pixelStorei(Pt.UNPACK_ALIGNMENT,e.unpackAlignment);const _=Pt.getParameter(Pt.UNPACK_ROW_LENGTH),y=Pt.getParameter(Pt.UNPACK_IMAGE_HEIGHT),x=Pt.getParameter(Pt.UNPACK_SKIP_PIXELS),M=Pt.getParameter(Pt.UNPACK_SKIP_ROWS),S=Pt.getParameter(Pt.UNPACK_SKIP_IMAGES);Pt.pixelStorei(Pt.UNPACK_ROW_LENGTH,m.width),Pt.pixelStorei(Pt.UNPACK_IMAGE_HEIGHT,m.height),Pt.pixelStorei(Pt.UNPACK_SKIP_PIXELS,l),Pt.pixelStorei(Pt.UNPACK_SKIP_ROWS,c),Pt.pixelStorei(Pt.UNPACK_SKIP_IMAGES,h),t.isDataTexture||t.isData3DTexture?Pt.texSubImage3D(v,r,u,d,p,s,a,o,f,g,m.data):e.isCompressedArrayTexture?Pt.compressedTexSubImage3D(v,r,u,d,p,s,a,o,f,m.data):Pt.texSubImage3D(v,r,u,d,p,s,a,o,f,g,m),Pt.pixelStorei(Pt.UNPACK_ROW_LENGTH,_),Pt.pixelStorei(Pt.UNPACK_IMAGE_HEIGHT,y),Pt.pixelStorei(Pt.UNPACK_SKIP_PIXELS,x),Pt.pixelStorei(Pt.UNPACK_SKIP_ROWS,M),Pt.pixelStorei(Pt.UNPACK_SKIP_IMAGES,S),0===r&&e.generateMipmaps&&Pt.generateMipmap(v),lt.unbindTexture()},this.initRenderTarget=function(t){void 0===ht.get(t).__webglFramebuffer&&ut.setupRenderTarget(t)},this.initTexture=function(t){t.isCubeTexture?ut.setTextureCube(t,0):t.isData3DTexture?ut.setTexture3D(t,0):t.isDataArrayTexture||t.isCompressedArrayTexture?ut.setTexture2DArray(t,0):ut.setTexture2D(t,0),lt.unbindTexture()},this.resetState=function(){M=0,w=0,T=null,lt.reset(),Ct.reset()},"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return Wt}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(t){this._outputColorSpace=t;const e=this.getContext();e.drawingBufferColorSpace=t===Nt?"display-p3":"srgb",e.unpackColorSpace=_e.workingColorSpace===Ot?"display-p3":"srgb"}},e.WebGLUtils=za,e.WebGPUCoordinateSystem=Xt,e.WireframeGeometry=$c,e.WrapAroundEnding=Pt,e.ZeroCurvatureEnding=Ct,e.ZeroFactor=200,e.ZeroSlopeEnding=Rt,e.ZeroStencilOp=0,e.createCanvasElement=ue}},s={};function a(t){var e=s[t];if(void 0!==e)return e.exports;var n=s[t]={id:t,exports:{}};return r[t].call(n.exports,n,n.exports,a),n.exports}return a.m=r,a.n=t=>{var e=t&&t.__esModule?()=>t.default:()=>t;return a.d(e,{a:e}),e},a.d=(t,e)=>{for(var n in e)a.o(e,n)&&!a.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:e[n]})},a.f={},a.e=t=>Promise.all(Object.keys(a.f).reduce(((e,n)=>(a.f[n](t,e),e)),[])),a.u=t=>t+".index.js",a.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),n={},i="FileViewer:",a.l=(t,e,r,s)=>{if(n[t])n[t].push(e);else{var o,l;if(void 0!==r)for(var c=document.getElementsByTagName("script"),h=0;h{o.onerror=o.onload=null,clearTimeout(p);var r=n[t];if(delete n[t],o.parentNode&&o.parentNode.removeChild(o),r&&r.forEach((t=>t(i))),e)return e(i)},p=setTimeout(d.bind(null,void 0,{type:"timeout",target:o}),12e4);o.onerror=d.bind(null,o.onerror),o.onload=d.bind(null,o.onload),l&&document.head.appendChild(o)}},a.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},a.p="/",(()=>{a.b=document.baseURI||self.location.href;var t={179:0};a.f.j=(e,n)=>{var i=a.o(t,e)?t[e]:void 0;if(0!==i)if(i)n.push(i[2]);else{var r=new Promise(((n,r)=>i=t[e]=[n,r]));n.push(i[2]=r);var s=a.p+a.u(e),o=new Error;a.l(s,(n=>{if(a.o(t,e)&&(0!==(i=t[e])&&(t[e]=void 0),i)){var r=n&&("load"===n.type?"missing":n.type),s=n&&n.target&&n.target.src;o.message="Loading chunk "+e+" failed.\n("+r+": "+s+")",o.name="ChunkLoadError",o.type=r,o.request=s,i[1](o)}}),"chunk-"+e,e)}};var e=(e,n)=>{var i,r,[s,o,l]=n,c=0;if(s.some((e=>0!==t[e]))){for(i in o)a.o(o,i)&&(a.m[i]=o[i]);l&&l(a)}for(e&&e(n);c(()=>{var e,n,i,r={154:t=>{function e(){return t.exports=e=Object.assign||function(t){for(var e=1;e{t.exports=function(t){return t&&t.__esModule?t:{default:t}}},85:(t,e,n)=>{"use strict";var i=n(318);Object.defineProperty(e,"__esModule",{value:!0}),e.default=e.PDFPage=void 0;var r=i(n(787));class s extends r.default.Component{constructor(t){super(t),this.canvas=r.default.createRef(),this.state={isVisible:!0},this.renderTask=null}componentDidMount(){this.props.disableVisibilityCheck||(this.observer=new IntersectionObserver((([t])=>{t.target===this.canvas.current&&this.setState({isVisible:t.isIntersecting})})),this.canvas.current&&this.observer.observe(this.canvas.current)),this.fetchAndRenderPage()}componentDidUpdate(t){this.props.disableVisibilityCheck?t.zoom===this.props.zoom&&t.rotation===this.props.rotation||this.fetchAndRenderPage():t.zoom===this.props.zoom&&t.rotation===this.props.rotation&&t.index===this.props.index&&t.isVisible===this.state.isVisible||this.fetchAndRenderPage()}componentWillUnmount(){this.observer&&this.observer.disconnect(),this.renderTask&&(this.renderTask.cancel(),this.renderTask=null)}fetchAndRenderPage(){if(this.renderTask&&(this.renderTask.cancel(),this.renderTask=null),this.props.disableVisibilityCheck||this.state.isVisible){const{pdf:t,index:e}=this.props;t.getPage(e).then(this.renderPage.bind(this)).catch((t=>{console.error(`Error fetching page ${e}:`,t)}))}}renderPage(t){try{const{containerWidth:e,zoom:n,rotation:i}=this.props,r=e/t.getViewport({scale:1.1}).width,s=(r>1.1?1.1:r)+.2*n,a=t.getViewport({scale:s,rotation:i}),{width:o,height:l}=a,c=this.canvas.current,h=c.getContext("2d");c.width=o,c.height=l,this.renderTask=t.render({canvasContext:h,viewport:a}),this.renderTask.promise.then((()=>{this.renderTask=null})).catch((t=>{console.error(`Error rendering page ${this.props.index}:`,t)}))}catch(t){console.error(`Error rendering page ${this.props.index}:`,t)}}render(){const{index:t}=this.props;return r.default.createElement("div",{key:`page-${t}`,className:"pdf-canvas"},r.default.createElement("canvas",{ref:this.canvas,width:"670",height:"870"}))}}e.PDFPage=s;class a extends r.default.Component{constructor(t){super(t),this.state={pdf:null,zoom:0,percent:0,rotationValue:0},this.increaseZoom=this.increaseZoom.bind(this),this.reduceZoom=this.reduceZoom.bind(this),this.resetZoom=this.resetZoom.bind(this),this.rotateLeft=this.rotateLeft.bind(this),this.rotateRight=this.rotateRight.bind(this)}rotateLeft(){this.setState((t=>({rotationValue:(t.rotationValue-90+360)%360})))}rotateRight(){this.setState((t=>({rotationValue:(t.rotationValue+90)%360})))}componentDidMount(){(async()=>{const t=await n.e(840).then(n.bind(n,560)),{filePath:e}=this.props,i=this.container.offsetWidth,r=t.getDocument(e);r.onProgress=t=>{this.progressCallback(t)},r.promise.then((t=>{this.pdf&&this.pdf.destroy(),this.setState({pdf:t,containerWidth:i})})).catch((t=>{null!=typeof this.props.onError&&null!=this.props.onError?this.props.onError(t):console.error("Error loading PDF:",t)}))})()}componentWillUnmount(){this.pdf&&(this.pdf.destroy(),this.pdf=null)}componentDidUpdate(t){this.props.filePath!==t.filePath&&(this.pdf&&(this.pdf.destroy(),this.pdf=null),this.loadPdf())}setZoom(t){this.setState({zoom:t})}progressCallback(t){const e=(t.loaded/t.total*100).toFixed();this.setState({percent:e})}reduceZoom(){0!==this.state.zoom&&this.setZoom(this.state.zoom-1)}increaseZoom(){this.setZoom(this.state.zoom+1)}resetZoom(){this.setZoom(0)}renderPages(){const{pdf:t,containerWidth:e,zoom:n,rotationValue:i}=this.state;return t?[...Array(t.numPages).keys()].map((t=>t+1)).map(((a,o)=>r.default.createElement(s,{index:o+1,key:`pdfPage_${o}`,pdf:t,containerWidth:e,zoom:.2*n,rotation:i,disableVisibilityCheck:this.props.disableVisibilityCheck}))):null}renderLoading(){return this.state.pdf?null:r.default.createElement("div",{className:"pdf-loading"},"LOADING (",this.state.percent,"%)")}render(){const{renderControls:t}=this.props;return r.default.createElement("div",{className:"pdf-viewer-container"},t?t({handleZoomIn:this.increaseZoom,handleZoomOut:this.reduceZoom,handleRotateLeft:this.rotateLeft,handleRotateRight:this.rotateRight}):r.default.createElement("div",{className:"pdf-controls-container"},r.default.createElement("button",{type:"button",className:"view-control",onClick:this.increaseZoom},r.default.createElement("i",{className:"zoom-in"})),r.default.createElement("button",{type:"button",className:"view-control",onClick:this.resetZoom},r.default.createElement("i",{className:"zoom-reset"})),r.default.createElement("button",{type:"button",className:"view-control",onClick:this.reduceZoom},r.default.createElement("i",{className:"zoom-out"})),r.default.createElement("button",{type:"button",className:"view-control",onClick:this.rotateLeft},r.default.createElement("i",{className:"rotate-left"})),r.default.createElement("button",{type:"button",className:"view-control",onClick:this.rotateRight},r.default.createElement("i",{className:"rotate-right"}))),r.default.createElement("div",{className:"pdf-viewer",ref:t=>this.container=t},this.renderLoading(),this.renderPages()))}}e.default=a,a.defaultProps={disableVisibilityCheck:!1}},229:(t,e,n)=>{"use strict";var i=n(318);Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var r=i(n(154)),s=u(n(787)),a=u(n(232)),o=i(n(679)),l=i(n(908)),c=i(n(886));function h(t){if("function"!=typeof WeakMap)return null;var e=new WeakMap,n=new WeakMap;return(h=function(t){return t?n:e})(t)}function u(t,e){if(!e&&t&&t.__esModule)return t;if(null===t||"object"!=typeof t&&"function"!=typeof t)return{default:t};var n=h(e);if(n&&n.has(t))return n.get(t);var i={__proto__:null},r=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in t)if("default"!==s&&{}.hasOwnProperty.call(t,s)){var a=r?Object.getOwnPropertyDescriptor(t,s):null;a&&(a.get||a.set)?Object.defineProperty(i,s,a):i[s]=t[s]}return i.default=t,n&&n.set(t,i),i}class d extends s.Component{constructor(t){super(t),this.state={originalWidth:0,originalHeight:0,imageLoaded:!1}}componentDidMount(){const t=new a.TextureLoader;t.crossOrigin="";var e=this.props.onError;void 0!==e&&null!=e||(e=t=>{console.log("An error happened",t)}),t.load(this.props.filePath,(t=>{this.setState({originalWidth:t.image.width,originalHeight:t.image.height,imageLoaded:!0,texture:t})}),(t=>{console.log(t.loaded/t.total*100+"% loaded")}),e)}render(){if(!this.state.imageLoaded)return s.default.createElement(c.default,null);const{originalWidth:t,originalHeight:e}=this.state,n=(i=t,a=e,"jpg"===this.props.fileType&&window.Math.abs(i/a-2)<=.01?l.default:o.default);var i,a;return s.default.createElement(n,(0,r.default)({},this.state,this.props))}}e.default=d},679:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=function(t,e){if(t&&t.__esModule)return t;if(null===t||"object"!=typeof t&&"function"!=typeof t)return{default:t};var n=r(e);if(n&&n.has(t))return n.get(t);var i={__proto__:null},s=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var a in t)if("default"!==a&&{}.hasOwnProperty.call(t,a)){var o=s?Object.getOwnPropertyDescriptor(t,a):null;o&&(o.get||o.set)?Object.defineProperty(i,a,o):i[a]=t[a]}return i.default=t,n&&n.set(t,i),i}(n(787));function r(t){if("function"!=typeof WeakMap)return null;var e=new WeakMap,n=new WeakMap;return(r=function(t){return t?n:e})(t)}n(266);class s extends i.Component{constructor(t){super(t),this.state={zoom:10},this.increaseZoom=this.increaseZoom.bind(this),this.reduceZoom=this.reduceZoom.bind(this),this.rotateLeft=this.rotateLeft.bind(this),this.rotateRight=this.rotateRight.bind(this)}setZoom(t){this.setState({zoom:t})}increaseZoom(){const{zoom:t}=this.state;this.setZoom(t+1)}reduceZoom(){const{zoom:t}=this.state;t>1&&this.setZoom(t-1)}updateRotation(t){t>=0&&t<=3&&this.props.setRotationValue(t)}rotateLeft(){const t=(this.props.rotationValue+3)%4;this.updateRotation(t)}rotateRight(){const t=(this.props.rotationValue+1)%4;this.updateRotation(t)}componentDidMount(){const{originalWidth:t,originalHeight:e}=this.props,n=this.getImageDimensions.call(this,t,e);this.props.texture.image.style.width=`${n.width}px`,this.props.texture.image.style.height=`${n.height}px`,this.props.texture.image.style.transformOrigin="center center",this.props.texture.image.setAttribute("class","photo"),this.props.texture.image.setAttribute("z-index","0"),document.getElementById("photo-viewer-image-container").appendChild(this.props.texture.image)}componentWillUnmount(){const{texture:t}=this.props,e=t.image;e.parentNode&&e.parentNode.removeChild(e)}getImageDimensions(t,e){let n,i;const{height:r,width:s}=this.props;if(e<=r&&t<=s)i=t,n=e;else{const a=r/e,o=s/t;a{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=a(n(787)),r=a(n(232));function s(t){if("function"!=typeof WeakMap)return null;var e=new WeakMap,n=new WeakMap;return(s=function(t){return t?n:e})(t)}function a(t,e){if(!e&&t&&t.__esModule)return t;if(null===t||"object"!=typeof t&&"function"!=typeof t)return{default:t};var n=s(e);if(n&&n.has(t))return n.get(t);var i={__proto__:null},r=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var a in t)if("default"!==a&&{}.hasOwnProperty.call(t,a)){var o=r?Object.getOwnPropertyDescriptor(t,a):null;o&&(o.get||o.set)?Object.defineProperty(i,a,o):i[a]=t[a]}return i.default=t,n&&n.set(t,i),i}n(193);class o extends i.Component{constructor(t){super(t),this.onMouseDown=this.onMouseDown.bind(this),this.onMouseMove=this.onMouseMove.bind(this),this.onMouseUp=this.onMouseUp.bind(this),this.state={manualControl:!1,longitude:0,latitude:0,savedX:void 0,savedY:void 0,savedLongitude:void 0,savedLatitude:void 0}}componentDidMount(){const t=document.getElementById("360-photo"),e=t.getBoundingClientRect(),n=e.height,i=e.width;this.renderer=new r.WebGLRenderer,this.renderer.setSize(i,n),t.appendChild(this.renderer.domElement),this.scene=new r.Scene,this.camera=new r.PerspectiveCamera(75,i/n,1,1e3),this.camera.target=new r.Vector3(0,0,0),this.sphere=new r.SphereGeometry(100,100,40),this.sphere.applyMatrix((new r.Matrix4).makeScale(-1,1,1)),this.sphereMaterial=new r.MeshBasicMaterial,this.sphereMaterial.map=this.props.texture;const s=new r.Mesh(this.sphere,this.sphereMaterial);this.scene.add(s),this.updateView()}UNSAFE_componentWillUpdate(){this.updateView()}onMouseMove(t){const{savedX:e,savedY:n,savedLongitude:i,savedLatitude:r}=this.state;if(this.state.manualControl){const s=.1*(e-t.clientX)+i,a=.1*(t.clientY-n)+r;this.setState({longitude:s,latitude:a})}}onMouseUp(){this.setState({manualControl:!1})}onMouseDown(t){t.preventDefault(),this.setState({savedLongitude:this.state.longitude,savedLatitude:this.state.latitude,savedX:t.clientX,savedY:t.clientY,manualControl:!0})}updateView(){const t=Math.max(-85,Math.min(85,this.state.latitude));this.camera.target.x=500*Math.sin(r.MathUtils.degToRad(90-t)),Math.cos(r.MathUtils.degToRad(this.state.longitude)),this.camera.target.y=500*Math.cos(r.MathUtils.degToRad(90-t)),this.camera.target.z=500*Math.sin(r.MathUtils.degToRad(90-t))*Math.sin(r.MathUtils.degToRad(this.state.longitude)),this.camera.lookAt(this.camera.target),this.renderer.render(this.scene,this.camera)}render(){return i.default.createElement("div",{id:"360-photo",className:"photo360",onMouseDown:this.onMouseDown,onMouseMove:this.onMouseMove,onMouseUp:this.onMouseUp,role:"img"})}}e.default=o},282:(t,e,n)=>{"use strict";var i=n(318);Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var r=i(n(787));n(380),e.default=t=>r.default.createElement("div",{className:"pg-driver-view"},r.default.createElement("div",{className:"unsupported-message"},t.unsupportedComponent?r.default.createElement(t.unsupportedComponent,t):r.default.createElement("p",null,"No preview available for this kind of file.",r.default.createElement("br",null),"Download file to see the contents.")))},255:(t,e,n)=>{"use strict";var i=n(318);Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var r=i(n(154)),s=function(t,e){if(t&&t.__esModule)return t;if(null===t||"object"!=typeof t&&"function"!=typeof t)return{default:t};var n=h(e);if(n&&n.has(t))return n.get(t);var i={__proto__:null},r=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in t)if("default"!==s&&{}.hasOwnProperty.call(t,s)){var a=r?Object.getOwnPropertyDescriptor(t,s):null;a&&(a.get||a.set)?Object.defineProperty(i,s,a):i[s]=t[s]}return i.default=t,n&&n.set(t,i),i}(n(787)),a=i(n(697));n(192);var o=i(n(282)),l=i(n(85)),c=i(n(229));function h(t){if("function"!=typeof WeakMap)return null;var e=new WeakMap,n=new WeakMap;return(h=function(t){return t?n:e})(t)}class u extends s.Component{constructor(t){super(t),this.state={loading:!0}}componentDidMount(){const t=document.getElementById("pg-viewer"),e=t?t.clientHeight:0,n=t?t.clientWidth:0;this.setState({height:e,width:n})}getDriver(){switch(this.props.fileType){case"pdf":return l.default;case"jpg":case"jpeg":case"gif":case"png":return c.default;default:return o.default}}render(){const t=this.getDriver(this.props);return s.default.createElement("div",{className:"pg-viewer-wrapper"},s.default.createElement("div",{className:"pg-viewer",id:"pg-viewer"},s.default.createElement(t,(0,r.default)({},this.props,{width:this.state.width,height:this.state.height}))))}}u.displayName="FileViewer",u.propTypes={fileType:a.default.string.isRequired,filePath:a.default.string.isRequired,onError:a.default.func,errorComponent:a.default.element,unsupportedComponent:a.default.element},u.defaultProps={onError:()=>null,errorComponent:null,unsupportedComponent:null},e.default=u},352:(t,e,n)=>{"use strict";t.exports=n(255)},886:(t,e,n)=>{"use strict";var i=n(318);Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var r=i(n(787));n(269),e.default=()=>r.default.createElement("div",{className:"loading-container"},r.default.createElement("span",{className:"loading"}))},355:(t,e,n)=>{"use strict";n.r(e),n.d(e,{default:()=>d});var i=n(81),r=n.n(i),s=n(645),a=n.n(s),o=n(667),l=n.n(o),c=new URL(n(57),n.b),h=a()(r()),u=l()(c);h.push([t.id,".pg-viewer-wrapper .loading-container{-webkit-box-align:center;-ms-flex-align:center;align-items:center;display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-orient:horizontal;-webkit-box-direction:normal;-ms-flex-direction:row;flex-direction:row;height:100%;-webkit-box-pack:center;-ms-flex-pack:center;justify-content:center;width:100%}.pg-viewer-wrapper .loading-container .loading{background-image:url("+u+");background-repeat:no-repeat;display:inline-block;height:96px;width:96px;-webkit-animation:rotating 2s linear infinite;animation:rotating 2s linear infinite}@-webkit-keyframes rotating{from{-webkit-transform:rotate(0deg);transform:rotate(0deg)}to{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}@keyframes rotating{from{-webkit-transform:rotate(0deg);transform:rotate(0deg)}to{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}",""]);const d=h},329:(t,e,n)=>{"use strict";n.r(e),n.d(e,{default:()=>o});var i=n(81),r=n.n(i),s=n(645),a=n.n(s)()(r());a.push([t.id,".pg-viewer-wrapper{height:100%;display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-orient:horizontal;-webkit-box-direction:normal;-ms-flex-direction:row;flex-direction:row}.pg-viewer-wrapper .pg-viewer{height:100%;position:relative;-webkit-box-flex:2;-ms-flex-positive:2;flex-grow:2}.pg-viewer-wrapper .pg-viewer .pg-driver-view{margin:auto;width:100%;height:100%}.pg-viewer-wrapper .pg-viewer .pg-driver-view .loading{position:relative}.pg-viewer-wrapper .pg-viewer .pg-driver-view canvas,.pg-viewer-wrapper .pg-viewer .pg-driver-view .react-grid-Container{width:100%}.pg-viewer-wrapper .pg-viewer-link{background:#9370db;height:100%;-webkit-box-flex:1;-ms-flex-positive:1;flex-grow:1}.react-grid-Container{margin:auto}#xbim-viewer{height:100%;width:100%}#app{background:pink}",""]);const o=a},238:(t,e,n)=>{"use strict";n.r(e),n.d(e,{default:()=>o});var i=n(81),r=n.n(i),s=n(645),a=n.n(s)()(r());a.push([t.id,".pg-viewer-wrapper .photo-viewer-container{-webkit-box-align:center;-ms-flex-align:center;align-items:center;display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-orient:horizontal;-webkit-box-direction:normal;-ms-flex-direction:row;flex-direction:row;height:100%;-webkit-box-pack:center;-ms-flex-pack:center;justify-content:center;width:100%}",""]);const o=a},811:(t,e,n)=>{"use strict";n.r(e),n.d(e,{default:()=>o});var i=n(81),r=n.n(i),s=n(645),a=n.n(s)()(r());a.push([t.id,".photo360{height:100%;width:100%}",""]);const o=a},427:(t,e,n)=>{"use strict";n.r(e),n.d(e,{default:()=>o});var i=n(81),r=n.n(i),s=n(645),a=n.n(s)()(r());a.push([t.id,".unsupported-message{padding:46px;background:#dcdee0;color:#3d4551;margin:auto;text-align:center;height:100%;display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-align:center;-ms-flex-align:center;align-items:center;-webkit-box-pack:center;-ms-flex-pack:center;justify-content:center}",""]);const o=a},645:t=>{"use strict";t.exports=function(t){var e=[];return e.toString=function(){return this.map((function(e){var n="",i=void 0!==e[5];return e[4]&&(n+="@supports (".concat(e[4],") {")),e[2]&&(n+="@media ".concat(e[2]," {")),i&&(n+="@layer".concat(e[5].length>0?" ".concat(e[5]):""," {")),n+=t(e),i&&(n+="}"),e[2]&&(n+="}"),e[4]&&(n+="}"),n})).join("")},e.i=function(t,n,i,r,s){"string"==typeof t&&(t=[[null,t,void 0]]);var a={};if(i)for(var o=0;o0?" ".concat(h[5]):""," {").concat(h[1],"}")),h[5]=s),n&&(h[2]?(h[1]="@media ".concat(h[2]," {").concat(h[1],"}"),h[2]=n):h[2]=n),r&&(h[4]?(h[1]="@supports (".concat(h[4],") {").concat(h[1],"}"),h[4]=r):h[4]="".concat(r)),e.push(h))}},e}},667:t=>{"use strict";t.exports=function(t,e){return e||(e={}),t?(t=String(t.__esModule?t.default:t),/^['"].*['"]$/.test(t)&&(t=t.slice(1,-1)),e.hash&&(t+=e.hash),/["'() \t\n]|(%20)/.test(t)||e.needQuotes?'"'.concat(t.replace(/"/g,'\\"').replace(/\n/g,"\\n"),'"'):t):t}},81:t=>{"use strict";t.exports=function(t){return t[1]}},703:(t,e,n)=>{"use strict";var i=n(414);function r(){}function s(){}s.resetWarningCache=r,t.exports=function(){function t(t,e,n,r,s,a){if(a!==i){var o=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw o.name="Invariant Violation",o}}function e(){return t}t.isRequired=t;var n={array:t,bool:t,func:t,number:t,object:t,string:t,symbol:t,any:t,arrayOf:e,element:t,elementType:t,instanceOf:e,node:t,objectOf:e,oneOf:e,oneOfType:e,shape:e,exact:e,checkPropTypes:s,resetWarningCache:r};return n.PropTypes=n,n}},697:(t,e,n)=>{t.exports=n(703)()},414:t=>{"use strict";t.exports="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"},269:(t,e,n)=>{var i=n(379),r=n(355);"string"==typeof(r=r.__esModule?r.default:r)&&(r=[[t.id,r,""]]);i(r,{insert:"head",singleton:!1}),t.exports=r.locals||{}},192:(t,e,n)=>{var i=n(379),r=n(329);"string"==typeof(r=r.__esModule?r.default:r)&&(r=[[t.id,r,""]]);i(r,{insert:"head",singleton:!1}),t.exports=r.locals||{}},266:(t,e,n)=>{var i=n(379),r=n(238);"string"==typeof(r=r.__esModule?r.default:r)&&(r=[[t.id,r,""]]);i(r,{insert:"head",singleton:!1}),t.exports=r.locals||{}},193:(t,e,n)=>{var i=n(379),r=n(811);"string"==typeof(r=r.__esModule?r.default:r)&&(r=[[t.id,r,""]]);i(r,{insert:"head",singleton:!1}),t.exports=r.locals||{}},380:(t,e,n)=>{var i=n(379),r=n(427);"string"==typeof(r=r.__esModule?r.default:r)&&(r=[[t.id,r,""]]);i(r,{insert:"head",singleton:!1}),t.exports=r.locals||{}},379:(t,e,n)=>{"use strict";var i,r=function(){var t={};return function(e){if(void 0===t[e]){var n=document.querySelector(e);if(window.HTMLIFrameElement&&n instanceof window.HTMLIFrameElement)try{n=n.contentDocument.head}catch(t){n=null}t[e]=n}return t[e]}}(),s=[];function a(t){for(var e=-1,n=0;n{"use strict";t.exports=n.p+"28c58d40210ac28e2a3e.png"},787:e=>{"use strict";e.exports=t},232:(t,e)=>{"use strict";const n="169",i=100,r=204,s=205,a="attached",o="detached",l=300,c=301,h=302,u=303,d=304,p=306,m=1e3,f=1001,g=1002,v=1003,_=1004,x=1005,y=1006,M=1007,S=1008,b=1009,w=1010,T=1011,E=1012,A=1013,R=1014,C=1015,P=1016,I=1017,L=1018,U=1020,D=35902,N=1021,O=1022,F=1023,B=1024,z=1025,k=1026,V=1027,H=1028,G=1029,W=1030,X=1031,j=1033,q=33776,Y=33777,Z=33778,J=33779,K=35840,$=35841,Q=35842,tt=35843,et=36196,nt=37492,it=37496,rt=37808,st=37809,at=37810,ot=37811,lt=37812,ct=37813,ht=37814,ut=37815,dt=37816,pt=37817,mt=37818,ft=37819,gt=37820,vt=37821,_t=36492,xt=36494,yt=36495,Mt=36283,St=36284,bt=36285,wt=36286,Tt=2300,Et=2301,At=2302,Rt=2400,Ct=2401,Pt=2402,It=2501,Lt="",Ut="srgb",Dt="srgb-linear",Nt="display-p3",Ot="display-p3-linear",Ft="linear",Bt="srgb",zt="rec709",kt="p3",Vt=7680,Ht=35044,Gt="300 es",Wt=2e3,Xt=2001;class jt{addEventListener(t,e){void 0===this._listeners&&(this._listeners={});const n=this._listeners;void 0===n[t]&&(n[t]=[]),-1===n[t].indexOf(e)&&n[t].push(e)}hasEventListener(t,e){if(void 0===this._listeners)return!1;const n=this._listeners;return void 0!==n[t]&&-1!==n[t].indexOf(e)}removeEventListener(t,e){if(void 0===this._listeners)return;const n=this._listeners[t];if(void 0!==n){const t=n.indexOf(e);-1!==t&&n.splice(t,1)}}dispatchEvent(t){if(void 0===this._listeners)return;const e=this._listeners[t.type];if(void 0!==e){t.target=this;const n=e.slice(0);for(let e=0,i=n.length;e>8&255]+qt[t>>16&255]+qt[t>>24&255]+"-"+qt[255&e]+qt[e>>8&255]+"-"+qt[e>>16&15|64]+qt[e>>24&255]+"-"+qt[63&n|128]+qt[n>>8&255]+"-"+qt[n>>16&255]+qt[n>>24&255]+qt[255&i]+qt[i>>8&255]+qt[i>>16&255]+qt[i>>24&255]).toLowerCase()}function $t(t,e,n){return Math.max(e,Math.min(n,t))}function Qt(t,e){return(t%e+e)%e}function te(t,e,n){return(1-n)*t+n*e}function ee(t,e){switch(e.constructor){case Float32Array:return t;case Uint32Array:return t/4294967295;case Uint16Array:return t/65535;case Uint8Array:return t/255;case Int32Array:return Math.max(t/2147483647,-1);case Int16Array:return Math.max(t/32767,-1);case Int8Array:return Math.max(t/127,-1);default:throw new Error("Invalid component type.")}}function ne(t,e){switch(e.constructor){case Float32Array:return t;case Uint32Array:return Math.round(4294967295*t);case Uint16Array:return Math.round(65535*t);case Uint8Array:return Math.round(255*t);case Int32Array:return Math.round(2147483647*t);case Int16Array:return Math.round(32767*t);case Int8Array:return Math.round(127*t);default:throw new Error("Invalid component type.")}}const ie={DEG2RAD:Zt,RAD2DEG:Jt,generateUUID:Kt,clamp:$t,euclideanModulo:Qt,mapLinear:function(t,e,n,i,r){return i+(t-e)*(r-i)/(n-e)},inverseLerp:function(t,e,n){return t!==e?(n-t)/(e-t):0},lerp:te,damp:function(t,e,n,i){return te(t,e,1-Math.exp(-n*i))},pingpong:function(t,e=1){return e-Math.abs(Qt(t,2*e)-e)},smoothstep:function(t,e,n){return t<=e?0:t>=n?1:(t=(t-e)/(n-e))*t*(3-2*t)},smootherstep:function(t,e,n){return t<=e?0:t>=n?1:(t=(t-e)/(n-e))*t*t*(t*(6*t-15)+10)},randInt:function(t,e){return t+Math.floor(Math.random()*(e-t+1))},randFloat:function(t,e){return t+Math.random()*(e-t)},randFloatSpread:function(t){return t*(.5-Math.random())},seededRandom:function(t){void 0!==t&&(Yt=t);let e=Yt+=1831565813;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296},degToRad:function(t){return t*Zt},radToDeg:function(t){return t*Jt},isPowerOfTwo:function(t){return 0==(t&t-1)&&0!==t},ceilPowerOfTwo:function(t){return Math.pow(2,Math.ceil(Math.log(t)/Math.LN2))},floorPowerOfTwo:function(t){return Math.pow(2,Math.floor(Math.log(t)/Math.LN2))},setQuaternionFromProperEuler:function(t,e,n,i,r){const s=Math.cos,a=Math.sin,o=s(n/2),l=a(n/2),c=s((e+i)/2),h=a((e+i)/2),u=s((e-i)/2),d=a((e-i)/2),p=s((i-e)/2),m=a((i-e)/2);switch(r){case"XYX":t.set(o*h,l*u,l*d,o*c);break;case"YZY":t.set(l*d,o*h,l*u,o*c);break;case"ZXZ":t.set(l*u,l*d,o*h,o*c);break;case"XZX":t.set(o*h,l*m,l*p,o*c);break;case"YXY":t.set(l*p,o*h,l*m,o*c);break;case"ZYZ":t.set(l*m,l*p,o*h,o*c);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+r)}},normalize:ne,denormalize:ee};class re{constructor(t=0,e=0){re.prototype.isVector2=!0,this.x=t,this.y=e}get width(){return this.x}set width(t){this.x=t}get height(){return this.y}set height(t){this.y=t}set(t,e){return this.x=t,this.y=e,this}setScalar(t){return this.x=t,this.y=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y)}copy(t){return this.x=t.x,this.y=t.y,this}add(t){return this.x+=t.x,this.y+=t.y,this}addScalar(t){return this.x+=t,this.y+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this}subScalar(t){return this.x-=t,this.y-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this}multiply(t){return this.x*=t.x,this.y*=t.y,this}multiplyScalar(t){return this.x*=t,this.y*=t,this}divide(t){return this.x/=t.x,this.y/=t.y,this}divideScalar(t){return this.multiplyScalar(1/t)}applyMatrix3(t){const e=this.x,n=this.y,i=t.elements;return this.x=i[0]*e+i[3]*n+i[6],this.y=i[1]*e+i[4]*n+i[7],this}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this}clamp(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this}clampScalar(t,e){return this.x=Math.max(t,Math.min(e,this.x)),this.y=Math.max(t,Math.min(e,this.y)),this}clampLength(t,e){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Math.max(t,Math.min(e,n)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(t){return this.x*t.x+this.y*t.y}cross(t){return this.x*t.y-this.y*t.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(t){const e=Math.sqrt(this.lengthSq()*t.lengthSq());if(0===e)return Math.PI/2;const n=this.dot(t)/e;return Math.acos($t(n,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){const e=this.x-t.x,n=this.y-t.y;return e*e+n*n}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this}lerpVectors(t,e,n){return this.x=t.x+(e.x-t.x)*n,this.y=t.y+(e.y-t.y)*n,this}equals(t){return t.x===this.x&&t.y===this.y}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t}fromBufferAttribute(t,e){return this.x=t.getX(e),this.y=t.getY(e),this}rotateAround(t,e){const n=Math.cos(e),i=Math.sin(e),r=this.x-t.x,s=this.y-t.y;return this.x=r*n-s*i+t.x,this.y=r*i+s*n+t.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class se{constructor(t,e,n,i,r,s,a,o,l){se.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],void 0!==t&&this.set(t,e,n,i,r,s,a,o,l)}set(t,e,n,i,r,s,a,o,l){const c=this.elements;return c[0]=t,c[1]=i,c[2]=a,c[3]=e,c[4]=r,c[5]=o,c[6]=n,c[7]=s,c[8]=l,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(t){const e=this.elements,n=t.elements;return e[0]=n[0],e[1]=n[1],e[2]=n[2],e[3]=n[3],e[4]=n[4],e[5]=n[5],e[6]=n[6],e[7]=n[7],e[8]=n[8],this}extractBasis(t,e,n){return t.setFromMatrix3Column(this,0),e.setFromMatrix3Column(this,1),n.setFromMatrix3Column(this,2),this}setFromMatrix4(t){const e=t.elements;return this.set(e[0],e[4],e[8],e[1],e[5],e[9],e[2],e[6],e[10]),this}multiply(t){return this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){const n=t.elements,i=e.elements,r=this.elements,s=n[0],a=n[3],o=n[6],l=n[1],c=n[4],h=n[7],u=n[2],d=n[5],p=n[8],m=i[0],f=i[3],g=i[6],v=i[1],_=i[4],x=i[7],y=i[2],M=i[5],S=i[8];return r[0]=s*m+a*v+o*y,r[3]=s*f+a*_+o*M,r[6]=s*g+a*x+o*S,r[1]=l*m+c*v+h*y,r[4]=l*f+c*_+h*M,r[7]=l*g+c*x+h*S,r[2]=u*m+d*v+p*y,r[5]=u*f+d*_+p*M,r[8]=u*g+d*x+p*S,this}multiplyScalar(t){const e=this.elements;return e[0]*=t,e[3]*=t,e[6]*=t,e[1]*=t,e[4]*=t,e[7]*=t,e[2]*=t,e[5]*=t,e[8]*=t,this}determinant(){const t=this.elements,e=t[0],n=t[1],i=t[2],r=t[3],s=t[4],a=t[5],o=t[6],l=t[7],c=t[8];return e*s*c-e*a*l-n*r*c+n*a*o+i*r*l-i*s*o}invert(){const t=this.elements,e=t[0],n=t[1],i=t[2],r=t[3],s=t[4],a=t[5],o=t[6],l=t[7],c=t[8],h=c*s-a*l,u=a*o-c*r,d=l*r-s*o,p=e*h+n*u+i*d;if(0===p)return this.set(0,0,0,0,0,0,0,0,0);const m=1/p;return t[0]=h*m,t[1]=(i*l-c*n)*m,t[2]=(a*n-i*s)*m,t[3]=u*m,t[4]=(c*e-i*o)*m,t[5]=(i*r-a*e)*m,t[6]=d*m,t[7]=(n*o-l*e)*m,t[8]=(s*e-n*r)*m,this}transpose(){let t;const e=this.elements;return t=e[1],e[1]=e[3],e[3]=t,t=e[2],e[2]=e[6],e[6]=t,t=e[5],e[5]=e[7],e[7]=t,this}getNormalMatrix(t){return this.setFromMatrix4(t).invert().transpose()}transposeIntoArray(t){const e=this.elements;return t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8],this}setUvTransform(t,e,n,i,r,s,a){const o=Math.cos(r),l=Math.sin(r);return this.set(n*o,n*l,-n*(o*s+l*a)+s+t,-i*l,i*o,-i*(-l*s+o*a)+a+e,0,0,1),this}scale(t,e){return this.premultiply(ae.makeScale(t,e)),this}rotate(t){return this.premultiply(ae.makeRotation(-t)),this}translate(t,e){return this.premultiply(ae.makeTranslation(t,e)),this}makeTranslation(t,e){return t.isVector2?this.set(1,0,t.x,0,1,t.y,0,0,1):this.set(1,0,t,0,1,e,0,0,1),this}makeRotation(t){const e=Math.cos(t),n=Math.sin(t);return this.set(e,-n,0,n,e,0,0,0,1),this}makeScale(t,e){return this.set(t,0,0,0,e,0,0,0,1),this}equals(t){const e=this.elements,n=t.elements;for(let t=0;t<9;t++)if(e[t]!==n[t])return!1;return!0}fromArray(t,e=0){for(let n=0;n<9;n++)this.elements[n]=t[n+e];return this}toArray(t=[],e=0){const n=this.elements;return t[e]=n[0],t[e+1]=n[1],t[e+2]=n[2],t[e+3]=n[3],t[e+4]=n[4],t[e+5]=n[5],t[e+6]=n[6],t[e+7]=n[7],t[e+8]=n[8],t}clone(){return(new this.constructor).fromArray(this.elements)}}const ae=new se;function oe(t){for(let e=t.length-1;e>=0;--e)if(t[e]>=65535)return!0;return!1}const le={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array};function ce(t,e){return new le[t](e)}function he(t){return document.createElementNS("http://www.w3.org/1999/xhtml",t)}function ue(){const t=he("canvas");return t.style.display="block",t}const de={};function pe(t){t in de||(de[t]=!0,console.warn(t))}const me=(new se).set(.8224621,.177538,0,.0331941,.9668058,0,.0170827,.0723974,.9105199),fe=(new se).set(1.2249401,-.2249404,0,-.0420569,1.0420571,0,-.0196376,-.0786361,1.0982735),ge={[Dt]:{transfer:Ft,primaries:zt,luminanceCoefficients:[.2126,.7152,.0722],toReference:t=>t,fromReference:t=>t},[Ut]:{transfer:Bt,primaries:zt,luminanceCoefficients:[.2126,.7152,.0722],toReference:t=>t.convertSRGBToLinear(),fromReference:t=>t.convertLinearToSRGB()},[Ot]:{transfer:Ft,primaries:kt,luminanceCoefficients:[.2289,.6917,.0793],toReference:t=>t.applyMatrix3(fe),fromReference:t=>t.applyMatrix3(me)},[Nt]:{transfer:Bt,primaries:kt,luminanceCoefficients:[.2289,.6917,.0793],toReference:t=>t.convertSRGBToLinear().applyMatrix3(fe),fromReference:t=>t.applyMatrix3(me).convertLinearToSRGB()}},ve=new Set([Dt,Ot]),_e={enabled:!0,_workingColorSpace:Dt,get workingColorSpace(){return this._workingColorSpace},set workingColorSpace(t){if(!ve.has(t))throw new Error(`Unsupported working color space, "${t}".`);this._workingColorSpace=t},convert:function(t,e,n){if(!1===this.enabled||e===n||!e||!n)return t;const i=ge[e].toReference;return(0,ge[n].fromReference)(i(t))},fromWorkingColorSpace:function(t,e){return this.convert(t,this._workingColorSpace,e)},toWorkingColorSpace:function(t,e){return this.convert(t,e,this._workingColorSpace)},getPrimaries:function(t){return ge[t].primaries},getTransfer:function(t){return t===Lt?Ft:ge[t].transfer},getLuminanceCoefficients:function(t,e=this._workingColorSpace){return t.fromArray(ge[e].luminanceCoefficients)}};function xe(t){return t<.04045?.0773993808*t:Math.pow(.9478672986*t+.0521327014,2.4)}function ye(t){return t<.0031308?12.92*t:1.055*Math.pow(t,.41666)-.055}let Me;class Se{static getDataURL(t){if(/^data:/i.test(t.src))return t.src;if("undefined"==typeof HTMLCanvasElement)return t.src;let e;if(t instanceof HTMLCanvasElement)e=t;else{void 0===Me&&(Me=he("canvas")),Me.width=t.width,Me.height=t.height;const n=Me.getContext("2d");t instanceof ImageData?n.putImageData(t,0,0):n.drawImage(t,0,0,t.width,t.height),e=Me}return e.width>2048||e.height>2048?(console.warn("THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons",t),e.toDataURL("image/jpeg",.6)):e.toDataURL("image/png")}static sRGBToLinear(t){if("undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&t instanceof ImageBitmap){const e=he("canvas");e.width=t.width,e.height=t.height;const n=e.getContext("2d");n.drawImage(t,0,0,t.width,t.height);const i=n.getImageData(0,0,t.width,t.height),r=i.data;for(let t=0;t0&&(n.userData=this.userData),e||(t.textures[this.uuid]=n),n}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(t){if(this.mapping!==l)return t;if(t.applyMatrix3(this.matrix),t.x<0||t.x>1)switch(this.wrapS){case m:t.x=t.x-Math.floor(t.x);break;case f:t.x=t.x<0?0:1;break;case g:1===Math.abs(Math.floor(t.x)%2)?t.x=Math.ceil(t.x)-t.x:t.x=t.x-Math.floor(t.x)}if(t.y<0||t.y>1)switch(this.wrapT){case m:t.y=t.y-Math.floor(t.y);break;case f:t.y=t.y<0?0:1;break;case g:1===Math.abs(Math.floor(t.y)%2)?t.y=Math.ceil(t.y)-t.y:t.y=t.y-Math.floor(t.y)}return this.flipY&&(t.y=1-t.y),t}set needsUpdate(t){!0===t&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(t){!0===t&&this.pmremVersion++}}Ae.DEFAULT_IMAGE=null,Ae.DEFAULT_MAPPING=l,Ae.DEFAULT_ANISOTROPY=1;class Re{constructor(t=0,e=0,n=0,i=1){Re.prototype.isVector4=!0,this.x=t,this.y=e,this.z=n,this.w=i}get width(){return this.z}set width(t){this.z=t}get height(){return this.w}set height(t){this.w=t}set(t,e,n,i){return this.x=t,this.y=e,this.z=n,this.w=i,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this.w=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setW(t){return this.w=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;case 3:this.w=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=void 0!==t.w?t.w:1,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this.w+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this.w=t.w+e.w,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this.w+=t.w*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this.w-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this.w=t.w-e.w,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this}applyMatrix4(t){const e=this.x,n=this.y,i=this.z,r=this.w,s=t.elements;return this.x=s[0]*e+s[4]*n+s[8]*i+s[12]*r,this.y=s[1]*e+s[5]*n+s[9]*i+s[13]*r,this.z=s[2]*e+s[6]*n+s[10]*i+s[14]*r,this.w=s[3]*e+s[7]*n+s[11]*i+s[15]*r,this}divideScalar(t){return this.multiplyScalar(1/t)}setAxisAngleFromQuaternion(t){this.w=2*Math.acos(t.w);const e=Math.sqrt(1-t.w*t.w);return e<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=t.x/e,this.y=t.y/e,this.z=t.z/e),this}setAxisAngleFromRotationMatrix(t){let e,n,i,r;const s=.01,a=.1,o=t.elements,l=o[0],c=o[4],h=o[8],u=o[1],d=o[5],p=o[9],m=o[2],f=o[6],g=o[10];if(Math.abs(c-u)o&&t>v?tv?o=0?1:-1,i=1-e*e;if(i>Number.EPSILON){const r=Math.sqrt(i),s=Math.atan2(r,e*n);t=Math.sin(t*s)/r,a=Math.sin(a*s)/r}const r=a*n;if(o=o*t+u*r,l=l*t+d*r,c=c*t+p*r,h=h*t+m*r,t===1-a){const t=1/Math.sqrt(o*o+l*l+c*c+h*h);o*=t,l*=t,c*=t,h*=t}}t[e]=o,t[e+1]=l,t[e+2]=c,t[e+3]=h}static multiplyQuaternionsFlat(t,e,n,i,r,s){const a=n[i],o=n[i+1],l=n[i+2],c=n[i+3],h=r[s],u=r[s+1],d=r[s+2],p=r[s+3];return t[e]=a*p+c*h+o*d-l*u,t[e+1]=o*p+c*u+l*h-a*d,t[e+2]=l*p+c*d+a*u-o*h,t[e+3]=c*p-a*h-o*u-l*d,t}get x(){return this._x}set x(t){this._x=t,this._onChangeCallback()}get y(){return this._y}set y(t){this._y=t,this._onChangeCallback()}get z(){return this._z}set z(t){this._z=t,this._onChangeCallback()}get w(){return this._w}set w(t){this._w=t,this._onChangeCallback()}set(t,e,n,i){return this._x=t,this._y=e,this._z=n,this._w=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(t){return this._x=t.x,this._y=t.y,this._z=t.z,this._w=t.w,this._onChangeCallback(),this}setFromEuler(t,e=!0){const n=t._x,i=t._y,r=t._z,s=t._order,a=Math.cos,o=Math.sin,l=a(n/2),c=a(i/2),h=a(r/2),u=o(n/2),d=o(i/2),p=o(r/2);switch(s){case"XYZ":this._x=u*c*h+l*d*p,this._y=l*d*h-u*c*p,this._z=l*c*p+u*d*h,this._w=l*c*h-u*d*p;break;case"YXZ":this._x=u*c*h+l*d*p,this._y=l*d*h-u*c*p,this._z=l*c*p-u*d*h,this._w=l*c*h+u*d*p;break;case"ZXY":this._x=u*c*h-l*d*p,this._y=l*d*h+u*c*p,this._z=l*c*p+u*d*h,this._w=l*c*h-u*d*p;break;case"ZYX":this._x=u*c*h-l*d*p,this._y=l*d*h+u*c*p,this._z=l*c*p-u*d*h,this._w=l*c*h+u*d*p;break;case"YZX":this._x=u*c*h+l*d*p,this._y=l*d*h+u*c*p,this._z=l*c*p-u*d*h,this._w=l*c*h-u*d*p;break;case"XZY":this._x=u*c*h-l*d*p,this._y=l*d*h-u*c*p,this._z=l*c*p+u*d*h,this._w=l*c*h+u*d*p;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+s)}return!0===e&&this._onChangeCallback(),this}setFromAxisAngle(t,e){const n=e/2,i=Math.sin(n);return this._x=t.x*i,this._y=t.y*i,this._z=t.z*i,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(t){const e=t.elements,n=e[0],i=e[4],r=e[8],s=e[1],a=e[5],o=e[9],l=e[2],c=e[6],h=e[10],u=n+a+h;if(u>0){const t=.5/Math.sqrt(u+1);this._w=.25/t,this._x=(c-o)*t,this._y=(r-l)*t,this._z=(s-i)*t}else if(n>a&&n>h){const t=2*Math.sqrt(1+n-a-h);this._w=(c-o)/t,this._x=.25*t,this._y=(i+s)/t,this._z=(r+l)/t}else if(a>h){const t=2*Math.sqrt(1+a-n-h);this._w=(r-l)/t,this._x=(i+s)/t,this._y=.25*t,this._z=(o+c)/t}else{const t=2*Math.sqrt(1+h-n-a);this._w=(s-i)/t,this._x=(r+l)/t,this._y=(o+c)/t,this._z=.25*t}return this._onChangeCallback(),this}setFromUnitVectors(t,e){let n=t.dot(e)+1;return nMath.abs(t.z)?(this._x=-t.y,this._y=t.x,this._z=0,this._w=n):(this._x=0,this._y=-t.z,this._z=t.y,this._w=n)):(this._x=t.y*e.z-t.z*e.y,this._y=t.z*e.x-t.x*e.z,this._z=t.x*e.y-t.y*e.x,this._w=n),this.normalize()}angleTo(t){return 2*Math.acos(Math.abs($t(this.dot(t),-1,1)))}rotateTowards(t,e){const n=this.angleTo(t);if(0===n)return this;const i=Math.min(1,e/n);return this.slerp(t,i),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(t){return this._x*t._x+this._y*t._y+this._z*t._z+this._w*t._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let t=this.length();return 0===t?(this._x=0,this._y=0,this._z=0,this._w=1):(t=1/t,this._x=this._x*t,this._y=this._y*t,this._z=this._z*t,this._w=this._w*t),this._onChangeCallback(),this}multiply(t){return this.multiplyQuaternions(this,t)}premultiply(t){return this.multiplyQuaternions(t,this)}multiplyQuaternions(t,e){const n=t._x,i=t._y,r=t._z,s=t._w,a=e._x,o=e._y,l=e._z,c=e._w;return this._x=n*c+s*a+i*l-r*o,this._y=i*c+s*o+r*a-n*l,this._z=r*c+s*l+n*o-i*a,this._w=s*c-n*a-i*o-r*l,this._onChangeCallback(),this}slerp(t,e){if(0===e)return this;if(1===e)return this.copy(t);const n=this._x,i=this._y,r=this._z,s=this._w;let a=s*t._w+n*t._x+i*t._y+r*t._z;if(a<0?(this._w=-t._w,this._x=-t._x,this._y=-t._y,this._z=-t._z,a=-a):this.copy(t),a>=1)return this._w=s,this._x=n,this._y=i,this._z=r,this;const o=1-a*a;if(o<=Number.EPSILON){const t=1-e;return this._w=t*s+e*this._w,this._x=t*n+e*this._x,this._y=t*i+e*this._y,this._z=t*r+e*this._z,this.normalize(),this}const l=Math.sqrt(o),c=Math.atan2(l,a),h=Math.sin((1-e)*c)/l,u=Math.sin(e*c)/l;return this._w=s*h+this._w*u,this._x=n*h+this._x*u,this._y=i*h+this._y*u,this._z=r*h+this._z*u,this._onChangeCallback(),this}slerpQuaternions(t,e,n){return this.copy(t).slerp(e,n)}random(){const t=2*Math.PI*Math.random(),e=2*Math.PI*Math.random(),n=Math.random(),i=Math.sqrt(1-n),r=Math.sqrt(n);return this.set(i*Math.sin(t),i*Math.cos(t),r*Math.sin(e),r*Math.cos(e))}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._w===this._w}fromArray(t,e=0){return this._x=t[e],this._y=t[e+1],this._z=t[e+2],this._w=t[e+3],this._onChangeCallback(),this}toArray(t=[],e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._w,t}fromBufferAttribute(t,e){return this._x=t.getX(e),this._y=t.getY(e),this._z=t.getZ(e),this._w=t.getW(e),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class De{constructor(t=0,e=0,n=0){De.prototype.isVector3=!0,this.x=t,this.y=e,this.z=n}set(t,e,n){return void 0===n&&(n=this.z),this.x=t,this.y=e,this.z=n,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this}multiplyVectors(t,e){return this.x=t.x*e.x,this.y=t.y*e.y,this.z=t.z*e.z,this}applyEuler(t){return this.applyQuaternion(Oe.setFromEuler(t))}applyAxisAngle(t,e){return this.applyQuaternion(Oe.setFromAxisAngle(t,e))}applyMatrix3(t){const e=this.x,n=this.y,i=this.z,r=t.elements;return this.x=r[0]*e+r[3]*n+r[6]*i,this.y=r[1]*e+r[4]*n+r[7]*i,this.z=r[2]*e+r[5]*n+r[8]*i,this}applyNormalMatrix(t){return this.applyMatrix3(t).normalize()}applyMatrix4(t){const e=this.x,n=this.y,i=this.z,r=t.elements,s=1/(r[3]*e+r[7]*n+r[11]*i+r[15]);return this.x=(r[0]*e+r[4]*n+r[8]*i+r[12])*s,this.y=(r[1]*e+r[5]*n+r[9]*i+r[13])*s,this.z=(r[2]*e+r[6]*n+r[10]*i+r[14])*s,this}applyQuaternion(t){const e=this.x,n=this.y,i=this.z,r=t.x,s=t.y,a=t.z,o=t.w,l=2*(s*i-a*n),c=2*(a*e-r*i),h=2*(r*n-s*e);return this.x=e+o*l+s*h-a*c,this.y=n+o*c+a*l-r*h,this.z=i+o*h+r*c-s*l,this}project(t){return this.applyMatrix4(t.matrixWorldInverse).applyMatrix4(t.projectionMatrix)}unproject(t){return this.applyMatrix4(t.projectionMatrixInverse).applyMatrix4(t.matrixWorld)}transformDirection(t){const e=this.x,n=this.y,i=this.z,r=t.elements;return this.x=r[0]*e+r[4]*n+r[8]*i,this.y=r[1]*e+r[5]*n+r[9]*i,this.z=r[2]*e+r[6]*n+r[10]*i,this.normalize()}divide(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this}divideScalar(t){return this.multiplyScalar(1/t)}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this}clamp(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this.z=Math.max(t.z,Math.min(e.z,this.z)),this}clampScalar(t,e){return this.x=Math.max(t,Math.min(e,this.x)),this.y=Math.max(t,Math.min(e,this.y)),this.z=Math.max(t,Math.min(e,this.z)),this}clampLength(t,e){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Math.max(t,Math.min(e,n)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this}lerpVectors(t,e,n){return this.x=t.x+(e.x-t.x)*n,this.y=t.y+(e.y-t.y)*n,this.z=t.z+(e.z-t.z)*n,this}cross(t){return this.crossVectors(this,t)}crossVectors(t,e){const n=t.x,i=t.y,r=t.z,s=e.x,a=e.y,o=e.z;return this.x=i*o-r*a,this.y=r*s-n*o,this.z=n*a-i*s,this}projectOnVector(t){const e=t.lengthSq();if(0===e)return this.set(0,0,0);const n=t.dot(this)/e;return this.copy(t).multiplyScalar(n)}projectOnPlane(t){return Ne.copy(this).projectOnVector(t),this.sub(Ne)}reflect(t){return this.sub(Ne.copy(t).multiplyScalar(2*this.dot(t)))}angleTo(t){const e=Math.sqrt(this.lengthSq()*t.lengthSq());if(0===e)return Math.PI/2;const n=this.dot(t)/e;return Math.acos($t(n,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){const e=this.x-t.x,n=this.y-t.y,i=this.z-t.z;return e*e+n*n+i*i}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)+Math.abs(this.z-t.z)}setFromSpherical(t){return this.setFromSphericalCoords(t.radius,t.phi,t.theta)}setFromSphericalCoords(t,e,n){const i=Math.sin(e)*t;return this.x=i*Math.sin(n),this.y=Math.cos(e)*t,this.z=i*Math.cos(n),this}setFromCylindrical(t){return this.setFromCylindricalCoords(t.radius,t.theta,t.y)}setFromCylindricalCoords(t,e,n){return this.x=t*Math.sin(e),this.y=n,this.z=t*Math.cos(e),this}setFromMatrixPosition(t){const e=t.elements;return this.x=e[12],this.y=e[13],this.z=e[14],this}setFromMatrixScale(t){const e=this.setFromMatrixColumn(t,0).length(),n=this.setFromMatrixColumn(t,1).length(),i=this.setFromMatrixColumn(t,2).length();return this.x=e,this.y=n,this.z=i,this}setFromMatrixColumn(t,e){return this.fromArray(t.elements,4*e)}setFromMatrix3Column(t,e){return this.fromArray(t.elements,3*e)}setFromEuler(t){return this.x=t._x,this.y=t._y,this.z=t._z,this}setFromColor(t){return this.x=t.r,this.y=t.g,this.z=t.b,this}equals(t){return t.x===this.x&&t.y===this.y&&t.z===this.z}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this.z=t[e+2],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t}fromBufferAttribute(t,e){return this.x=t.getX(e),this.y=t.getY(e),this.z=t.getZ(e),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const t=Math.random()*Math.PI*2,e=2*Math.random()-1,n=Math.sqrt(1-e*e);return this.x=n*Math.cos(t),this.y=e,this.z=n*Math.sin(t),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const Ne=new De,Oe=new Ue;class Fe{constructor(t=new De(1/0,1/0,1/0),e=new De(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=t,this.max=e}set(t,e){return this.min.copy(t),this.max.copy(e),this}setFromArray(t){this.makeEmpty();for(let e=0,n=t.length;e=this.min.x&&t.x<=this.max.x&&t.y>=this.min.y&&t.y<=this.max.y&&t.z>=this.min.z&&t.z<=this.max.z}containsBox(t){return this.min.x<=t.min.x&&t.max.x<=this.max.x&&this.min.y<=t.min.y&&t.max.y<=this.max.y&&this.min.z<=t.min.z&&t.max.z<=this.max.z}getParameter(t,e){return e.set((t.x-this.min.x)/(this.max.x-this.min.x),(t.y-this.min.y)/(this.max.y-this.min.y),(t.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(t){return t.max.x>=this.min.x&&t.min.x<=this.max.x&&t.max.y>=this.min.y&&t.min.y<=this.max.y&&t.max.z>=this.min.z&&t.min.z<=this.max.z}intersectsSphere(t){return this.clampPoint(t.center,ze),ze.distanceToSquared(t.center)<=t.radius*t.radius}intersectsPlane(t){let e,n;return t.normal.x>0?(e=t.normal.x*this.min.x,n=t.normal.x*this.max.x):(e=t.normal.x*this.max.x,n=t.normal.x*this.min.x),t.normal.y>0?(e+=t.normal.y*this.min.y,n+=t.normal.y*this.max.y):(e+=t.normal.y*this.max.y,n+=t.normal.y*this.min.y),t.normal.z>0?(e+=t.normal.z*this.min.z,n+=t.normal.z*this.max.z):(e+=t.normal.z*this.max.z,n+=t.normal.z*this.min.z),e<=-t.constant&&n>=-t.constant}intersectsTriangle(t){if(this.isEmpty())return!1;this.getCenter(qe),Ye.subVectors(this.max,qe),Ve.subVectors(t.a,qe),He.subVectors(t.b,qe),Ge.subVectors(t.c,qe),We.subVectors(He,Ve),Xe.subVectors(Ge,He),je.subVectors(Ve,Ge);let e=[0,-We.z,We.y,0,-Xe.z,Xe.y,0,-je.z,je.y,We.z,0,-We.x,Xe.z,0,-Xe.x,je.z,0,-je.x,-We.y,We.x,0,-Xe.y,Xe.x,0,-je.y,je.x,0];return!!Ke(e,Ve,He,Ge,Ye)&&(e=[1,0,0,0,1,0,0,0,1],!!Ke(e,Ve,He,Ge,Ye)&&(Ze.crossVectors(We,Xe),e=[Ze.x,Ze.y,Ze.z],Ke(e,Ve,He,Ge,Ye)))}clampPoint(t,e){return e.copy(t).clamp(this.min,this.max)}distanceToPoint(t){return this.clampPoint(t,ze).distanceTo(t)}getBoundingSphere(t){return this.isEmpty()?t.makeEmpty():(this.getCenter(t.center),t.radius=.5*this.getSize(ze).length()),t}intersect(t){return this.min.max(t.min),this.max.min(t.max),this.isEmpty()&&this.makeEmpty(),this}union(t){return this.min.min(t.min),this.max.max(t.max),this}applyMatrix4(t){return this.isEmpty()||(Be[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(t),Be[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(t),Be[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(t),Be[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(t),Be[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(t),Be[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(t),Be[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(t),Be[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(t),this.setFromPoints(Be)),this}translate(t){return this.min.add(t),this.max.add(t),this}equals(t){return t.min.equals(this.min)&&t.max.equals(this.max)}}const Be=[new De,new De,new De,new De,new De,new De,new De,new De],ze=new De,ke=new Fe,Ve=new De,He=new De,Ge=new De,We=new De,Xe=new De,je=new De,qe=new De,Ye=new De,Ze=new De,Je=new De;function Ke(t,e,n,i,r){for(let s=0,a=t.length-3;s<=a;s+=3){Je.fromArray(t,s);const a=r.x*Math.abs(Je.x)+r.y*Math.abs(Je.y)+r.z*Math.abs(Je.z),o=e.dot(Je),l=n.dot(Je),c=i.dot(Je);if(Math.max(-Math.max(o,l,c),Math.min(o,l,c))>a)return!1}return!0}const $e=new Fe,Qe=new De,tn=new De;class en{constructor(t=new De,e=-1){this.isSphere=!0,this.center=t,this.radius=e}set(t,e){return this.center.copy(t),this.radius=e,this}setFromPoints(t,e){const n=this.center;void 0!==e?n.copy(e):$e.setFromPoints(t).getCenter(n);let i=0;for(let e=0,r=t.length;ethis.radius*this.radius&&(e.sub(this.center).normalize(),e.multiplyScalar(this.radius).add(this.center)),e}getBoundingBox(t){return this.isEmpty()?(t.makeEmpty(),t):(t.set(this.center,this.center),t.expandByScalar(this.radius),t)}applyMatrix4(t){return this.center.applyMatrix4(t),this.radius=this.radius*t.getMaxScaleOnAxis(),this}translate(t){return this.center.add(t),this}expandByPoint(t){if(this.isEmpty())return this.center.copy(t),this.radius=0,this;Qe.subVectors(t,this.center);const e=Qe.lengthSq();if(e>this.radius*this.radius){const t=Math.sqrt(e),n=.5*(t-this.radius);this.center.addScaledVector(Qe,n/t),this.radius+=n}return this}union(t){return t.isEmpty()?this:this.isEmpty()?(this.copy(t),this):(!0===this.center.equals(t.center)?this.radius=Math.max(this.radius,t.radius):(tn.subVectors(t.center,this.center).setLength(t.radius),this.expandByPoint(Qe.copy(t.center).add(tn)),this.expandByPoint(Qe.copy(t.center).sub(tn))),this)}equals(t){return t.center.equals(this.center)&&t.radius===this.radius}clone(){return(new this.constructor).copy(this)}}const nn=new De,rn=new De,sn=new De,an=new De,on=new De,ln=new De,cn=new De;class hn{constructor(t=new De,e=new De(0,0,-1)){this.origin=t,this.direction=e}set(t,e){return this.origin.copy(t),this.direction.copy(e),this}copy(t){return this.origin.copy(t.origin),this.direction.copy(t.direction),this}at(t,e){return e.copy(this.origin).addScaledVector(this.direction,t)}lookAt(t){return this.direction.copy(t).sub(this.origin).normalize(),this}recast(t){return this.origin.copy(this.at(t,nn)),this}closestPointToPoint(t,e){e.subVectors(t,this.origin);const n=e.dot(this.direction);return n<0?e.copy(this.origin):e.copy(this.origin).addScaledVector(this.direction,n)}distanceToPoint(t){return Math.sqrt(this.distanceSqToPoint(t))}distanceSqToPoint(t){const e=nn.subVectors(t,this.origin).dot(this.direction);return e<0?this.origin.distanceToSquared(t):(nn.copy(this.origin).addScaledVector(this.direction,e),nn.distanceToSquared(t))}distanceSqToSegment(t,e,n,i){rn.copy(t).add(e).multiplyScalar(.5),sn.copy(e).sub(t).normalize(),an.copy(this.origin).sub(rn);const r=.5*t.distanceTo(e),s=-this.direction.dot(sn),a=an.dot(this.direction),o=-an.dot(sn),l=an.lengthSq(),c=Math.abs(1-s*s);let h,u,d,p;if(c>0)if(h=s*o-a,u=s*a-o,p=r*c,h>=0)if(u>=-p)if(u<=p){const t=1/c;h*=t,u*=t,d=h*(h+s*u+2*a)+u*(s*h+u+2*o)+l}else u=r,h=Math.max(0,-(s*u+a)),d=-h*h+u*(u+2*o)+l;else u=-r,h=Math.max(0,-(s*u+a)),d=-h*h+u*(u+2*o)+l;else u<=-p?(h=Math.max(0,-(-s*r+a)),u=h>0?-r:Math.min(Math.max(-r,-o),r),d=-h*h+u*(u+2*o)+l):u<=p?(h=0,u=Math.min(Math.max(-r,-o),r),d=u*(u+2*o)+l):(h=Math.max(0,-(s*r+a)),u=h>0?r:Math.min(Math.max(-r,-o),r),d=-h*h+u*(u+2*o)+l);else u=s>0?-r:r,h=Math.max(0,-(s*u+a)),d=-h*h+u*(u+2*o)+l;return n&&n.copy(this.origin).addScaledVector(this.direction,h),i&&i.copy(rn).addScaledVector(sn,u),d}intersectSphere(t,e){nn.subVectors(t.center,this.origin);const n=nn.dot(this.direction),i=nn.dot(nn)-n*n,r=t.radius*t.radius;if(i>r)return null;const s=Math.sqrt(r-i),a=n-s,o=n+s;return o<0?null:a<0?this.at(o,e):this.at(a,e)}intersectsSphere(t){return this.distanceSqToPoint(t.center)<=t.radius*t.radius}distanceToPlane(t){const e=t.normal.dot(this.direction);if(0===e)return 0===t.distanceToPoint(this.origin)?0:null;const n=-(this.origin.dot(t.normal)+t.constant)/e;return n>=0?n:null}intersectPlane(t,e){const n=this.distanceToPlane(t);return null===n?null:this.at(n,e)}intersectsPlane(t){const e=t.distanceToPoint(this.origin);return 0===e||t.normal.dot(this.direction)*e<0}intersectBox(t,e){let n,i,r,s,a,o;const l=1/this.direction.x,c=1/this.direction.y,h=1/this.direction.z,u=this.origin;return l>=0?(n=(t.min.x-u.x)*l,i=(t.max.x-u.x)*l):(n=(t.max.x-u.x)*l,i=(t.min.x-u.x)*l),c>=0?(r=(t.min.y-u.y)*c,s=(t.max.y-u.y)*c):(r=(t.max.y-u.y)*c,s=(t.min.y-u.y)*c),n>s||r>i?null:((r>n||isNaN(n))&&(n=r),(s=0?(a=(t.min.z-u.z)*h,o=(t.max.z-u.z)*h):(a=(t.max.z-u.z)*h,o=(t.min.z-u.z)*h),n>o||a>i?null:((a>n||n!=n)&&(n=a),(o=0?n:i,e)))}intersectsBox(t){return null!==this.intersectBox(t,nn)}intersectTriangle(t,e,n,i,r){on.subVectors(e,t),ln.subVectors(n,t),cn.crossVectors(on,ln);let s,a=this.direction.dot(cn);if(a>0){if(i)return null;s=1}else{if(!(a<0))return null;s=-1,a=-a}an.subVectors(this.origin,t);const o=s*this.direction.dot(ln.crossVectors(an,ln));if(o<0)return null;const l=s*this.direction.dot(on.cross(an));if(l<0)return null;if(o+l>a)return null;const c=-s*an.dot(cn);return c<0?null:this.at(c/a,r)}applyMatrix4(t){return this.origin.applyMatrix4(t),this.direction.transformDirection(t),this}equals(t){return t.origin.equals(this.origin)&&t.direction.equals(this.direction)}clone(){return(new this.constructor).copy(this)}}class un{constructor(t,e,n,i,r,s,a,o,l,c,h,u,d,p,m,f){un.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],void 0!==t&&this.set(t,e,n,i,r,s,a,o,l,c,h,u,d,p,m,f)}set(t,e,n,i,r,s,a,o,l,c,h,u,d,p,m,f){const g=this.elements;return g[0]=t,g[4]=e,g[8]=n,g[12]=i,g[1]=r,g[5]=s,g[9]=a,g[13]=o,g[2]=l,g[6]=c,g[10]=h,g[14]=u,g[3]=d,g[7]=p,g[11]=m,g[15]=f,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return(new un).fromArray(this.elements)}copy(t){const e=this.elements,n=t.elements;return e[0]=n[0],e[1]=n[1],e[2]=n[2],e[3]=n[3],e[4]=n[4],e[5]=n[5],e[6]=n[6],e[7]=n[7],e[8]=n[8],e[9]=n[9],e[10]=n[10],e[11]=n[11],e[12]=n[12],e[13]=n[13],e[14]=n[14],e[15]=n[15],this}copyPosition(t){const e=this.elements,n=t.elements;return e[12]=n[12],e[13]=n[13],e[14]=n[14],this}setFromMatrix3(t){const e=t.elements;return this.set(e[0],e[3],e[6],0,e[1],e[4],e[7],0,e[2],e[5],e[8],0,0,0,0,1),this}extractBasis(t,e,n){return t.setFromMatrixColumn(this,0),e.setFromMatrixColumn(this,1),n.setFromMatrixColumn(this,2),this}makeBasis(t,e,n){return this.set(t.x,e.x,n.x,0,t.y,e.y,n.y,0,t.z,e.z,n.z,0,0,0,0,1),this}extractRotation(t){const e=this.elements,n=t.elements,i=1/dn.setFromMatrixColumn(t,0).length(),r=1/dn.setFromMatrixColumn(t,1).length(),s=1/dn.setFromMatrixColumn(t,2).length();return e[0]=n[0]*i,e[1]=n[1]*i,e[2]=n[2]*i,e[3]=0,e[4]=n[4]*r,e[5]=n[5]*r,e[6]=n[6]*r,e[7]=0,e[8]=n[8]*s,e[9]=n[9]*s,e[10]=n[10]*s,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromEuler(t){const e=this.elements,n=t.x,i=t.y,r=t.z,s=Math.cos(n),a=Math.sin(n),o=Math.cos(i),l=Math.sin(i),c=Math.cos(r),h=Math.sin(r);if("XYZ"===t.order){const t=s*c,n=s*h,i=a*c,r=a*h;e[0]=o*c,e[4]=-o*h,e[8]=l,e[1]=n+i*l,e[5]=t-r*l,e[9]=-a*o,e[2]=r-t*l,e[6]=i+n*l,e[10]=s*o}else if("YXZ"===t.order){const t=o*c,n=o*h,i=l*c,r=l*h;e[0]=t+r*a,e[4]=i*a-n,e[8]=s*l,e[1]=s*h,e[5]=s*c,e[9]=-a,e[2]=n*a-i,e[6]=r+t*a,e[10]=s*o}else if("ZXY"===t.order){const t=o*c,n=o*h,i=l*c,r=l*h;e[0]=t-r*a,e[4]=-s*h,e[8]=i+n*a,e[1]=n+i*a,e[5]=s*c,e[9]=r-t*a,e[2]=-s*l,e[6]=a,e[10]=s*o}else if("ZYX"===t.order){const t=s*c,n=s*h,i=a*c,r=a*h;e[0]=o*c,e[4]=i*l-n,e[8]=t*l+r,e[1]=o*h,e[5]=r*l+t,e[9]=n*l-i,e[2]=-l,e[6]=a*o,e[10]=s*o}else if("YZX"===t.order){const t=s*o,n=s*l,i=a*o,r=a*l;e[0]=o*c,e[4]=r-t*h,e[8]=i*h+n,e[1]=h,e[5]=s*c,e[9]=-a*c,e[2]=-l*c,e[6]=n*h+i,e[10]=t-r*h}else if("XZY"===t.order){const t=s*o,n=s*l,i=a*o,r=a*l;e[0]=o*c,e[4]=-h,e[8]=l*c,e[1]=t*h+r,e[5]=s*c,e[9]=n*h-i,e[2]=i*h-n,e[6]=a*c,e[10]=r*h+t}return e[3]=0,e[7]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromQuaternion(t){return this.compose(mn,t,fn)}lookAt(t,e,n){const i=this.elements;return _n.subVectors(t,e),0===_n.lengthSq()&&(_n.z=1),_n.normalize(),gn.crossVectors(n,_n),0===gn.lengthSq()&&(1===Math.abs(n.z)?_n.x+=1e-4:_n.z+=1e-4,_n.normalize(),gn.crossVectors(n,_n)),gn.normalize(),vn.crossVectors(_n,gn),i[0]=gn.x,i[4]=vn.x,i[8]=_n.x,i[1]=gn.y,i[5]=vn.y,i[9]=_n.y,i[2]=gn.z,i[6]=vn.z,i[10]=_n.z,this}multiply(t){return this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){const n=t.elements,i=e.elements,r=this.elements,s=n[0],a=n[4],o=n[8],l=n[12],c=n[1],h=n[5],u=n[9],d=n[13],p=n[2],m=n[6],f=n[10],g=n[14],v=n[3],_=n[7],x=n[11],y=n[15],M=i[0],S=i[4],b=i[8],w=i[12],T=i[1],E=i[5],A=i[9],R=i[13],C=i[2],P=i[6],I=i[10],L=i[14],U=i[3],D=i[7],N=i[11],O=i[15];return r[0]=s*M+a*T+o*C+l*U,r[4]=s*S+a*E+o*P+l*D,r[8]=s*b+a*A+o*I+l*N,r[12]=s*w+a*R+o*L+l*O,r[1]=c*M+h*T+u*C+d*U,r[5]=c*S+h*E+u*P+d*D,r[9]=c*b+h*A+u*I+d*N,r[13]=c*w+h*R+u*L+d*O,r[2]=p*M+m*T+f*C+g*U,r[6]=p*S+m*E+f*P+g*D,r[10]=p*b+m*A+f*I+g*N,r[14]=p*w+m*R+f*L+g*O,r[3]=v*M+_*T+x*C+y*U,r[7]=v*S+_*E+x*P+y*D,r[11]=v*b+_*A+x*I+y*N,r[15]=v*w+_*R+x*L+y*O,this}multiplyScalar(t){const e=this.elements;return e[0]*=t,e[4]*=t,e[8]*=t,e[12]*=t,e[1]*=t,e[5]*=t,e[9]*=t,e[13]*=t,e[2]*=t,e[6]*=t,e[10]*=t,e[14]*=t,e[3]*=t,e[7]*=t,e[11]*=t,e[15]*=t,this}determinant(){const t=this.elements,e=t[0],n=t[4],i=t[8],r=t[12],s=t[1],a=t[5],o=t[9],l=t[13],c=t[2],h=t[6],u=t[10],d=t[14];return t[3]*(+r*o*h-i*l*h-r*a*u+n*l*u+i*a*d-n*o*d)+t[7]*(+e*o*d-e*l*u+r*s*u-i*s*d+i*l*c-r*o*c)+t[11]*(+e*l*h-e*a*d-r*s*h+n*s*d+r*a*c-n*l*c)+t[15]*(-i*a*c-e*o*h+e*a*u+i*s*h-n*s*u+n*o*c)}transpose(){const t=this.elements;let e;return e=t[1],t[1]=t[4],t[4]=e,e=t[2],t[2]=t[8],t[8]=e,e=t[6],t[6]=t[9],t[9]=e,e=t[3],t[3]=t[12],t[12]=e,e=t[7],t[7]=t[13],t[13]=e,e=t[11],t[11]=t[14],t[14]=e,this}setPosition(t,e,n){const i=this.elements;return t.isVector3?(i[12]=t.x,i[13]=t.y,i[14]=t.z):(i[12]=t,i[13]=e,i[14]=n),this}invert(){const t=this.elements,e=t[0],n=t[1],i=t[2],r=t[3],s=t[4],a=t[5],o=t[6],l=t[7],c=t[8],h=t[9],u=t[10],d=t[11],p=t[12],m=t[13],f=t[14],g=t[15],v=h*f*l-m*u*l+m*o*d-a*f*d-h*o*g+a*u*g,_=p*u*l-c*f*l-p*o*d+s*f*d+c*o*g-s*u*g,x=c*m*l-p*h*l+p*a*d-s*m*d-c*a*g+s*h*g,y=p*h*o-c*m*o-p*a*u+s*m*u+c*a*f-s*h*f,M=e*v+n*_+i*x+r*y;if(0===M)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const S=1/M;return t[0]=v*S,t[1]=(m*u*r-h*f*r-m*i*d+n*f*d+h*i*g-n*u*g)*S,t[2]=(a*f*r-m*o*r+m*i*l-n*f*l-a*i*g+n*o*g)*S,t[3]=(h*o*r-a*u*r-h*i*l+n*u*l+a*i*d-n*o*d)*S,t[4]=_*S,t[5]=(c*f*r-p*u*r+p*i*d-e*f*d-c*i*g+e*u*g)*S,t[6]=(p*o*r-s*f*r-p*i*l+e*f*l+s*i*g-e*o*g)*S,t[7]=(s*u*r-c*o*r+c*i*l-e*u*l-s*i*d+e*o*d)*S,t[8]=x*S,t[9]=(p*h*r-c*m*r-p*n*d+e*m*d+c*n*g-e*h*g)*S,t[10]=(s*m*r-p*a*r+p*n*l-e*m*l-s*n*g+e*a*g)*S,t[11]=(c*a*r-s*h*r-c*n*l+e*h*l+s*n*d-e*a*d)*S,t[12]=y*S,t[13]=(c*m*i-p*h*i+p*n*u-e*m*u-c*n*f+e*h*f)*S,t[14]=(p*a*i-s*m*i-p*n*o+e*m*o+s*n*f-e*a*f)*S,t[15]=(s*h*i-c*a*i+c*n*o-e*h*o-s*n*u+e*a*u)*S,this}scale(t){const e=this.elements,n=t.x,i=t.y,r=t.z;return e[0]*=n,e[4]*=i,e[8]*=r,e[1]*=n,e[5]*=i,e[9]*=r,e[2]*=n,e[6]*=i,e[10]*=r,e[3]*=n,e[7]*=i,e[11]*=r,this}getMaxScaleOnAxis(){const t=this.elements,e=t[0]*t[0]+t[1]*t[1]+t[2]*t[2],n=t[4]*t[4]+t[5]*t[5]+t[6]*t[6],i=t[8]*t[8]+t[9]*t[9]+t[10]*t[10];return Math.sqrt(Math.max(e,n,i))}makeTranslation(t,e,n){return t.isVector3?this.set(1,0,0,t.x,0,1,0,t.y,0,0,1,t.z,0,0,0,1):this.set(1,0,0,t,0,1,0,e,0,0,1,n,0,0,0,1),this}makeRotationX(t){const e=Math.cos(t),n=Math.sin(t);return this.set(1,0,0,0,0,e,-n,0,0,n,e,0,0,0,0,1),this}makeRotationY(t){const e=Math.cos(t),n=Math.sin(t);return this.set(e,0,n,0,0,1,0,0,-n,0,e,0,0,0,0,1),this}makeRotationZ(t){const e=Math.cos(t),n=Math.sin(t);return this.set(e,-n,0,0,n,e,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(t,e){const n=Math.cos(e),i=Math.sin(e),r=1-n,s=t.x,a=t.y,o=t.z,l=r*s,c=r*a;return this.set(l*s+n,l*a-i*o,l*o+i*a,0,l*a+i*o,c*a+n,c*o-i*s,0,l*o-i*a,c*o+i*s,r*o*o+n,0,0,0,0,1),this}makeScale(t,e,n){return this.set(t,0,0,0,0,e,0,0,0,0,n,0,0,0,0,1),this}makeShear(t,e,n,i,r,s){return this.set(1,n,r,0,t,1,s,0,e,i,1,0,0,0,0,1),this}compose(t,e,n){const i=this.elements,r=e._x,s=e._y,a=e._z,o=e._w,l=r+r,c=s+s,h=a+a,u=r*l,d=r*c,p=r*h,m=s*c,f=s*h,g=a*h,v=o*l,_=o*c,x=o*h,y=n.x,M=n.y,S=n.z;return i[0]=(1-(m+g))*y,i[1]=(d+x)*y,i[2]=(p-_)*y,i[3]=0,i[4]=(d-x)*M,i[5]=(1-(u+g))*M,i[6]=(f+v)*M,i[7]=0,i[8]=(p+_)*S,i[9]=(f-v)*S,i[10]=(1-(u+m))*S,i[11]=0,i[12]=t.x,i[13]=t.y,i[14]=t.z,i[15]=1,this}decompose(t,e,n){const i=this.elements;let r=dn.set(i[0],i[1],i[2]).length();const s=dn.set(i[4],i[5],i[6]).length(),a=dn.set(i[8],i[9],i[10]).length();this.determinant()<0&&(r=-r),t.x=i[12],t.y=i[13],t.z=i[14],pn.copy(this);const o=1/r,l=1/s,c=1/a;return pn.elements[0]*=o,pn.elements[1]*=o,pn.elements[2]*=o,pn.elements[4]*=l,pn.elements[5]*=l,pn.elements[6]*=l,pn.elements[8]*=c,pn.elements[9]*=c,pn.elements[10]*=c,e.setFromRotationMatrix(pn),n.x=r,n.y=s,n.z=a,this}makePerspective(t,e,n,i,r,s,a=2e3){const o=this.elements,l=2*r/(e-t),c=2*r/(n-i),h=(e+t)/(e-t),u=(n+i)/(n-i);let d,p;if(a===Wt)d=-(s+r)/(s-r),p=-2*s*r/(s-r);else{if(a!==Xt)throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+a);d=-s/(s-r),p=-s*r/(s-r)}return o[0]=l,o[4]=0,o[8]=h,o[12]=0,o[1]=0,o[5]=c,o[9]=u,o[13]=0,o[2]=0,o[6]=0,o[10]=d,o[14]=p,o[3]=0,o[7]=0,o[11]=-1,o[15]=0,this}makeOrthographic(t,e,n,i,r,s,a=2e3){const o=this.elements,l=1/(e-t),c=1/(n-i),h=1/(s-r),u=(e+t)*l,d=(n+i)*c;let p,m;if(a===Wt)p=(s+r)*h,m=-2*h;else{if(a!==Xt)throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+a);p=r*h,m=-1*h}return o[0]=2*l,o[4]=0,o[8]=0,o[12]=-u,o[1]=0,o[5]=2*c,o[9]=0,o[13]=-d,o[2]=0,o[6]=0,o[10]=m,o[14]=-p,o[3]=0,o[7]=0,o[11]=0,o[15]=1,this}equals(t){const e=this.elements,n=t.elements;for(let t=0;t<16;t++)if(e[t]!==n[t])return!1;return!0}fromArray(t,e=0){for(let n=0;n<16;n++)this.elements[n]=t[n+e];return this}toArray(t=[],e=0){const n=this.elements;return t[e]=n[0],t[e+1]=n[1],t[e+2]=n[2],t[e+3]=n[3],t[e+4]=n[4],t[e+5]=n[5],t[e+6]=n[6],t[e+7]=n[7],t[e+8]=n[8],t[e+9]=n[9],t[e+10]=n[10],t[e+11]=n[11],t[e+12]=n[12],t[e+13]=n[13],t[e+14]=n[14],t[e+15]=n[15],t}}const dn=new De,pn=new un,mn=new De(0,0,0),fn=new De(1,1,1),gn=new De,vn=new De,_n=new De,xn=new un,yn=new Ue;class Mn{constructor(t=0,e=0,n=0,i=Mn.DEFAULT_ORDER){this.isEuler=!0,this._x=t,this._y=e,this._z=n,this._order=i}get x(){return this._x}set x(t){this._x=t,this._onChangeCallback()}get y(){return this._y}set y(t){this._y=t,this._onChangeCallback()}get z(){return this._z}set z(t){this._z=t,this._onChangeCallback()}get order(){return this._order}set order(t){this._order=t,this._onChangeCallback()}set(t,e,n,i=this._order){return this._x=t,this._y=e,this._z=n,this._order=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(t){return this._x=t._x,this._y=t._y,this._z=t._z,this._order=t._order,this._onChangeCallback(),this}setFromRotationMatrix(t,e=this._order,n=!0){const i=t.elements,r=i[0],s=i[4],a=i[8],o=i[1],l=i[5],c=i[9],h=i[2],u=i[6],d=i[10];switch(e){case"XYZ":this._y=Math.asin($t(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-c,d),this._z=Math.atan2(-s,r)):(this._x=Math.atan2(u,l),this._z=0);break;case"YXZ":this._x=Math.asin(-$t(c,-1,1)),Math.abs(c)<.9999999?(this._y=Math.atan2(a,d),this._z=Math.atan2(o,l)):(this._y=Math.atan2(-h,r),this._z=0);break;case"ZXY":this._x=Math.asin($t(u,-1,1)),Math.abs(u)<.9999999?(this._y=Math.atan2(-h,d),this._z=Math.atan2(-s,l)):(this._y=0,this._z=Math.atan2(o,r));break;case"ZYX":this._y=Math.asin(-$t(h,-1,1)),Math.abs(h)<.9999999?(this._x=Math.atan2(u,d),this._z=Math.atan2(o,r)):(this._x=0,this._z=Math.atan2(-s,l));break;case"YZX":this._z=Math.asin($t(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-c,l),this._y=Math.atan2(-h,r)):(this._x=0,this._y=Math.atan2(a,d));break;case"XZY":this._z=Math.asin(-$t(s,-1,1)),Math.abs(s)<.9999999?(this._x=Math.atan2(u,l),this._y=Math.atan2(a,r)):(this._x=Math.atan2(-c,d),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+e)}return this._order=e,!0===n&&this._onChangeCallback(),this}setFromQuaternion(t,e,n){return xn.makeRotationFromQuaternion(t),this.setFromRotationMatrix(xn,e,n)}setFromVector3(t,e=this._order){return this.set(t.x,t.y,t.z,e)}reorder(t){return yn.setFromEuler(this),this.setFromQuaternion(yn,t)}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._order===this._order}fromArray(t){return this._x=t[0],this._y=t[1],this._z=t[2],void 0!==t[3]&&(this._order=t[3]),this._onChangeCallback(),this}toArray(t=[],e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._order,t}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}Mn.DEFAULT_ORDER="XYZ";class Sn{constructor(){this.mask=1}set(t){this.mask=(1<>>0}enable(t){this.mask|=1<1){for(let t=0;t1){for(let t=0;t0&&(i.userData=this.userData),i.layers=this.layers.mask,i.matrix=this.matrix.toArray(),i.up=this.up.toArray(),!1===this.matrixAutoUpdate&&(i.matrixAutoUpdate=!1),this.isInstancedMesh&&(i.type="InstancedMesh",i.count=this.count,i.instanceMatrix=this.instanceMatrix.toJSON(),null!==this.instanceColor&&(i.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(i.type="BatchedMesh",i.perObjectFrustumCulled=this.perObjectFrustumCulled,i.sortObjects=this.sortObjects,i.drawRanges=this._drawRanges,i.reservedRanges=this._reservedRanges,i.visibility=this._visibility,i.active=this._active,i.bounds=this._bounds.map((t=>({boxInitialized:t.boxInitialized,boxMin:t.box.min.toArray(),boxMax:t.box.max.toArray(),sphereInitialized:t.sphereInitialized,sphereRadius:t.sphere.radius,sphereCenter:t.sphere.center.toArray()}))),i.maxInstanceCount=this._maxInstanceCount,i.maxVertexCount=this._maxVertexCount,i.maxIndexCount=this._maxIndexCount,i.geometryInitialized=this._geometryInitialized,i.geometryCount=this._geometryCount,i.matricesTexture=this._matricesTexture.toJSON(t),null!==this._colorsTexture&&(i.colorsTexture=this._colorsTexture.toJSON(t)),null!==this.boundingSphere&&(i.boundingSphere={center:i.boundingSphere.center.toArray(),radius:i.boundingSphere.radius}),null!==this.boundingBox&&(i.boundingBox={min:i.boundingBox.min.toArray(),max:i.boundingBox.max.toArray()})),this.isScene)this.background&&(this.background.isColor?i.background=this.background.toJSON():this.background.isTexture&&(i.background=this.background.toJSON(t).uuid)),this.environment&&this.environment.isTexture&&!0!==this.environment.isRenderTargetTexture&&(i.environment=this.environment.toJSON(t).uuid);else if(this.isMesh||this.isLine||this.isPoints){i.geometry=r(t.geometries,this.geometry);const e=this.geometry.parameters;if(void 0!==e&&void 0!==e.shapes){const n=e.shapes;if(Array.isArray(n))for(let e=0,i=n.length;e0){i.children=[];for(let e=0;e0){i.animations=[];for(let e=0;e0&&(n.geometries=e),i.length>0&&(n.materials=i),r.length>0&&(n.textures=r),a.length>0&&(n.images=a),o.length>0&&(n.shapes=o),l.length>0&&(n.skeletons=l),c.length>0&&(n.animations=c),h.length>0&&(n.nodes=h)}return n.object=i,n;function s(t){const e=[];for(const n in t){const i=t[n];delete i.metadata,e.push(i)}return e}}clone(t){return(new this.constructor).copy(this,t)}copy(t,e=!0){if(this.name=t.name,this.up.copy(t.up),this.position.copy(t.position),this.rotation.order=t.rotation.order,this.quaternion.copy(t.quaternion),this.scale.copy(t.scale),this.matrix.copy(t.matrix),this.matrixWorld.copy(t.matrixWorld),this.matrixAutoUpdate=t.matrixAutoUpdate,this.matrixWorldAutoUpdate=t.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=t.matrixWorldNeedsUpdate,this.layers.mask=t.layers.mask,this.visible=t.visible,this.castShadow=t.castShadow,this.receiveShadow=t.receiveShadow,this.frustumCulled=t.frustumCulled,this.renderOrder=t.renderOrder,this.animations=t.animations.slice(),this.userData=JSON.parse(JSON.stringify(t.userData)),!0===e)for(let e=0;e0?i.multiplyScalar(1/Math.sqrt(r)):i.set(0,0,0)}static getBarycoord(t,e,n,i,r){zn.subVectors(i,e),kn.subVectors(n,e),Vn.subVectors(t,e);const s=zn.dot(zn),a=zn.dot(kn),o=zn.dot(Vn),l=kn.dot(kn),c=kn.dot(Vn),h=s*l-a*a;if(0===h)return r.set(0,0,0),null;const u=1/h,d=(l*o-a*c)*u,p=(s*c-a*o)*u;return r.set(1-d-p,p,d)}static containsPoint(t,e,n,i){return null!==this.getBarycoord(t,e,n,i,Hn)&&Hn.x>=0&&Hn.y>=0&&Hn.x+Hn.y<=1}static getInterpolation(t,e,n,i,r,s,a,o){return null===this.getBarycoord(t,e,n,i,Hn)?(o.x=0,o.y=0,"z"in o&&(o.z=0),"w"in o&&(o.w=0),null):(o.setScalar(0),o.addScaledVector(r,Hn.x),o.addScaledVector(s,Hn.y),o.addScaledVector(a,Hn.z),o)}static getInterpolatedAttribute(t,e,n,i,r,s){return Zn.setScalar(0),Jn.setScalar(0),Kn.setScalar(0),Zn.fromBufferAttribute(t,e),Jn.fromBufferAttribute(t,n),Kn.fromBufferAttribute(t,i),s.setScalar(0),s.addScaledVector(Zn,r.x),s.addScaledVector(Jn,r.y),s.addScaledVector(Kn,r.z),s}static isFrontFacing(t,e,n,i){return zn.subVectors(n,e),kn.subVectors(t,e),zn.cross(kn).dot(i)<0}set(t,e,n){return this.a.copy(t),this.b.copy(e),this.c.copy(n),this}setFromPointsAndIndices(t,e,n,i){return this.a.copy(t[e]),this.b.copy(t[n]),this.c.copy(t[i]),this}setFromAttributeAndIndices(t,e,n,i){return this.a.fromBufferAttribute(t,e),this.b.fromBufferAttribute(t,n),this.c.fromBufferAttribute(t,i),this}clone(){return(new this.constructor).copy(this)}copy(t){return this.a.copy(t.a),this.b.copy(t.b),this.c.copy(t.c),this}getArea(){return zn.subVectors(this.c,this.b),kn.subVectors(this.a,this.b),.5*zn.cross(kn).length()}getMidpoint(t){return t.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(t){return $n.getNormal(this.a,this.b,this.c,t)}getPlane(t){return t.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(t,e){return $n.getBarycoord(t,this.a,this.b,this.c,e)}getInterpolation(t,e,n,i,r){return $n.getInterpolation(t,this.a,this.b,this.c,e,n,i,r)}containsPoint(t){return $n.containsPoint(t,this.a,this.b,this.c)}isFrontFacing(t){return $n.isFrontFacing(this.a,this.b,this.c,t)}intersectsBox(t){return t.intersectsTriangle(this)}closestPointToPoint(t,e){const n=this.a,i=this.b,r=this.c;let s,a;Gn.subVectors(i,n),Wn.subVectors(r,n),jn.subVectors(t,n);const o=Gn.dot(jn),l=Wn.dot(jn);if(o<=0&&l<=0)return e.copy(n);qn.subVectors(t,i);const c=Gn.dot(qn),h=Wn.dot(qn);if(c>=0&&h<=c)return e.copy(i);const u=o*h-c*l;if(u<=0&&o>=0&&c<=0)return s=o/(o-c),e.copy(n).addScaledVector(Gn,s);Yn.subVectors(t,r);const d=Gn.dot(Yn),p=Wn.dot(Yn);if(p>=0&&d<=p)return e.copy(r);const m=d*l-o*p;if(m<=0&&l>=0&&p<=0)return a=l/(l-p),e.copy(n).addScaledVector(Wn,a);const f=c*p-d*h;if(f<=0&&h-c>=0&&d-p>=0)return Xn.subVectors(r,i),a=(h-c)/(h-c+(d-p)),e.copy(i).addScaledVector(Xn,a);const g=1/(f+m+u);return s=m*g,a=u*g,e.copy(n).addScaledVector(Gn,s).addScaledVector(Wn,a)}equals(t){return t.a.equals(this.a)&&t.b.equals(this.b)&&t.c.equals(this.c)}}const Qn={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},ti={h:0,s:0,l:0},ei={h:0,s:0,l:0};function ni(t,e,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?t+6*(e-t)*n:n<.5?e:n<2/3?t+6*(e-t)*(2/3-n):t}class ii{constructor(t,e,n){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(t,e,n)}set(t,e,n){if(void 0===e&&void 0===n){const e=t;e&&e.isColor?this.copy(e):"number"==typeof e?this.setHex(e):"string"==typeof e&&this.setStyle(e)}else this.setRGB(t,e,n);return this}setScalar(t){return this.r=t,this.g=t,this.b=t,this}setHex(t,e=Ut){return t=Math.floor(t),this.r=(t>>16&255)/255,this.g=(t>>8&255)/255,this.b=(255&t)/255,_e.toWorkingColorSpace(this,e),this}setRGB(t,e,n,i=_e.workingColorSpace){return this.r=t,this.g=e,this.b=n,_e.toWorkingColorSpace(this,i),this}setHSL(t,e,n,i=_e.workingColorSpace){if(t=Qt(t,1),e=$t(e,0,1),n=$t(n,0,1),0===e)this.r=this.g=this.b=n;else{const i=n<=.5?n*(1+e):n+e-n*e,r=2*n-i;this.r=ni(r,i,t+1/3),this.g=ni(r,i,t),this.b=ni(r,i,t-1/3)}return _e.toWorkingColorSpace(this,i),this}setStyle(t,e=Ut){function n(e){void 0!==e&&parseFloat(e)<1&&console.warn("THREE.Color: Alpha component of "+t+" will be ignored.")}let i;if(i=/^(\w+)\(([^\)]*)\)/.exec(t)){let r;const s=i[1],a=i[2];switch(s){case"rgb":case"rgba":if(r=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setRGB(Math.min(255,parseInt(r[1],10))/255,Math.min(255,parseInt(r[2],10))/255,Math.min(255,parseInt(r[3],10))/255,e);if(r=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setRGB(Math.min(100,parseInt(r[1],10))/100,Math.min(100,parseInt(r[2],10))/100,Math.min(100,parseInt(r[3],10))/100,e);break;case"hsl":case"hsla":if(r=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setHSL(parseFloat(r[1])/360,parseFloat(r[2])/100,parseFloat(r[3])/100,e);break;default:console.warn("THREE.Color: Unknown color model "+t)}}else if(i=/^\#([A-Fa-f\d]+)$/.exec(t)){const n=i[1],r=n.length;if(3===r)return this.setRGB(parseInt(n.charAt(0),16)/15,parseInt(n.charAt(1),16)/15,parseInt(n.charAt(2),16)/15,e);if(6===r)return this.setHex(parseInt(n,16),e);console.warn("THREE.Color: Invalid hex color "+t)}else if(t&&t.length>0)return this.setColorName(t,e);return this}setColorName(t,e=Ut){const n=Qn[t.toLowerCase()];return void 0!==n?this.setHex(n,e):console.warn("THREE.Color: Unknown color "+t),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(t){return this.r=t.r,this.g=t.g,this.b=t.b,this}copySRGBToLinear(t){return this.r=xe(t.r),this.g=xe(t.g),this.b=xe(t.b),this}copyLinearToSRGB(t){return this.r=ye(t.r),this.g=ye(t.g),this.b=ye(t.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(t=Ut){return _e.fromWorkingColorSpace(ri.copy(this),t),65536*Math.round($t(255*ri.r,0,255))+256*Math.round($t(255*ri.g,0,255))+Math.round($t(255*ri.b,0,255))}getHexString(t=Ut){return("000000"+this.getHex(t).toString(16)).slice(-6)}getHSL(t,e=_e.workingColorSpace){_e.fromWorkingColorSpace(ri.copy(this),e);const n=ri.r,i=ri.g,r=ri.b,s=Math.max(n,i,r),a=Math.min(n,i,r);let o,l;const c=(a+s)/2;if(a===s)o=0,l=0;else{const t=s-a;switch(l=c<=.5?t/(s+a):t/(2-s-a),s){case n:o=(i-r)/t+(i0!=t>0&&this.version++,this._alphaTest=t}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(t){if(void 0!==t)for(const e in t){const n=t[e];if(void 0===n){console.warn(`THREE.Material: parameter '${e}' has value of undefined.`);continue}const i=this[e];void 0!==i?i&&i.isColor?i.set(n):i&&i.isVector3&&n&&n.isVector3?i.copy(n):this[e]=n:console.warn(`THREE.Material: '${e}' is not a property of THREE.${this.type}.`)}}toJSON(t){const e=void 0===t||"string"==typeof t;e&&(t={textures:{},images:{}});const n={metadata:{version:4.6,type:"Material",generator:"Material.toJSON"}};function a(t){const e=[];for(const n in t){const i=t[n];delete i.metadata,e.push(i)}return e}if(n.uuid=this.uuid,n.type=this.type,""!==this.name&&(n.name=this.name),this.color&&this.color.isColor&&(n.color=this.color.getHex()),void 0!==this.roughness&&(n.roughness=this.roughness),void 0!==this.metalness&&(n.metalness=this.metalness),void 0!==this.sheen&&(n.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(n.sheenColor=this.sheenColor.getHex()),void 0!==this.sheenRoughness&&(n.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),void 0!==this.emissiveIntensity&&1!==this.emissiveIntensity&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),void 0!==this.specularIntensity&&(n.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(n.specularColor=this.specularColor.getHex()),void 0!==this.shininess&&(n.shininess=this.shininess),void 0!==this.clearcoat&&(n.clearcoat=this.clearcoat),void 0!==this.clearcoatRoughness&&(n.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(n.clearcoatMap=this.clearcoatMap.toJSON(t).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(t).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(t).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),void 0!==this.dispersion&&(n.dispersion=this.dispersion),void 0!==this.iridescence&&(n.iridescence=this.iridescence),void 0!==this.iridescenceIOR&&(n.iridescenceIOR=this.iridescenceIOR),void 0!==this.iridescenceThicknessRange&&(n.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(n.iridescenceMap=this.iridescenceMap.toJSON(t).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(n.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(t).uuid),void 0!==this.anisotropy&&(n.anisotropy=this.anisotropy),void 0!==this.anisotropyRotation&&(n.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(n.anisotropyMap=this.anisotropyMap.toJSON(t).uuid),this.map&&this.map.isTexture&&(n.map=this.map.toJSON(t).uuid),this.matcap&&this.matcap.isTexture&&(n.matcap=this.matcap.toJSON(t).uuid),this.alphaMap&&this.alphaMap.isTexture&&(n.alphaMap=this.alphaMap.toJSON(t).uuid),this.lightMap&&this.lightMap.isTexture&&(n.lightMap=this.lightMap.toJSON(t).uuid,n.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(n.aoMap=this.aoMap.toJSON(t).uuid,n.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(n.bumpMap=this.bumpMap.toJSON(t).uuid,n.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(n.normalMap=this.normalMap.toJSON(t).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(n.displacementMap=this.displacementMap.toJSON(t).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(n.roughnessMap=this.roughnessMap.toJSON(t).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(n.metalnessMap=this.metalnessMap.toJSON(t).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(n.emissiveMap=this.emissiveMap.toJSON(t).uuid),this.specularMap&&this.specularMap.isTexture&&(n.specularMap=this.specularMap.toJSON(t).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(n.specularIntensityMap=this.specularIntensityMap.toJSON(t).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(n.specularColorMap=this.specularColorMap.toJSON(t).uuid),this.envMap&&this.envMap.isTexture&&(n.envMap=this.envMap.toJSON(t).uuid,void 0!==this.combine&&(n.combine=this.combine)),void 0!==this.envMapRotation&&(n.envMapRotation=this.envMapRotation.toArray()),void 0!==this.envMapIntensity&&(n.envMapIntensity=this.envMapIntensity),void 0!==this.reflectivity&&(n.reflectivity=this.reflectivity),void 0!==this.refractionRatio&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(t).uuid),void 0!==this.transmission&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(t).uuid),void 0!==this.thickness&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(t).uuid),void 0!==this.attenuationDistance&&this.attenuationDistance!==1/0&&(n.attenuationDistance=this.attenuationDistance),void 0!==this.attenuationColor&&(n.attenuationColor=this.attenuationColor.getHex()),void 0!==this.size&&(n.size=this.size),null!==this.shadowSide&&(n.shadowSide=this.shadowSide),void 0!==this.sizeAttenuation&&(n.sizeAttenuation=this.sizeAttenuation),1!==this.blending&&(n.blending=this.blending),0!==this.side&&(n.side=this.side),!0===this.vertexColors&&(n.vertexColors=!0),this.opacity<1&&(n.opacity=this.opacity),!0===this.transparent&&(n.transparent=!0),this.blendSrc!==r&&(n.blendSrc=this.blendSrc),this.blendDst!==s&&(n.blendDst=this.blendDst),this.blendEquation!==i&&(n.blendEquation=this.blendEquation),null!==this.blendSrcAlpha&&(n.blendSrcAlpha=this.blendSrcAlpha),null!==this.blendDstAlpha&&(n.blendDstAlpha=this.blendDstAlpha),null!==this.blendEquationAlpha&&(n.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(n.blendColor=this.blendColor.getHex()),0!==this.blendAlpha&&(n.blendAlpha=this.blendAlpha),3!==this.depthFunc&&(n.depthFunc=this.depthFunc),!1===this.depthTest&&(n.depthTest=this.depthTest),!1===this.depthWrite&&(n.depthWrite=this.depthWrite),!1===this.colorWrite&&(n.colorWrite=this.colorWrite),255!==this.stencilWriteMask&&(n.stencilWriteMask=this.stencilWriteMask),519!==this.stencilFunc&&(n.stencilFunc=this.stencilFunc),0!==this.stencilRef&&(n.stencilRef=this.stencilRef),255!==this.stencilFuncMask&&(n.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==Vt&&(n.stencilFail=this.stencilFail),this.stencilZFail!==Vt&&(n.stencilZFail=this.stencilZFail),this.stencilZPass!==Vt&&(n.stencilZPass=this.stencilZPass),!0===this.stencilWrite&&(n.stencilWrite=this.stencilWrite),void 0!==this.rotation&&0!==this.rotation&&(n.rotation=this.rotation),!0===this.polygonOffset&&(n.polygonOffset=!0),0!==this.polygonOffsetFactor&&(n.polygonOffsetFactor=this.polygonOffsetFactor),0!==this.polygonOffsetUnits&&(n.polygonOffsetUnits=this.polygonOffsetUnits),void 0!==this.linewidth&&1!==this.linewidth&&(n.linewidth=this.linewidth),void 0!==this.dashSize&&(n.dashSize=this.dashSize),void 0!==this.gapSize&&(n.gapSize=this.gapSize),void 0!==this.scale&&(n.scale=this.scale),!0===this.dithering&&(n.dithering=!0),this.alphaTest>0&&(n.alphaTest=this.alphaTest),!0===this.alphaHash&&(n.alphaHash=!0),!0===this.alphaToCoverage&&(n.alphaToCoverage=!0),!0===this.premultipliedAlpha&&(n.premultipliedAlpha=!0),!0===this.forceSinglePass&&(n.forceSinglePass=!0),!0===this.wireframe&&(n.wireframe=!0),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),"round"!==this.wireframeLinecap&&(n.wireframeLinecap=this.wireframeLinecap),"round"!==this.wireframeLinejoin&&(n.wireframeLinejoin=this.wireframeLinejoin),!0===this.flatShading&&(n.flatShading=!0),!1===this.visible&&(n.visible=!1),!1===this.toneMapped&&(n.toneMapped=!1),!1===this.fog&&(n.fog=!1),Object.keys(this.userData).length>0&&(n.userData=this.userData),e){const e=a(t.textures),i=a(t.images);e.length>0&&(n.textures=e),i.length>0&&(n.images=i)}return n}clone(){return(new this.constructor).copy(this)}copy(t){this.name=t.name,this.blending=t.blending,this.side=t.side,this.vertexColors=t.vertexColors,this.opacity=t.opacity,this.transparent=t.transparent,this.blendSrc=t.blendSrc,this.blendDst=t.blendDst,this.blendEquation=t.blendEquation,this.blendSrcAlpha=t.blendSrcAlpha,this.blendDstAlpha=t.blendDstAlpha,this.blendEquationAlpha=t.blendEquationAlpha,this.blendColor.copy(t.blendColor),this.blendAlpha=t.blendAlpha,this.depthFunc=t.depthFunc,this.depthTest=t.depthTest,this.depthWrite=t.depthWrite,this.stencilWriteMask=t.stencilWriteMask,this.stencilFunc=t.stencilFunc,this.stencilRef=t.stencilRef,this.stencilFuncMask=t.stencilFuncMask,this.stencilFail=t.stencilFail,this.stencilZFail=t.stencilZFail,this.stencilZPass=t.stencilZPass,this.stencilWrite=t.stencilWrite;const e=t.clippingPlanes;let n=null;if(null!==e){const t=e.length;n=new Array(t);for(let i=0;i!==t;++i)n[i]=e[i].clone()}return this.clippingPlanes=n,this.clipIntersection=t.clipIntersection,this.clipShadows=t.clipShadows,this.shadowSide=t.shadowSide,this.colorWrite=t.colorWrite,this.precision=t.precision,this.polygonOffset=t.polygonOffset,this.polygonOffsetFactor=t.polygonOffsetFactor,this.polygonOffsetUnits=t.polygonOffsetUnits,this.dithering=t.dithering,this.alphaTest=t.alphaTest,this.alphaHash=t.alphaHash,this.alphaToCoverage=t.alphaToCoverage,this.premultipliedAlpha=t.premultipliedAlpha,this.forceSinglePass=t.forceSinglePass,this.visible=t.visible,this.toneMapped=t.toneMapped,this.userData=JSON.parse(JSON.stringify(t.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(t){!0===t&&this.version++}onBuild(){console.warn("Material: onBuild() has been removed.")}}class oi extends ai{constructor(t){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new ii(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Mn,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.specularMap=t.specularMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.envMapRotation.copy(t.envMapRotation),this.combine=t.combine,this.reflectivity=t.reflectivity,this.refractionRatio=t.refractionRatio,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.fog=t.fog,this}}const li=ci();function ci(){const t=new ArrayBuffer(4),e=new Float32Array(t),n=new Uint32Array(t),i=new Uint32Array(512),r=new Uint32Array(512);for(let t=0;t<256;++t){const e=t-127;e<-27?(i[t]=0,i[256|t]=32768,r[t]=24,r[256|t]=24):e<-14?(i[t]=1024>>-e-14,i[256|t]=1024>>-e-14|32768,r[t]=-e-1,r[256|t]=-e-1):e<=15?(i[t]=e+15<<10,i[256|t]=e+15<<10|32768,r[t]=13,r[256|t]=13):e<128?(i[t]=31744,i[256|t]=64512,r[t]=24,r[256|t]=24):(i[t]=31744,i[256|t]=64512,r[t]=13,r[256|t]=13)}const s=new Uint32Array(2048),a=new Uint32Array(64),o=new Uint32Array(64);for(let t=1;t<1024;++t){let e=t<<13,n=0;for(;0==(8388608&e);)e<<=1,n-=8388608;e&=-8388609,n+=947912704,s[t]=e|n}for(let t=1024;t<2048;++t)s[t]=939524096+(t-1024<<13);for(let t=1;t<31;++t)a[t]=t<<23;a[31]=1199570944,a[32]=2147483648;for(let t=33;t<63;++t)a[t]=2147483648+(t-32<<23);a[63]=3347054592;for(let t=1;t<64;++t)32!==t&&(o[t]=1024);return{floatView:e,uint32View:n,baseTable:i,shiftTable:r,mantissaTable:s,exponentTable:a,offsetTable:o}}function hi(t){Math.abs(t)>65504&&console.warn("THREE.DataUtils.toHalfFloat(): Value out of range."),t=$t(t,-65504,65504),li.floatView[0]=t;const e=li.uint32View[0],n=e>>23&511;return li.baseTable[n]+((8388607&e)>>li.shiftTable[n])}function ui(t){const e=t>>10;return li.uint32View[0]=li.mantissaTable[li.offsetTable[e]+(1023&t)]+li.exponentTable[e],li.floatView[0]}const di={toHalfFloat:hi,fromHalfFloat:ui},pi=new De,mi=new re;class fi{constructor(t,e,n=!1){if(Array.isArray(t))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,this.name="",this.array=t,this.itemSize=e,this.count=void 0!==t?t.length/e:0,this.normalized=n,this.usage=Ht,this.updateRanges=[],this.gpuType=C,this.version=0}onUploadCallback(){}set needsUpdate(t){!0===t&&this.version++}setUsage(t){return this.usage=t,this}addUpdateRange(t,e){this.updateRanges.push({start:t,count:e})}clearUpdateRanges(){this.updateRanges.length=0}copy(t){return this.name=t.name,this.array=new t.array.constructor(t.array),this.itemSize=t.itemSize,this.count=t.count,this.normalized=t.normalized,this.usage=t.usage,this.gpuType=t.gpuType,this}copyAt(t,e,n){t*=this.itemSize,n*=e.itemSize;for(let i=0,r=this.itemSize;i0&&(t.userData=this.userData),void 0!==this.parameters){const e=this.parameters;for(const n in e)void 0!==e[n]&&(t[n]=e[n]);return t}t.data={attributes:{}};const e=this.index;null!==e&&(t.data.index={type:e.array.constructor.name,array:Array.prototype.slice.call(e.array)});const n=this.attributes;for(const e in n){const i=n[e];t.data.attributes[e]=i.toJSON(t.data)}const i={};let r=!1;for(const e in this.morphAttributes){const n=this.morphAttributes[e],s=[];for(let e=0,i=n.length;e0&&(i[e]=s,r=!0)}r&&(t.data.morphAttributes=i,t.data.morphTargetsRelative=this.morphTargetsRelative);const s=this.groups;s.length>0&&(t.data.groups=JSON.parse(JSON.stringify(s)));const a=this.boundingSphere;return null!==a&&(t.data.boundingSphere={center:a.center.toArray(),radius:a.radius}),t}clone(){return(new this.constructor).copy(this)}copy(t){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const e={};this.name=t.name;const n=t.index;null!==n&&this.setIndex(n.clone(e));const i=t.attributes;for(const t in i){const n=i[t];this.setAttribute(t,n.clone(e))}const r=t.morphAttributes;for(const t in r){const n=[],i=r[t];for(let t=0,r=i.length;t0){const n=t[e[0]];if(void 0!==n){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let t=0,e=n.length;t(t.far-t.near)**2)return}Ai.copy(r).invert(),Ri.copy(t.ray).applyMatrix4(Ai),null!==n.boundingBox&&!1===Ri.intersectsBox(n.boundingBox)||this._computeIntersections(t,e,Ri)}}_computeIntersections(t,e,n){let i;const r=this.geometry,s=this.material,a=r.index,o=r.attributes.position,l=r.attributes.uv,c=r.attributes.uv1,h=r.attributes.normal,u=r.groups,d=r.drawRange;if(null!==a)if(Array.isArray(s))for(let r=0,o=u.length;rn.far?null:{distance:c,point:Fi.clone(),object:t}}(t,e,n,i,Ii,Li,Ui,Oi);if(h){const t=new De;$n.getBarycoord(Oi,Ii,Li,Ui,t),r&&(h.uv=$n.getInterpolatedAttribute(r,o,l,c,t,new re)),s&&(h.uv1=$n.getInterpolatedAttribute(s,o,l,c,t,new re)),a&&(h.normal=$n.getInterpolatedAttribute(a,o,l,c,t,new De),h.normal.dot(i.direction)>0&&h.normal.multiplyScalar(-1));const e={a:o,b:l,c,normal:new De,materialIndex:0};$n.getNormal(Ii,Li,Ui,e.normal),h.face=e,h.barycoord=t}return h}class ki extends Ei{constructor(t=1,e=1,n=1,i=1,r=1,s=1){super(),this.type="BoxGeometry",this.parameters={width:t,height:e,depth:n,widthSegments:i,heightSegments:r,depthSegments:s};const a=this;i=Math.floor(i),r=Math.floor(r),s=Math.floor(s);const o=[],l=[],c=[],h=[];let u=0,d=0;function p(t,e,n,i,r,s,p,m,f,g,v){const _=s/f,x=p/g,y=s/2,M=p/2,S=m/2,b=f+1,w=g+1;let T=0,E=0;const A=new De;for(let s=0;s0?1:-1,c.push(A.x,A.y,A.z),h.push(o/f),h.push(1-s/g),T+=1}}for(let t=0;t0&&(e.defines=this.defines),e.vertexShader=this.vertexShader,e.fragmentShader=this.fragmentShader,e.lights=this.lights,e.clipping=this.clipping;const n={};for(const t in this.extensions)!0===this.extensions[t]&&(n[t]=!0);return Object.keys(n).length>0&&(e.extensions=n),e}}class ji extends Bn{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new un,this.projectionMatrix=new un,this.projectionMatrixInverse=new un,this.coordinateSystem=Wt}copy(t,e){return super.copy(t,e),this.matrixWorldInverse.copy(t.matrixWorldInverse),this.projectionMatrix.copy(t.projectionMatrix),this.projectionMatrixInverse.copy(t.projectionMatrixInverse),this.coordinateSystem=t.coordinateSystem,this}getWorldDirection(t){return super.getWorldDirection(t).negate()}updateMatrixWorld(t){super.updateMatrixWorld(t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(t,e){super.updateWorldMatrix(t,e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return(new this.constructor).copy(this)}}const qi=new De,Yi=new re,Zi=new re;class Ji extends ji{constructor(t=50,e=1,n=.1,i=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=t,this.zoom=1,this.near=n,this.far=i,this.focus=10,this.aspect=e,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(t,e){return super.copy(t,e),this.fov=t.fov,this.zoom=t.zoom,this.near=t.near,this.far=t.far,this.focus=t.focus,this.aspect=t.aspect,this.view=null===t.view?null:Object.assign({},t.view),this.filmGauge=t.filmGauge,this.filmOffset=t.filmOffset,this}setFocalLength(t){const e=.5*this.getFilmHeight()/t;this.fov=2*Jt*Math.atan(e),this.updateProjectionMatrix()}getFocalLength(){const t=Math.tan(.5*Zt*this.fov);return.5*this.getFilmHeight()/t}getEffectiveFOV(){return 2*Jt*Math.atan(Math.tan(.5*Zt*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(t,e,n){qi.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),e.set(qi.x,qi.y).multiplyScalar(-t/qi.z),qi.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(qi.x,qi.y).multiplyScalar(-t/qi.z)}getViewSize(t,e){return this.getViewBounds(t,Yi,Zi),e.subVectors(Zi,Yi)}setViewOffset(t,e,n,i,r,s){this.aspect=t/e,null===this.view&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=t,this.view.fullHeight=e,this.view.offsetX=n,this.view.offsetY=i,this.view.width=r,this.view.height=s,this.updateProjectionMatrix()}clearViewOffset(){null!==this.view&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const t=this.near;let e=t*Math.tan(.5*Zt*this.fov)/this.zoom,n=2*e,i=this.aspect*n,r=-.5*i;const s=this.view;if(null!==this.view&&this.view.enabled){const t=s.fullWidth,a=s.fullHeight;r+=s.offsetX*i/t,e-=s.offsetY*n/a,i*=s.width/t,n*=s.height/a}const a=this.filmOffset;0!==a&&(r+=t*a/this.getFilmWidth()),this.projectionMatrix.makePerspective(r,r+i,e,e-n,t,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(t){const e=super.toJSON(t);return e.object.fov=this.fov,e.object.zoom=this.zoom,e.object.near=this.near,e.object.far=this.far,e.object.focus=this.focus,e.object.aspect=this.aspect,null!==this.view&&(e.object.view=Object.assign({},this.view)),e.object.filmGauge=this.filmGauge,e.object.filmOffset=this.filmOffset,e}}const Ki=-90;class $i extends Bn{constructor(t,e,n){super(),this.type="CubeCamera",this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;const i=new Ji(Ki,1,t,e);i.layers=this.layers,this.add(i);const r=new Ji(Ki,1,t,e);r.layers=this.layers,this.add(r);const s=new Ji(Ki,1,t,e);s.layers=this.layers,this.add(s);const a=new Ji(Ki,1,t,e);a.layers=this.layers,this.add(a);const o=new Ji(Ki,1,t,e);o.layers=this.layers,this.add(o);const l=new Ji(Ki,1,t,e);l.layers=this.layers,this.add(l)}updateCoordinateSystem(){const t=this.coordinateSystem,e=this.children.concat(),[n,i,r,s,a,o]=e;for(const t of e)this.remove(t);if(t===Wt)n.up.set(0,1,0),n.lookAt(1,0,0),i.up.set(0,1,0),i.lookAt(-1,0,0),r.up.set(0,0,-1),r.lookAt(0,1,0),s.up.set(0,0,1),s.lookAt(0,-1,0),a.up.set(0,1,0),a.lookAt(0,0,1),o.up.set(0,1,0),o.lookAt(0,0,-1);else{if(t!==Xt)throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+t);n.up.set(0,-1,0),n.lookAt(-1,0,0),i.up.set(0,-1,0),i.lookAt(1,0,0),r.up.set(0,0,1),r.lookAt(0,1,0),s.up.set(0,0,-1),s.lookAt(0,-1,0),a.up.set(0,-1,0),a.lookAt(0,0,1),o.up.set(0,-1,0),o.lookAt(0,0,-1)}for(const t of e)this.add(t),t.updateMatrixWorld()}update(t,e){null===this.parent&&this.updateMatrixWorld();const{renderTarget:n,activeMipmapLevel:i}=this;this.coordinateSystem!==t.coordinateSystem&&(this.coordinateSystem=t.coordinateSystem,this.updateCoordinateSystem());const[r,s,a,o,l,c]=this.children,h=t.getRenderTarget(),u=t.getActiveCubeFace(),d=t.getActiveMipmapLevel(),p=t.xr.enabled;t.xr.enabled=!1;const m=n.texture.generateMipmaps;n.texture.generateMipmaps=!1,t.setRenderTarget(n,0,i),t.render(e,r),t.setRenderTarget(n,1,i),t.render(e,s),t.setRenderTarget(n,2,i),t.render(e,a),t.setRenderTarget(n,3,i),t.render(e,o),t.setRenderTarget(n,4,i),t.render(e,l),n.texture.generateMipmaps=m,t.setRenderTarget(n,5,i),t.render(e,c),t.setRenderTarget(h,u,d),t.xr.enabled=p,n.texture.needsPMREMUpdate=!0}}class Qi extends Ae{constructor(t,e,n,i,r,s,a,o,l,h){super(t=void 0!==t?t:[],e=void 0!==e?e:c,n,i,r,s,a,o,l,h),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(t){this.image=t}}class tr extends Pe{constructor(t=1,e={}){super(t,t,e),this.isWebGLCubeRenderTarget=!0;const n={width:t,height:t,depth:1},i=[n,n,n,n,n,n];this.texture=new Qi(i,e.mapping,e.wrapS,e.wrapT,e.magFilter,e.minFilter,e.format,e.type,e.anisotropy,e.colorSpace),this.texture.isRenderTargetTexture=!0,this.texture.generateMipmaps=void 0!==e.generateMipmaps&&e.generateMipmaps,this.texture.minFilter=void 0!==e.minFilter?e.minFilter:y}fromEquirectangularTexture(t,e){this.texture.type=e.type,this.texture.colorSpace=e.colorSpace,this.texture.generateMipmaps=e.generateMipmaps,this.texture.minFilter=e.minFilter,this.texture.magFilter=e.magFilter;const n={tEquirect:{value:null}},i="\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\tvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\n\t\t\t\t\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n\n\t\t\t\t}\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvWorldDirection = transformDirection( position, modelMatrix );\n\n\t\t\t\t\t#include \n\t\t\t\t\t#include \n\n\t\t\t\t}\n\t\t\t",r="\n\n\t\t\t\tuniform sampler2D tEquirect;\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\t#include \n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvec3 direction = normalize( vWorldDirection );\n\n\t\t\t\t\tvec2 sampleUV = equirectUv( direction );\n\n\t\t\t\t\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\n\t\t\t\t}\n\t\t\t",s=new ki(5,5,5),a=new Xi({name:"CubemapFromEquirect",uniforms:Vi(n),vertexShader:i,fragmentShader:r,side:1,blending:0});a.uniforms.tEquirect.value=e;const o=new Bi(s,a),l=e.minFilter;return e.minFilter===S&&(e.minFilter=y),new $i(1,10,this).update(t,o),e.minFilter=l,o.geometry.dispose(),o.material.dispose(),this}clear(t,e,n,i){const r=t.getRenderTarget();for(let r=0;r<6;r++)t.setRenderTarget(this,r),t.clear(e,n,i);t.setRenderTarget(r)}}const er=new De,nr=new De,ir=new se;class rr{constructor(t=new De(1,0,0),e=0){this.isPlane=!0,this.normal=t,this.constant=e}set(t,e){return this.normal.copy(t),this.constant=e,this}setComponents(t,e,n,i){return this.normal.set(t,e,n),this.constant=i,this}setFromNormalAndCoplanarPoint(t,e){return this.normal.copy(t),this.constant=-e.dot(this.normal),this}setFromCoplanarPoints(t,e,n){const i=er.subVectors(n,e).cross(nr.subVectors(t,e)).normalize();return this.setFromNormalAndCoplanarPoint(i,t),this}copy(t){return this.normal.copy(t.normal),this.constant=t.constant,this}normalize(){const t=1/this.normal.length();return this.normal.multiplyScalar(t),this.constant*=t,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(t){return this.normal.dot(t)+this.constant}distanceToSphere(t){return this.distanceToPoint(t.center)-t.radius}projectPoint(t,e){return e.copy(t).addScaledVector(this.normal,-this.distanceToPoint(t))}intersectLine(t,e){const n=t.delta(er),i=this.normal.dot(n);if(0===i)return 0===this.distanceToPoint(t.start)?e.copy(t.start):null;const r=-(t.start.dot(this.normal)+this.constant)/i;return r<0||r>1?null:e.copy(t.start).addScaledVector(n,r)}intersectsLine(t){const e=this.distanceToPoint(t.start),n=this.distanceToPoint(t.end);return e<0&&n>0||n<0&&e>0}intersectsBox(t){return t.intersectsPlane(this)}intersectsSphere(t){return t.intersectsPlane(this)}coplanarPoint(t){return t.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(t,e){const n=e||ir.getNormalMatrix(t),i=this.coplanarPoint(er).applyMatrix4(t),r=this.normal.applyMatrix3(n).normalize();return this.constant=-i.dot(r),this}translate(t){return this.constant-=t.dot(this.normal),this}equals(t){return t.normal.equals(this.normal)&&t.constant===this.constant}clone(){return(new this.constructor).copy(this)}}const sr=new en,ar=new De;class or{constructor(t=new rr,e=new rr,n=new rr,i=new rr,r=new rr,s=new rr){this.planes=[t,e,n,i,r,s]}set(t,e,n,i,r,s){const a=this.planes;return a[0].copy(t),a[1].copy(e),a[2].copy(n),a[3].copy(i),a[4].copy(r),a[5].copy(s),this}copy(t){const e=this.planes;for(let n=0;n<6;n++)e[n].copy(t.planes[n]);return this}setFromProjectionMatrix(t,e=2e3){const n=this.planes,i=t.elements,r=i[0],s=i[1],a=i[2],o=i[3],l=i[4],c=i[5],h=i[6],u=i[7],d=i[8],p=i[9],m=i[10],f=i[11],g=i[12],v=i[13],_=i[14],x=i[15];if(n[0].setComponents(o-r,u-l,f-d,x-g).normalize(),n[1].setComponents(o+r,u+l,f+d,x+g).normalize(),n[2].setComponents(o+s,u+c,f+p,x+v).normalize(),n[3].setComponents(o-s,u-c,f-p,x-v).normalize(),n[4].setComponents(o-a,u-h,f-m,x-_).normalize(),e===Wt)n[5].setComponents(o+a,u+h,f+m,x+_).normalize();else{if(e!==Xt)throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+e);n[5].setComponents(a,h,m,_).normalize()}return this}intersectsObject(t){if(void 0!==t.boundingSphere)null===t.boundingSphere&&t.computeBoundingSphere(),sr.copy(t.boundingSphere).applyMatrix4(t.matrixWorld);else{const e=t.geometry;null===e.boundingSphere&&e.computeBoundingSphere(),sr.copy(e.boundingSphere).applyMatrix4(t.matrixWorld)}return this.intersectsSphere(sr)}intersectsSprite(t){return sr.center.set(0,0,0),sr.radius=.7071067811865476,sr.applyMatrix4(t.matrixWorld),this.intersectsSphere(sr)}intersectsSphere(t){const e=this.planes,n=t.center,i=-t.radius;for(let t=0;t<6;t++)if(e[t].distanceToPoint(n)0?t.max.x:t.min.x,ar.y=i.normal.y>0?t.max.y:t.min.y,ar.z=i.normal.z>0?t.max.z:t.min.z,i.distanceToPoint(ar)<0)return!1}return!0}containsPoint(t){const e=this.planes;for(let n=0;n<6;n++)if(e[n].distanceToPoint(t)<0)return!1;return!0}clone(){return(new this.constructor).copy(this)}}function lr(){let t=null,e=!1,n=null,i=null;function r(e,s){n(e,s),i=t.requestAnimationFrame(r)}return{start:function(){!0!==e&&null!==n&&(i=t.requestAnimationFrame(r),e=!0)},stop:function(){t.cancelAnimationFrame(i),e=!1},setAnimationLoop:function(t){n=t},setContext:function(e){t=e}}}function cr(t){const e=new WeakMap;return{get:function(t){return t.isInterleavedBufferAttribute&&(t=t.data),e.get(t)},remove:function(n){n.isInterleavedBufferAttribute&&(n=n.data);const i=e.get(n);i&&(t.deleteBuffer(i.buffer),e.delete(n))},update:function(n,i){if(n.isInterleavedBufferAttribute&&(n=n.data),n.isGLBufferAttribute){const t=e.get(n);return void((!t||t.versiont.start-e.start));let e=0;for(let t=1;t 0\n\tvec4 plane;\n\t#ifdef ALPHA_TO_COVERAGE\n\t\tfloat distanceToPlane, distanceGradient;\n\t\tfloat clipOpacity = 1.0;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tdistanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n\t\t\tdistanceGradient = fwidth( distanceToPlane ) / 2.0;\n\t\t\tclipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n\t\t\tif ( clipOpacity == 0.0 ) discard;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\t\tfloat unionClipOpacity = 1.0;\n\t\t\t#pragma unroll_loop_start\n\t\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\t\tplane = clippingPlanes[ i ];\n\t\t\t\tdistanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n\t\t\t\tdistanceGradient = fwidth( distanceToPlane ) / 2.0;\n\t\t\t\tunionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n\t\t\t}\n\t\t\t#pragma unroll_loop_end\n\t\t\tclipOpacity *= 1.0 - unionClipOpacity;\n\t\t#endif\n\t\tdiffuseColor.a *= clipOpacity;\n\t\tif ( diffuseColor.a == 0.0 ) discard;\n\t#else\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\t\tbool clipped = true;\n\t\t\t#pragma unroll_loop_start\n\t\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\t\tplane = clippingPlanes[ i ];\n\t\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t\t}\n\t\t\t#pragma unroll_loop_end\n\t\t\tif ( clipped ) discard;\n\t\t#endif\n\t#endif\n#endif",clipping_planes_pars_fragment:"#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif",clipping_planes_pars_vertex:"#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif",clipping_planes_vertex:"#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif",color_fragment:"#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif",color_pars_fragment:"#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif",color_pars_vertex:"#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )\n\tvarying vec3 vColor;\n#endif",color_vertex:"#if defined( USE_COLOR_ALPHA )\n\tvColor = vec4( 1.0 );\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )\n\tvColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n\tvColor *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.xyz *= instanceColor.xyz;\n#endif\n#ifdef USE_BATCHING_COLOR\n\tvec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) );\n\tvColor.xyz *= batchingColor.xyz;\n#endif",common:"#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement( a ) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nvec3 pow2( const in vec3 x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\nfloat average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract( sin( sn ) * c );\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\n#ifdef USE_ALPHAHASH\n\tvarying vec3 vPosition;\n#endif\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}\nvec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat F_Schlick( const in float f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n} // validated",cube_uv_reflection_fragment:"#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_minTileSize 16.0\n\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\thighp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tuv.x += filterInt * 3.0 * cubeUV_minTileSize;\n\t\tuv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );\n\t\tuv.x *= CUBEUV_TEXEL_WIDTH;\n\t\tuv.y *= CUBEUV_TEXEL_HEIGHT;\n\t\t#ifdef texture2DGradEXT\n\t\t\treturn texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;\n\t\t#else\n\t\t\treturn texture2D( envMap, uv ).rgb;\n\t\t#endif\n\t}\n\t#define cubeUV_r0 1.0\n\t#define cubeUV_m0 - 2.0\n\t#define cubeUV_r1 0.8\n\t#define cubeUV_m1 - 1.0\n\t#define cubeUV_r4 0.4\n\t#define cubeUV_m4 2.0\n\t#define cubeUV_r5 0.305\n\t#define cubeUV_m5 3.0\n\t#define cubeUV_r6 0.21\n\t#define cubeUV_m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= cubeUV_r1 ) {\n\t\t\tmip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;\n\t\t} else if ( roughness >= cubeUV_r4 ) {\n\t\t\tmip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;\n\t\t} else if ( roughness >= cubeUV_r5 ) {\n\t\t\tmip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;\n\t\t} else if ( roughness >= cubeUV_r6 ) {\n\t\t\tmip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif",defaultnormal_vertex:"vec3 transformedNormal = objectNormal;\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = objectTangent;\n#endif\n#ifdef USE_BATCHING\n\tmat3 bm = mat3( batchingMatrix );\n\ttransformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) );\n\ttransformedNormal = bm * transformedNormal;\n\t#ifdef USE_TANGENT\n\t\ttransformedTangent = bm * transformedTangent;\n\t#endif\n#endif\n#ifdef USE_INSTANCING\n\tmat3 im = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) );\n\ttransformedNormal = im * transformedNormal;\n\t#ifdef USE_TANGENT\n\t\ttransformedTangent = im * transformedTangent;\n\t#endif\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\ttransformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif",displacementmap_pars_vertex:"#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif",displacementmap_vertex:"#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );\n#endif",emissivemap_fragment:"#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif",emissivemap_pars_fragment:"#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif",colorspace_fragment:"gl_FragColor = linearToOutputTexel( gl_FragColor );",colorspace_pars_fragment:"\nconst mat3 LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 = mat3(\n\tvec3( 0.8224621, 0.177538, 0.0 ),\n\tvec3( 0.0331941, 0.9668058, 0.0 ),\n\tvec3( 0.0170827, 0.0723974, 0.9105199 )\n);\nconst mat3 LINEAR_DISPLAY_P3_TO_LINEAR_SRGB = mat3(\n\tvec3( 1.2249401, - 0.2249404, 0.0 ),\n\tvec3( - 0.0420569, 1.0420571, 0.0 ),\n\tvec3( - 0.0196376, - 0.0786361, 1.0982735 )\n);\nvec4 LinearSRGBToLinearDisplayP3( in vec4 value ) {\n\treturn vec4( value.rgb * LINEAR_SRGB_TO_LINEAR_DISPLAY_P3, value.a );\n}\nvec4 LinearDisplayP3ToLinearSRGB( in vec4 value ) {\n\treturn vec4( value.rgb * LINEAR_DISPLAY_P3_TO_LINEAR_SRGB, value.a );\n}\nvec4 LinearTransferOETF( in vec4 value ) {\n\treturn value;\n}\nvec4 sRGBTransferOETF( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}",envmap_fragment:"#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif",envmap_common_pars_fragment:"#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\tuniform mat3 envMapRotation;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif",envmap_pars_fragment:"#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif",envmap_pars_vertex:"#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif",envmap_physical_pars_fragment:"#ifdef USE_ENVMAP\n\tvec3 getIBLIrradiance( const in vec3 normal ) {\n\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 );\n\t\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\tvec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\tvec3 reflectVec = reflect( - viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness );\n\t\t\treturn envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\t#ifdef USE_ANISOTROPY\n\t\tvec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {\n\t\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\t\tvec3 bentNormal = cross( bitangent, viewDir );\n\t\t\t\tbentNormal = normalize( cross( bentNormal, bitangent ) );\n\t\t\t\tbentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );\n\t\t\t\treturn getIBLRadiance( viewDir, bentNormal, roughness );\n\t\t\t#else\n\t\t\t\treturn vec3( 0.0 );\n\t\t\t#endif\n\t\t}\n\t#endif\n#endif",envmap_vertex:"#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif",fog_vertex:"#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif",fog_pars_vertex:"#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif",fog_fragment:"#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, vFogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif",fog_pars_fragment:"#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float vFogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif",gradientmap_pars_fragment:"#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn vec3( texture2D( gradientMap, coord ).r );\n\t#else\n\t\tvec2 fw = fwidth( coord ) * 0.5;\n\t\treturn mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );\n\t#endif\n}",lightmap_pars_fragment:"#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif",lights_lambert_fragment:"LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;",lights_lambert_pars_fragment:"varying vec3 vViewPosition;\nstruct LambertMaterial {\n\tvec3 diffuseColor;\n\tfloat specularStrength;\n};\nvoid RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Lambert\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Lambert",lights_pars_begin:"uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\n#if defined( USE_LIGHT_PROBES )\n\tuniform vec3 lightProbe[ 9 ];\n#endif\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {\n\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\treturn irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\tif ( cutoffDistance > 0.0 ) {\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t}\n\treturn distanceFalloff;\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n\treturn smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) {\n\t\tlight.color = directionalLight.color;\n\t\tlight.direction = directionalLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometryPosition;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tlight.color = pointLight.color;\n\t\tlight.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometryPosition;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat angleCos = dot( light.direction, spotLight.direction );\n\t\tfloat spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\tif ( spotAttenuation > 0.0 ) {\n\t\t\tfloat lightDistance = length( lVector );\n\t\t\tlight.color = spotLight.color * spotAttenuation;\n\t\t\tlight.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t\t} else {\n\t\t\tlight.color = vec3( 0.0 );\n\t\t\tlight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {\n\t\tfloat dotNL = dot( normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\treturn irradiance;\n\t}\n#endif",lights_toon_fragment:"ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;",lights_toon_pars_fragment:"varying vec3 vViewPosition;\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon",lights_phong_fragment:"BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;",lights_phong_pars_fragment:"varying vec3 vViewPosition;\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong",lights_physical_fragment:"PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n\tmaterial.ior = ior;\n\t#ifdef USE_SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULAR_COLORMAP\n\t\t\tspecularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb;\n\t\t#endif\n\t\t#ifdef USE_SPECULAR_INTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularColorFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_DISPERSION\n\tmaterial.dispersion = dispersion;\n#endif\n#ifdef USE_IRIDESCENCE\n\tmaterial.iridescence = iridescence;\n\tmaterial.iridescenceIOR = iridescenceIOR;\n\t#ifdef USE_IRIDESCENCEMAP\n\t\tmaterial.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r;\n\t#endif\n\t#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\t\tmaterial.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum;\n\t#else\n\t\tmaterial.iridescenceThickness = iridescenceThicknessMaximum;\n\t#endif\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheenColor;\n\t#ifdef USE_SHEEN_COLORMAP\n\t\tmaterial.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\t#ifdef USE_ANISOTROPYMAP\n\t\tmat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x );\n\t\tvec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb;\n\t\tvec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b;\n\t#else\n\t\tvec2 anisotropyV = anisotropyVector;\n\t#endif\n\tmaterial.anisotropy = length( anisotropyV );\n\tif( material.anisotropy == 0.0 ) {\n\t\tanisotropyV = vec2( 1.0, 0.0 );\n\t} else {\n\t\tanisotropyV /= material.anisotropy;\n\t\tmaterial.anisotropy = saturate( material.anisotropy );\n\t}\n\tmaterial.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) );\n\tmaterial.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y;\n\tmaterial.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y;\n#endif",lights_physical_pars_fragment:"struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat roughness;\n\tvec3 specularColor;\n\tfloat specularF90;\n\tfloat dispersion;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_IRIDESCENCE\n\t\tfloat iridescence;\n\t\tfloat iridescenceIOR;\n\t\tfloat iridescenceThickness;\n\t\tvec3 iridescenceFresnel;\n\t\tvec3 iridescenceF0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenColor;\n\t\tfloat sheenRoughness;\n\t#endif\n\t#ifdef IOR\n\t\tfloat ior;\n\t#endif\n\t#ifdef USE_TRANSMISSION\n\t\tfloat transmission;\n\t\tfloat transmissionAlpha;\n\t\tfloat thickness;\n\t\tfloat attenuationDistance;\n\t\tvec3 attenuationColor;\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tfloat anisotropy;\n\t\tfloat alphaT;\n\t\tvec3 anisotropyT;\n\t\tvec3 anisotropyB;\n\t#endif\n};\nvec3 clearcoatSpecularDirect = vec3( 0.0 );\nvec3 clearcoatSpecularIndirect = vec3( 0.0 );\nvec3 sheenSpecularDirect = vec3( 0.0 );\nvec3 sheenSpecularIndirect = vec3(0.0 );\nvec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {\n float x = clamp( 1.0 - dotVH, 0.0, 1.0 );\n float x2 = x * x;\n float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );\n return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );\n}\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\n#ifdef USE_ANISOTROPY\n\tfloat V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) {\n\t\tfloat gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) );\n\t\tfloat gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) );\n\t\tfloat v = 0.5 / ( gv + gl );\n\t\treturn saturate(v);\n\t}\n\tfloat D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) {\n\t\tfloat a2 = alphaT * alphaB;\n\t\thighp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH );\n\t\thighp float v2 = dot( v, v );\n\t\tfloat w2 = a2 / v2;\n\t\treturn RECIPROCAL_PI * a2 * pow2 ( w2 );\n\t}\n#endif\n#ifdef USE_CLEARCOAT\n\tvec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) {\n\t\tvec3 f0 = material.clearcoatF0;\n\t\tfloat f90 = material.clearcoatF90;\n\t\tfloat roughness = material.clearcoatRoughness;\n\t\tfloat alpha = pow2( roughness );\n\t\tvec3 halfDir = normalize( lightDir + viewDir );\n\t\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\t\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\t\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\t\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\t\tvec3 F = F_Schlick( f0, f90, dotVH );\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t\treturn F * ( V * D );\n\t}\n#endif\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {\n\tvec3 f0 = material.specularColor;\n\tfloat f90 = material.specularF90;\n\tfloat roughness = material.roughness;\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( f0, f90, dotVH );\n\t#ifdef USE_IRIDESCENCE\n\t\tF = mix( F, material.iridescenceFresnel, material.iridescence );\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tfloat dotTL = dot( material.anisotropyT, lightDir );\n\t\tfloat dotTV = dot( material.anisotropyT, viewDir );\n\t\tfloat dotTH = dot( material.anisotropyT, halfDir );\n\t\tfloat dotBL = dot( material.anisotropyB, lightDir );\n\t\tfloat dotBV = dot( material.anisotropyB, viewDir );\n\t\tfloat dotBH = dot( material.anisotropyB, halfDir );\n\t\tfloat V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL );\n\t\tfloat D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH );\n\t#else\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t#endif\n\treturn F * ( V * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n\tfloat alpha = pow2( roughness );\n\tfloat invAlpha = 1.0 / alpha;\n\tfloat cos2h = dotNH * dotNH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n\treturn saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );\n}\nvec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat D = D_Charlie( sheenRoughness, dotNH );\n\tfloat V = V_Neubelt( dotNV, dotNL );\n\treturn sheenColor * ( D * V );\n}\n#endif\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat r2 = roughness * roughness;\n\tfloat a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;\n\tfloat b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;\n\tfloat DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );\n\treturn saturate( DG * RECIPROCAL_PI );\n}\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n\treturn fab;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\n#ifdef USE_IRIDESCENCE\nvoid computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#else\nvoid computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#endif\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\t#ifdef USE_IRIDESCENCE\n\t\tvec3 Fr = mix( specularColor, iridescenceF0, iridescence );\n\t#else\n\t\tvec3 Fr = specularColor;\n\t#endif\n\tvec3 FssEss = Fr * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometryNormal;\n\t\tvec3 viewDir = geometryViewDir;\n\t\tvec3 position = geometryPosition;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );\n\t#endif\n\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material );\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n\t#endif\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\t#ifdef USE_IRIDESCENCE\n\t\tcomputeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );\n\t#else\n\t\tcomputeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n\t#endif\n\tvec3 totalScattering = singleScattering + multiScattering;\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );\n\treflectedLight.indirectSpecular += radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}",lights_fragment_begin:"\nvec3 geometryPosition = - vViewPosition;\nvec3 geometryNormal = normal;\nvec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\nvec3 geometryClearcoatNormal = vec3( 0.0 );\n#ifdef USE_CLEARCOAT\n\tgeometryClearcoatNormal = clearcoatNormal;\n#endif\n#ifdef USE_IRIDESCENCE\n\tfloat dotNVi = saturate( dot( normal, geometryViewDir ) );\n\tif ( material.iridescenceThickness == 0.0 ) {\n\t\tmaterial.iridescence = 0.0;\n\t} else {\n\t\tmaterial.iridescence = saturate( material.iridescence );\n\t}\n\tif ( material.iridescence > 0.0 ) {\n\t\tmaterial.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );\n\t\tmaterial.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );\n\t}\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometryPosition, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tvec4 spotColor;\n\tvec3 spotLightCoord;\n\tbool inSpotLightMap;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometryPosition, directLight );\n\t\t#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX\n\t\t#elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t#define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS\n\t\t#else\n\t\t#define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#endif\n\t\t#if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )\n\t\t\tspotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;\n\t\t\tinSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );\n\t\t\tspotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );\n\t\t\tdirectLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;\n\t\t#endif\n\t\t#undef SPOT_LIGHT_MAP_INDEX\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\t#if defined( USE_LIGHT_PROBES )\n\t\tirradiance += getLightProbeIrradiance( lightProbe, geometryNormal );\n\t#endif\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif",lights_fragment_maps:"#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\t\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getIBLIrradiance( geometryNormal );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\t#ifdef USE_ANISOTROPY\n\t\tradiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );\n\t#else\n\t\tradiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness );\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif",lights_fragment_end:"#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif",logdepthbuf_fragment:"#if defined( USE_LOGDEPTHBUF )\n\tgl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif",logdepthbuf_pars_fragment:"#if defined( USE_LOGDEPTHBUF )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif",logdepthbuf_pars_vertex:"#ifdef USE_LOGDEPTHBUF\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif",logdepthbuf_vertex:"#ifdef USE_LOGDEPTHBUF\n\tvFragDepth = 1.0 + gl_Position.w;\n\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n#endif",map_fragment:"#ifdef USE_MAP\n\tvec4 sampledDiffuseColor = texture2D( map, vMapUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tsampledDiffuseColor = vec4( mix( pow( sampledDiffuseColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), sampledDiffuseColor.rgb * 0.0773993808, vec3( lessThanEqual( sampledDiffuseColor.rgb, vec3( 0.04045 ) ) ) ), sampledDiffuseColor.w );\n\t\n\t#endif\n\tdiffuseColor *= sampledDiffuseColor;\n#endif",map_pars_fragment:"#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif",map_particle_fragment:"#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\t#if defined( USE_POINTS_UV )\n\t\tvec2 uv = vUv;\n\t#else\n\t\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n\t#endif\n#endif\n#ifdef USE_MAP\n\tdiffuseColor *= texture2D( map, uv );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif",map_particle_pars_fragment:"#if defined( USE_POINTS_UV )\n\tvarying vec2 vUv;\n#else\n\t#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\t\tuniform mat3 uvTransform;\n\t#endif\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif",metalnessmap_fragment:"float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif",metalnessmap_pars_fragment:"#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif",morphinstance_vertex:"#ifdef USE_INSTANCING_MORPH\n\tfloat morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\tfloat morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tmorphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r;\n\t}\n#endif",morphcolor_vertex:"#if defined( USE_MORPHCOLORS )\n\tvColor *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t#if defined( USE_COLOR_ALPHA )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];\n\t\t#elif defined( USE_COLOR )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];\n\t\t#endif\n\t}\n#endif",morphnormal_vertex:"#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tif ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];\n\t}\n#endif",morphtarget_pars_vertex:"#ifdef USE_MORPHTARGETS\n\t#ifndef USE_INSTANCING_MORPH\n\t\tuniform float morphTargetBaseInfluence;\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t#endif\n\tuniform sampler2DArray morphTargetsTexture;\n\tuniform ivec2 morphTargetsTextureSize;\n\tvec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n\t\tint texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n\t\tint y = texelIndex / morphTargetsTextureSize.x;\n\t\tint x = texelIndex - y * morphTargetsTextureSize.x;\n\t\tivec3 morphUV = ivec3( x, y, morphTargetIndex );\n\t\treturn texelFetch( morphTargetsTexture, morphUV, 0 );\n\t}\n#endif",morphtarget_vertex:"#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];\n\t}\n#endif",normal_fragment_begin:"float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\n\tvec3 fdx = dFdx( vViewPosition );\n\tvec3 fdy = dFdy( vViewPosition );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal *= faceDirection;\n\t#endif\n#endif\n#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )\n\t#ifdef USE_TANGENT\n\t\tmat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\t#else\n\t\tmat3 tbn = getTangentFrame( - vViewPosition, normal,\n\t\t#if defined( USE_NORMALMAP )\n\t\t\tvNormalMapUv\n\t\t#elif defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tvClearcoatNormalMapUv\n\t\t#else\n\t\t\tvUv\n\t\t#endif\n\t\t);\n\t#endif\n\t#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n\t\ttbn[0] *= faceDirection;\n\t\ttbn[1] *= faceDirection;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\t#ifdef USE_TANGENT\n\t\tmat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\t#else\n\t\tmat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );\n\t#endif\n\t#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n\t\ttbn2[0] *= faceDirection;\n\t\ttbn2[1] *= faceDirection;\n\t#endif\n#endif\nvec3 nonPerturbedNormal = normal;",normal_fragment_maps:"#ifdef USE_NORMALMAP_OBJECTSPACE\n\tnormal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( USE_NORMALMAP_TANGENTSPACE )\n\tvec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\tnormal = normalize( tbn * mapN );\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif",normal_pars_fragment:"#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif",normal_pars_vertex:"#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif",normal_vertex:"#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif",normalmap_pars_fragment:"#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef USE_NORMALMAP_OBJECTSPACE\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) )\n\tmat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {\n\t\tvec3 q0 = dFdx( eye_pos.xyz );\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\n\t\tvec2 st0 = dFdx( uv.st );\n\t\tvec2 st1 = dFdy( uv.st );\n\t\tvec3 N = surf_norm;\n\t\tvec3 q1perp = cross( q1, N );\n\t\tvec3 q0perp = cross( N, q0 );\n\t\tvec3 T = q1perp * st0.x + q0perp * st1.x;\n\t\tvec3 B = q1perp * st0.y + q0perp * st1.y;\n\t\tfloat det = max( dot( T, T ), dot( B, B ) );\n\t\tfloat scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );\n\t\treturn mat3( T * scale, B * scale, N );\n\t}\n#endif",clearcoat_normal_fragment_begin:"#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = nonPerturbedNormal;\n#endif",clearcoat_normal_fragment_maps:"#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\tclearcoatNormal = normalize( tbn2 * clearcoatMapN );\n#endif",clearcoat_pars_fragment:"#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif",iridescence_pars_fragment:"#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif",opaque_fragment:"#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= material.transmissionAlpha;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );",packing:"vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.;\nconst float Inv255 = 1. / 255.;\nconst vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 );\nconst vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g );\nconst vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b );\nconst vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a );\nvec4 packDepthToRGBA( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec4( 0., 0., 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec4( 1., 1., 1., 1. );\n\tfloat vuf;\n\tfloat af = modf( v * PackFactors.a, vuf );\n\tfloat bf = modf( vuf * ShiftRight8, vuf );\n\tfloat gf = modf( vuf * ShiftRight8, vuf );\n\treturn vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af );\n}\nvec3 packDepthToRGB( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec3( 0., 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec3( 1., 1., 1. );\n\tfloat vuf;\n\tfloat bf = modf( v * PackFactors.b, vuf );\n\tfloat gf = modf( vuf * ShiftRight8, vuf );\n\treturn vec3( vuf * Inv255, gf * PackUpscale, bf );\n}\nvec2 packDepthToRG( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec2( 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec2( 1., 1. );\n\tfloat vuf;\n\tfloat gf = modf( v * 256., vuf );\n\treturn vec2( vuf * Inv255, gf );\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors4 );\n}\nfloat unpackRGBToDepth( const in vec3 v ) {\n\treturn dot( v, UnpackFactors3 );\n}\nfloat unpackRGToDepth( const in vec2 v ) {\n\treturn v.r * UnpackFactors2.r + v.g * UnpackFactors2.g;\n}\nvec4 pack2HalfToRGBA( const in vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );\n}\nvec2 unpackRGBATo2Half( const in vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) {\n\treturn depth * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * depth - far );\n}",premultiplied_alpha_fragment:"#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif",project_vertex:"vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_BATCHING\n\tmvPosition = batchingMatrix * mvPosition;\n#endif\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;",dithering_fragment:"#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif",dithering_pars_fragment:"#ifdef DITHERING\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif",roughnessmap_fragment:"float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );\n\troughnessFactor *= texelRoughness.g;\n#endif",roughnessmap_pars_fragment:"#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif",shadowmap_pars_fragment:"#if NUM_SPOT_LIGHT_COORDS > 0\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#if NUM_SPOT_LIGHT_MAPS > 0\n\tuniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tfloat shadow = 1.0;\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\t\n\t\tfloat lightToPositionLength = length( lightToPosition );\n\t\tif ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) {\n\t\t\tfloat dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\t\tdp += shadowBias;\n\t\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\t\tshadow = (\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t\t) * ( 1.0 / 9.0 );\n\t\t\t#else\n\t\t\t\tshadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t\t#endif\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n#endif",shadowmap_pars_vertex:"#if NUM_SPOT_LIGHT_COORDS > 0\n\tuniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif",shadowmap_vertex:"#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )\n\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\tvec4 shadowWorldPosition;\n#endif\n#if defined( USE_SHADOWMAP )\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if NUM_SPOT_LIGHT_COORDS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition;\n\t\t#if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t\tshadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;\n\t\t#endif\n\t\tvSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n#endif",shadowmask_pars_fragment:"float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}",skinbase_vertex:"#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif",skinning_pars_vertex:"#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\tuniform highp sampler2D boneTexture;\n\tmat4 getBoneMatrix( const in float i ) {\n\t\tint size = textureSize( boneTexture, 0 ).x;\n\t\tint j = int( i ) * 4;\n\t\tint x = j % size;\n\t\tint y = j / size;\n\t\tvec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 );\n\t\tvec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 );\n\t\tvec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 );\n\t\tvec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 );\n\t\treturn mat4( v1, v2, v3, v4 );\n\t}\n#endif",skinning_vertex:"#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif",skinnormal_vertex:"#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\t#ifdef USE_TANGENT\n\t\tobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#endif\n#endif",specularmap_fragment:"float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif",specularmap_pars_fragment:"#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif",tonemapping_fragment:"#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif",tonemapping_pars_fragment:"#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn saturate( toneMappingExposure * color );\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 CineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ),\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3( 1.60475, -0.10208, -0.00327 ),\t\tvec3( -0.53108, 1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605, 1.07602 )\n\t);\n\tcolor *= toneMappingExposure / 0.6;\n\tcolor = ACESInputMat * color;\n\tcolor = RRTAndODTFit( color );\n\tcolor = ACESOutputMat * color;\n\treturn saturate( color );\n}\nconst mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(\n\tvec3( 1.6605, - 0.1246, - 0.0182 ),\n\tvec3( - 0.5876, 1.1329, - 0.1006 ),\n\tvec3( - 0.0728, - 0.0083, 1.1187 )\n);\nconst mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(\n\tvec3( 0.6274, 0.0691, 0.0164 ),\n\tvec3( 0.3293, 0.9195, 0.0880 ),\n\tvec3( 0.0433, 0.0113, 0.8956 )\n);\nvec3 agxDefaultContrastApprox( vec3 x ) {\n\tvec3 x2 = x * x;\n\tvec3 x4 = x2 * x2;\n\treturn + 15.5 * x4 * x2\n\t\t- 40.14 * x4 * x\n\t\t+ 31.96 * x4\n\t\t- 6.868 * x2 * x\n\t\t+ 0.4298 * x2\n\t\t+ 0.1191 * x\n\t\t- 0.00232;\n}\nvec3 AgXToneMapping( vec3 color ) {\n\tconst mat3 AgXInsetMatrix = mat3(\n\t\tvec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),\n\t\tvec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),\n\t\tvec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )\n\t);\n\tconst mat3 AgXOutsetMatrix = mat3(\n\t\tvec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),\n\t\tvec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),\n\t\tvec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )\n\t);\n\tconst float AgxMinEv = - 12.47393;\tconst float AgxMaxEv = 4.026069;\n\tcolor *= toneMappingExposure;\n\tcolor = LINEAR_SRGB_TO_LINEAR_REC2020 * color;\n\tcolor = AgXInsetMatrix * color;\n\tcolor = max( color, 1e-10 );\tcolor = log2( color );\n\tcolor = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );\n\tcolor = clamp( color, 0.0, 1.0 );\n\tcolor = agxDefaultContrastApprox( color );\n\tcolor = AgXOutsetMatrix * color;\n\tcolor = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );\n\tcolor = LINEAR_REC2020_TO_LINEAR_SRGB * color;\n\tcolor = clamp( color, 0.0, 1.0 );\n\treturn color;\n}\nvec3 NeutralToneMapping( vec3 color ) {\n\tconst float StartCompression = 0.8 - 0.04;\n\tconst float Desaturation = 0.15;\n\tcolor *= toneMappingExposure;\n\tfloat x = min( color.r, min( color.g, color.b ) );\n\tfloat offset = x < 0.08 ? x - 6.25 * x * x : 0.04;\n\tcolor -= offset;\n\tfloat peak = max( color.r, max( color.g, color.b ) );\n\tif ( peak < StartCompression ) return color;\n\tfloat d = 1. - StartCompression;\n\tfloat newPeak = 1. - d * d / ( peak + d - StartCompression );\n\tcolor *= newPeak / peak;\n\tfloat g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );\n\treturn mix( color, vec3( newPeak ), g );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }",transmission_fragment:"#ifdef USE_TRANSMISSION\n\tmaterial.transmission = transmission;\n\tmaterial.transmissionAlpha = 1.0;\n\tmaterial.thickness = thickness;\n\tmaterial.attenuationDistance = attenuationDistance;\n\tmaterial.attenuationColor = attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tmaterial.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tmaterial.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = inverseTransformDirection( normal, viewMatrix );\n\tvec4 transmitted = getIBLVolumeRefraction(\n\t\tn, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness,\n\t\tmaterial.attenuationColor, material.attenuationDistance );\n\tmaterial.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );\n\ttotalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );\n#endif",transmission_pars_fragment:"#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tfloat w0( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );\n\t}\n\tfloat w1( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 );\n\t}\n\tfloat w2( float a ){\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );\n\t}\n\tfloat w3( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * a );\n\t}\n\tfloat g0( float a ) {\n\t\treturn w0( a ) + w1( a );\n\t}\n\tfloat g1( float a ) {\n\t\treturn w2( a ) + w3( a );\n\t}\n\tfloat h0( float a ) {\n\t\treturn - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );\n\t}\n\tfloat h1( float a ) {\n\t\treturn 1.0 + w3( a ) / ( w2( a ) + w3( a ) );\n\t}\n\tvec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) {\n\t\tuv = uv * texelSize.zw + 0.5;\n\t\tvec2 iuv = floor( uv );\n\t\tvec2 fuv = fract( uv );\n\t\tfloat g0x = g0( fuv.x );\n\t\tfloat g1x = g1( fuv.x );\n\t\tfloat h0x = h0( fuv.x );\n\t\tfloat h1x = h1( fuv.x );\n\t\tfloat h0y = h0( fuv.y );\n\t\tfloat h1y = h1( fuv.y );\n\t\tvec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\treturn g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) +\n\t\t\tg1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) );\n\t}\n\tvec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) {\n\t\tvec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) );\n\t\tvec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) );\n\t\tvec2 fLodSizeInv = 1.0 / fLodSize;\n\t\tvec2 cLodSizeInv = 1.0 / cLodSize;\n\t\tvec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) );\n\t\tvec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) );\n\t\treturn mix( fSample, cSample, fract( lod ) );\n\t}\n\tvec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( const in float roughness, const in float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {\n\t\tfloat lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\treturn textureBicubic( transmissionSamplerMap, fragCoord.xy, lod );\n\t}\n\tvec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tif ( isinf( attenuationDistance ) ) {\n\t\t\treturn vec3( 1.0 );\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,\n\t\tconst in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,\n\t\tconst in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness,\n\t\tconst in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tvec4 transmittedLight;\n\t\tvec3 transmittance;\n\t\t#ifdef USE_DISPERSION\n\t\t\tfloat halfSpread = ( ior - 1.0 ) * 0.025 * dispersion;\n\t\t\tvec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread );\n\t\t\tfor ( int i = 0; i < 3; i ++ ) {\n\t\t\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix );\n\t\t\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\t\n\t\t\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\t\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\t\t\trefractionCoords += 1.0;\n\t\t\t\trefractionCoords /= 2.0;\n\t\t\n\t\t\t\tvec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] );\n\t\t\t\ttransmittedLight[ i ] = transmissionSample[ i ];\n\t\t\t\ttransmittedLight.a += transmissionSample.a;\n\t\t\t\ttransmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ];\n\t\t\t}\n\t\t\ttransmittedLight.a /= 3.0;\n\t\t\n\t\t#else\n\t\t\n\t\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\t\trefractionCoords += 1.0;\n\t\t\trefractionCoords /= 2.0;\n\t\t\ttransmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\t\ttransmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\t\n\t\t#endif\n\t\tvec3 attenuatedColor = transmittance * transmittedLight.rgb;\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\tfloat transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );\n\t}\n#endif",uv_pars_fragment:"#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_MAP\n\tvarying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n\tvarying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n\tvarying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n\tvarying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n\tvarying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n\tvarying vec2 vNormalMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tvarying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n\tvarying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tvarying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tvarying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tvarying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tvarying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tvarying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tvarying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tvarying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tvarying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tvarying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n\tvarying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tvarying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tvarying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tuniform mat3 transmissionMapTransform;\n\tvarying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n\tuniform mat3 thicknessMapTransform;\n\tvarying vec2 vThicknessMapUv;\n#endif",uv_pars_vertex:"#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_MAP\n\tuniform mat3 mapTransform;\n\tvarying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform mat3 alphaMapTransform;\n\tvarying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n\tuniform mat3 lightMapTransform;\n\tvarying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n\tuniform mat3 aoMapTransform;\n\tvarying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n\tuniform mat3 bumpMapTransform;\n\tvarying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n\tuniform mat3 normalMapTransform;\n\tvarying vec2 vNormalMapUv;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n\tuniform mat3 displacementMapTransform;\n\tvarying vec2 vDisplacementMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tuniform mat3 emissiveMapTransform;\n\tvarying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n\tuniform mat3 metalnessMapTransform;\n\tvarying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tuniform mat3 roughnessMapTransform;\n\tvarying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tuniform mat3 anisotropyMapTransform;\n\tvarying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tuniform mat3 clearcoatMapTransform;\n\tvarying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform mat3 clearcoatNormalMapTransform;\n\tvarying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform mat3 clearcoatRoughnessMapTransform;\n\tvarying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tuniform mat3 sheenColorMapTransform;\n\tvarying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tuniform mat3 sheenRoughnessMapTransform;\n\tvarying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tuniform mat3 iridescenceMapTransform;\n\tvarying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform mat3 iridescenceThicknessMapTransform;\n\tvarying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n\tuniform mat3 specularMapTransform;\n\tvarying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tuniform mat3 specularColorMapTransform;\n\tvarying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tuniform mat3 specularIntensityMapTransform;\n\tvarying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tuniform mat3 transmissionMapTransform;\n\tvarying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n\tuniform mat3 thicknessMapTransform;\n\tvarying vec2 vThicknessMapUv;\n#endif",uv_vertex:"#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvUv = vec3( uv, 1 ).xy;\n#endif\n#ifdef USE_MAP\n\tvMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ALPHAMAP\n\tvAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_LIGHTMAP\n\tvLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_AOMAP\n\tvAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_BUMPMAP\n\tvBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_NORMALMAP\n\tvNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n\tvDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tvEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_METALNESSMAP\n\tvMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tvRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tvAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tvClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tvClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tvClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tvIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tvIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tvSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tvSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULARMAP\n\tvSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tvSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tvSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tvTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_THICKNESSMAP\n\tvThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;\n#endif",worldpos_vertex:"#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_BATCHING\n\t\tworldPosition = batchingMatrix * worldPosition;\n\t#endif\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif",background_vert:"varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}",background_frag:"uniform sampler2D t2D;\nuniform float backgroundIntensity;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\ttexColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include \n\t#include \n}",backgroundCube_vert:"varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n\tgl_Position.z = gl_Position.w;\n}",backgroundCube_frag:"#ifdef ENVMAP_TYPE_CUBE\n\tuniform samplerCube envMap;\n#elif defined( ENVMAP_TYPE_CUBE_UV )\n\tuniform sampler2D envMap;\n#endif\nuniform float flipEnvMap;\nuniform float backgroundBlurriness;\nuniform float backgroundIntensity;\nuniform mat3 backgroundRotation;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness );\n\t#else\n\t\tvec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include \n\t#include \n}",cube_vert:"varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n\tgl_Position.z = gl_Position.w;\n}",cube_frag:"uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldDirection;\nvoid main() {\n\tvec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );\n\tgl_FragColor = texColor;\n\tgl_FragColor.a *= opacity;\n\t#include \n\t#include \n}",depth_vert:"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvHighPrecisionZW = gl_Position.zw;\n}",depth_frag:"#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include \n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#elif DEPTH_PACKING == 3202\n\t\tgl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 );\n\t#elif DEPTH_PACKING == 3203\n\t\tgl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 );\n\t#endif\n}",distanceRGBA_vert:"#define DISTANCE\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvWorldPosition = worldPosition.xyz;\n}",distanceRGBA_frag:"#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main () {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}",equirect_vert:"varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n}",equirect_frag:"uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\t#include \n\t#include \n}",linedashed_vert:"uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",linedashed_frag:"uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshbasic_vert:"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshbasic_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\t\treflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include \n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshlambert_vert:"#define LAMBERT\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}",meshlambert_frag:"#define LAMBERT\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshmatcap_vert:"#define MATCAP\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n}",meshmatcap_frag:"#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t#else\n\t\tvec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshnormal_vert:"#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvarying vec3 vViewPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}",meshnormal_frag:"#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvarying vec3 vViewPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\tgl_FragColor = vec4( packNormalToRGB( normal ), diffuseColor.a );\n\t#ifdef OPAQUE\n\t\tgl_FragColor.a = 1.0;\n\t#endif\n}",meshphong_vert:"#define PHONG\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}",meshphong_frag:"#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshphysical_vert:"#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition.xyz;\n#endif\n}",meshphysical_frag:"#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define USE_SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n\tuniform float ior;\n#endif\n#ifdef USE_SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularColor;\n\t#ifdef USE_SPECULAR_COLORMAP\n\t\tuniform sampler2D specularColorMap;\n\t#endif\n\t#ifdef USE_SPECULAR_INTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_DISPERSION\n\tuniform float dispersion;\n#endif\n#ifdef USE_IRIDESCENCE\n\tuniform float iridescence;\n\tuniform float iridescenceIOR;\n\tuniform float iridescenceThicknessMinimum;\n\tuniform float iridescenceThicknessMaximum;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheenColor;\n\tuniform float sheenRoughness;\n\t#ifdef USE_SHEEN_COLORMAP\n\t\tuniform sampler2D sheenColorMap;\n\t#endif\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tuniform sampler2D sheenRoughnessMap;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\tuniform vec2 anisotropyVector;\n\t#ifdef USE_ANISOTROPYMAP\n\t\tuniform sampler2D anisotropyMap;\n\t#endif\n#endif\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include \n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_SHEEN\n\t\tfloat sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );\n\t\toutgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect;\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshtoon_vert:"#define TOON\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n}",meshtoon_frag:"#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",points_vert:"uniform float size;\nuniform float scale;\n#include \n#include \n#include \n#include \n#include \n#include \n#ifdef USE_POINTS_UV\n\tvarying vec2 vUv;\n\tuniform mat3 uvTransform;\n#endif\nvoid main() {\n\t#ifdef USE_POINTS_UV\n\t\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n}",points_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",shadow_vert:"#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",shadow_frag:"uniform vec3 color;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include \n\t#include \n\t#include \n}",sprite_vert:"uniform float rotation;\nuniform vec2 center;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 mvPosition = modelViewMatrix[ 3 ];\n\tvec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include \n\t#include \n\t#include \n}",sprite_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n}"},dr={common:{diffuse:{value:new ii(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new se},alphaMap:{value:null},alphaMapTransform:{value:new se},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new se}},envmap:{envMap:{value:null},envMapRotation:{value:new se},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new se}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new se}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new se},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new se},normalScale:{value:new re(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new se},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new se}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new se}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new se}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new ii(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new ii(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new se},alphaTest:{value:0},uvTransform:{value:new se}},sprite:{diffuse:{value:new ii(16777215)},opacity:{value:1},center:{value:new re(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new se},alphaMap:{value:null},alphaMapTransform:{value:new se},alphaTest:{value:0}}},pr={basic:{uniforms:Hi([dr.common,dr.specularmap,dr.envmap,dr.aomap,dr.lightmap,dr.fog]),vertexShader:ur.meshbasic_vert,fragmentShader:ur.meshbasic_frag},lambert:{uniforms:Hi([dr.common,dr.specularmap,dr.envmap,dr.aomap,dr.lightmap,dr.emissivemap,dr.bumpmap,dr.normalmap,dr.displacementmap,dr.fog,dr.lights,{emissive:{value:new ii(0)}}]),vertexShader:ur.meshlambert_vert,fragmentShader:ur.meshlambert_frag},phong:{uniforms:Hi([dr.common,dr.specularmap,dr.envmap,dr.aomap,dr.lightmap,dr.emissivemap,dr.bumpmap,dr.normalmap,dr.displacementmap,dr.fog,dr.lights,{emissive:{value:new ii(0)},specular:{value:new ii(1118481)},shininess:{value:30}}]),vertexShader:ur.meshphong_vert,fragmentShader:ur.meshphong_frag},standard:{uniforms:Hi([dr.common,dr.envmap,dr.aomap,dr.lightmap,dr.emissivemap,dr.bumpmap,dr.normalmap,dr.displacementmap,dr.roughnessmap,dr.metalnessmap,dr.fog,dr.lights,{emissive:{value:new ii(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:ur.meshphysical_vert,fragmentShader:ur.meshphysical_frag},toon:{uniforms:Hi([dr.common,dr.aomap,dr.lightmap,dr.emissivemap,dr.bumpmap,dr.normalmap,dr.displacementmap,dr.gradientmap,dr.fog,dr.lights,{emissive:{value:new ii(0)}}]),vertexShader:ur.meshtoon_vert,fragmentShader:ur.meshtoon_frag},matcap:{uniforms:Hi([dr.common,dr.bumpmap,dr.normalmap,dr.displacementmap,dr.fog,{matcap:{value:null}}]),vertexShader:ur.meshmatcap_vert,fragmentShader:ur.meshmatcap_frag},points:{uniforms:Hi([dr.points,dr.fog]),vertexShader:ur.points_vert,fragmentShader:ur.points_frag},dashed:{uniforms:Hi([dr.common,dr.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:ur.linedashed_vert,fragmentShader:ur.linedashed_frag},depth:{uniforms:Hi([dr.common,dr.displacementmap]),vertexShader:ur.depth_vert,fragmentShader:ur.depth_frag},normal:{uniforms:Hi([dr.common,dr.bumpmap,dr.normalmap,dr.displacementmap,{opacity:{value:1}}]),vertexShader:ur.meshnormal_vert,fragmentShader:ur.meshnormal_frag},sprite:{uniforms:Hi([dr.sprite,dr.fog]),vertexShader:ur.sprite_vert,fragmentShader:ur.sprite_frag},background:{uniforms:{uvTransform:{value:new se},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:ur.background_vert,fragmentShader:ur.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new se}},vertexShader:ur.backgroundCube_vert,fragmentShader:ur.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:ur.cube_vert,fragmentShader:ur.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:ur.equirect_vert,fragmentShader:ur.equirect_frag},distanceRGBA:{uniforms:Hi([dr.common,dr.displacementmap,{referencePosition:{value:new De},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:ur.distanceRGBA_vert,fragmentShader:ur.distanceRGBA_frag},shadow:{uniforms:Hi([dr.lights,dr.fog,{color:{value:new ii(0)},opacity:{value:1}}]),vertexShader:ur.shadow_vert,fragmentShader:ur.shadow_frag}};pr.physical={uniforms:Hi([pr.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new se},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new se},clearcoatNormalScale:{value:new re(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new se},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new se},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new se},sheen:{value:0},sheenColor:{value:new ii(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new se},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new se},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new se},transmissionSamplerSize:{value:new re},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new se},attenuationDistance:{value:0},attenuationColor:{value:new ii(0)},specularColor:{value:new ii(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new se},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new se},anisotropyVector:{value:new re},anisotropyMap:{value:null},anisotropyMapTransform:{value:new se}}]),vertexShader:ur.meshphysical_vert,fragmentShader:ur.meshphysical_frag};const mr={r:0,b:0,g:0},fr=new Mn,gr=new un;function vr(t,e,n,i,r,s,a){const o=new ii(0);let l,c,h=!0===s?0:1,u=null,d=0,m=null;function f(t){let i=!0===t.isScene?t.background:null;return i&&i.isTexture&&(i=(t.backgroundBlurriness>0?n:e).get(i)),i}function g(e,n){e.getRGB(mr,Gi(t)),i.buffers.color.setClear(mr.r,mr.g,mr.b,n,a)}return{getClearColor:function(){return o},setClearColor:function(t,e=1){o.set(t),h=e,g(o,h)},getClearAlpha:function(){return h},setClearAlpha:function(t){h=t,g(o,h)},render:function(e){let n=!1;const r=f(e);null===r?g(o,h):r&&r.isColor&&(g(r,1),n=!0);const s=t.xr.getEnvironmentBlendMode();"additive"===s?i.buffers.color.setClear(0,0,0,1,a):"alpha-blend"===s&&i.buffers.color.setClear(0,0,0,0,a),(t.autoClear||n)&&(i.buffers.depth.setTest(!0),i.buffers.depth.setMask(!0),i.buffers.color.setMask(!0),t.clear(t.autoClearColor,t.autoClearDepth,t.autoClearStencil))},addToRenderList:function(e,n){const i=f(n);i&&(i.isCubeTexture||i.mapping===p)?(void 0===c&&(c=new Bi(new ki(1,1,1),new Xi({name:"BackgroundCubeMaterial",uniforms:Vi(pr.backgroundCube.uniforms),vertexShader:pr.backgroundCube.vertexShader,fragmentShader:pr.backgroundCube.fragmentShader,side:1,depthTest:!1,depthWrite:!1,fog:!1})),c.geometry.deleteAttribute("normal"),c.geometry.deleteAttribute("uv"),c.onBeforeRender=function(t,e,n){this.matrixWorld.copyPosition(n.matrixWorld)},Object.defineProperty(c.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),r.update(c)),fr.copy(n.backgroundRotation),fr.x*=-1,fr.y*=-1,fr.z*=-1,i.isCubeTexture&&!1===i.isRenderTargetTexture&&(fr.y*=-1,fr.z*=-1),c.material.uniforms.envMap.value=i,c.material.uniforms.flipEnvMap.value=i.isCubeTexture&&!1===i.isRenderTargetTexture?-1:1,c.material.uniforms.backgroundBlurriness.value=n.backgroundBlurriness,c.material.uniforms.backgroundIntensity.value=n.backgroundIntensity,c.material.uniforms.backgroundRotation.value.setFromMatrix4(gr.makeRotationFromEuler(fr)),c.material.toneMapped=_e.getTransfer(i.colorSpace)!==Bt,u===i&&d===i.version&&m===t.toneMapping||(c.material.needsUpdate=!0,u=i,d=i.version,m=t.toneMapping),c.layers.enableAll(),e.unshift(c,c.geometry,c.material,0,0,null)):i&&i.isTexture&&(void 0===l&&(l=new Bi(new hr(2,2),new Xi({name:"BackgroundMaterial",uniforms:Vi(pr.background.uniforms),vertexShader:pr.background.vertexShader,fragmentShader:pr.background.fragmentShader,side:0,depthTest:!1,depthWrite:!1,fog:!1})),l.geometry.deleteAttribute("normal"),Object.defineProperty(l.material,"map",{get:function(){return this.uniforms.t2D.value}}),r.update(l)),l.material.uniforms.t2D.value=i,l.material.uniforms.backgroundIntensity.value=n.backgroundIntensity,l.material.toneMapped=_e.getTransfer(i.colorSpace)!==Bt,!0===i.matrixAutoUpdate&&i.updateMatrix(),l.material.uniforms.uvTransform.value.copy(i.matrix),u===i&&d===i.version&&m===t.toneMapping||(l.material.needsUpdate=!0,u=i,d=i.version,m=t.toneMapping),l.layers.enableAll(),e.unshift(l,l.geometry,l.material,0,0,null))}}}function _r(t,e){const n=t.getParameter(t.MAX_VERTEX_ATTRIBS),i={},r=c(null);let s=r,a=!1;function o(e){return t.bindVertexArray(e)}function l(e){return t.deleteVertexArray(e)}function c(t){const e=[],i=[],r=[];for(let t=0;t=0){const n=r[e];let i=a[e];if(void 0===i&&("instanceMatrix"===e&&t.instanceMatrix&&(i=t.instanceMatrix),"instanceColor"===e&&t.instanceColor&&(i=t.instanceColor)),void 0===n)return!0;if(n.attribute!==i)return!0;if(i&&n.data!==i.data)return!0;o++}return s.attributesNum!==o||s.index!==i}(n,f,l,g),v&&function(t,e,n,i){const r={},a=e.attributes;let o=0;const l=n.getAttributes();for(const e in l)if(l[e].location>=0){let n=a[e];void 0===n&&("instanceMatrix"===e&&t.instanceMatrix&&(n=t.instanceMatrix),"instanceColor"===e&&t.instanceColor&&(n=t.instanceColor));const i={};i.attribute=n,n&&n.data&&(i.data=n.data),r[e]=i,o++}s.attributes=r,s.attributesNum=o,s.index=i}(n,f,l,g),null!==g&&e.update(g,t.ELEMENT_ARRAY_BUFFER),(v||a)&&(a=!1,function(n,i,r,s){h();const a=s.attributes,o=r.getAttributes(),l=i.defaultAttributeValues;for(const i in o){const r=o[i];if(r.location>=0){let o=a[i];if(void 0===o&&("instanceMatrix"===i&&n.instanceMatrix&&(o=n.instanceMatrix),"instanceColor"===i&&n.instanceColor&&(o=n.instanceColor)),void 0!==o){const i=o.normalized,a=o.itemSize,l=e.get(o);if(void 0===l)continue;const c=l.buffer,h=l.type,p=l.bytesPerElement,f=h===t.INT||h===t.UNSIGNED_INT||o.gpuType===A;if(o.isInterleavedBufferAttribute){const e=o.data,l=e.stride,g=o.offset;if(e.isInstancedInterleavedBuffer){for(let t=0;t0&&t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.HIGH_FLOAT).precision>0)return"highp";e="mediump"}return"mediump"===e&&t.getShaderPrecisionFormat(t.VERTEX_SHADER,t.MEDIUM_FLOAT).precision>0&&t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let a=void 0!==n.precision?n.precision:"highp";const o=s(a);o!==a&&(console.warn("THREE.WebGLRenderer:",a,"not supported, using",o,"instead."),a=o);const l=!0===n.logarithmicDepthBuffer,c=!0===n.reverseDepthBuffer&&e.has("EXT_clip_control");if(!0===c){const t=e.get("EXT_clip_control");t.clipControlEXT(t.LOWER_LEFT_EXT,t.ZERO_TO_ONE_EXT)}const h=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS),u=t.getParameter(t.MAX_VERTEX_TEXTURE_IMAGE_UNITS);return{isWebGL2:!0,getMaxAnisotropy:function(){if(void 0!==r)return r;if(!0===e.has("EXT_texture_filter_anisotropic")){const n=e.get("EXT_texture_filter_anisotropic");r=t.getParameter(n.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else r=0;return r},getMaxPrecision:s,textureFormatReadable:function(e){return e===F||i.convert(e)===t.getParameter(t.IMPLEMENTATION_COLOR_READ_FORMAT)},textureTypeReadable:function(n){const r=n===P&&(e.has("EXT_color_buffer_half_float")||e.has("EXT_color_buffer_float"));return!(n!==b&&i.convert(n)!==t.getParameter(t.IMPLEMENTATION_COLOR_READ_TYPE)&&n!==C&&!r)},precision:a,logarithmicDepthBuffer:l,reverseDepthBuffer:c,maxTextures:h,maxVertexTextures:u,maxTextureSize:t.getParameter(t.MAX_TEXTURE_SIZE),maxCubemapSize:t.getParameter(t.MAX_CUBE_MAP_TEXTURE_SIZE),maxAttributes:t.getParameter(t.MAX_VERTEX_ATTRIBS),maxVertexUniforms:t.getParameter(t.MAX_VERTEX_UNIFORM_VECTORS),maxVaryings:t.getParameter(t.MAX_VARYING_VECTORS),maxFragmentUniforms:t.getParameter(t.MAX_FRAGMENT_UNIFORM_VECTORS),vertexTextures:u>0,maxSamples:t.getParameter(t.MAX_SAMPLES)}}function Mr(t){const e=this;let n=null,i=0,r=!1,s=!1;const a=new rr,o=new se,l={value:null,needsUpdate:!1};function c(t,n,i,r){const s=null!==t?t.length:0;let c=null;if(0!==s){if(c=l.value,!0!==r||null===c){const e=i+4*s,r=n.matrixWorldInverse;o.getNormalMatrix(r),(null===c||c.length0),e.numPlanes=i,e.numIntersection=0);else{const t=s?0:i,e=4*t;let r=m.clippingState||null;l.value=r,r=c(u,o,e,h);for(let t=0;t!==e;++t)r[t]=n[t];m.clippingState=r,this.numIntersection=d?this.numPlanes:0,this.numPlanes+=t}}}function Sr(t){let e=new WeakMap;function n(t,e){return e===u?t.mapping=c:e===d&&(t.mapping=h),t}function i(t){const n=t.target;n.removeEventListener("dispose",i);const r=e.get(n);void 0!==r&&(e.delete(n),r.dispose())}return{get:function(r){if(r&&r.isTexture){const s=r.mapping;if(s===u||s===d){if(e.has(r))return n(e.get(r).texture,r.mapping);{const s=r.image;if(s&&s.height>0){const a=new tr(s.height);return a.fromEquirectangularTexture(t,r),e.set(r,a),r.addEventListener("dispose",i),n(a.texture,r.mapping)}return null}}}return r},dispose:function(){e=new WeakMap}}}class br extends ji{constructor(t=-1,e=1,n=1,i=-1,r=.1,s=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=t,this.right=e,this.top=n,this.bottom=i,this.near=r,this.far=s,this.updateProjectionMatrix()}copy(t,e){return super.copy(t,e),this.left=t.left,this.right=t.right,this.top=t.top,this.bottom=t.bottom,this.near=t.near,this.far=t.far,this.zoom=t.zoom,this.view=null===t.view?null:Object.assign({},t.view),this}setViewOffset(t,e,n,i,r,s){null===this.view&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=t,this.view.fullHeight=e,this.view.offsetX=n,this.view.offsetY=i,this.view.width=r,this.view.height=s,this.updateProjectionMatrix()}clearViewOffset(){null!==this.view&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const t=(this.right-this.left)/(2*this.zoom),e=(this.top-this.bottom)/(2*this.zoom),n=(this.right+this.left)/2,i=(this.top+this.bottom)/2;let r=n-t,s=n+t,a=i+e,o=i-e;if(null!==this.view&&this.view.enabled){const t=(this.right-this.left)/this.view.fullWidth/this.zoom,e=(this.top-this.bottom)/this.view.fullHeight/this.zoom;r+=t*this.view.offsetX,s=r+t*this.view.width,a-=e*this.view.offsetY,o=a-e*this.view.height}this.projectionMatrix.makeOrthographic(r,s,a,o,this.near,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(t){const e=super.toJSON(t);return e.object.zoom=this.zoom,e.object.left=this.left,e.object.right=this.right,e.object.top=this.top,e.object.bottom=this.bottom,e.object.near=this.near,e.object.far=this.far,null!==this.view&&(e.object.view=Object.assign({},this.view)),e}}const wr=[.125,.215,.35,.446,.526,.582],Tr=new br,Er=new ii;let Ar=null,Rr=0,Cr=0,Pr=!1;const Ir=(1+Math.sqrt(5))/2,Lr=1/Ir,Ur=[new De(-Ir,Lr,0),new De(Ir,Lr,0),new De(-Lr,0,Ir),new De(Lr,0,Ir),new De(0,Ir,-Lr),new De(0,Ir,Lr),new De(-1,1,-1),new De(1,1,-1),new De(-1,1,1),new De(1,1,1)];class Dr{constructor(t){this._renderer=t,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._compileMaterial(this._blurMaterial)}fromScene(t,e=0,n=.1,i=100){Ar=this._renderer.getRenderTarget(),Rr=this._renderer.getActiveCubeFace(),Cr=this._renderer.getActiveMipmapLevel(),Pr=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(256);const r=this._allocateTargets();return r.depthBuffer=!0,this._sceneToCubeUV(t,n,i,r),e>0&&this._blur(r,0,0,e),this._applyPMREM(r),this._cleanup(r),r}fromEquirectangular(t,e=null){return this._fromTexture(t,e)}fromCubemap(t,e=null){return this._fromTexture(t,e)}compileCubemapShader(){null===this._cubemapMaterial&&(this._cubemapMaterial=Br(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=Fr(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),null!==this._cubemapMaterial&&this._cubemapMaterial.dispose(),null!==this._equirectMaterial&&this._equirectMaterial.dispose()}_setSize(t){this._lodMax=Math.floor(Math.log2(t)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){null!==this._blurMaterial&&this._blurMaterial.dispose(),null!==this._pingPongRenderTarget&&this._pingPongRenderTarget.dispose();for(let t=0;tt-4?o=wr[a-t+4-1]:0===a&&(o=0),i.push(o);const l=1/(s-2),c=-l,h=1+l,u=[c,c,h,c,h,h,c,c,h,h,c,h],d=6,p=6,m=3,f=2,g=1,v=new Float32Array(m*p*d),_=new Float32Array(f*p*d),x=new Float32Array(g*p*d);for(let t=0;t2?0:-1,i=[e,n,0,e+2/3,n,0,e+2/3,n+1,0,e,n,0,e+2/3,n+1,0,e,n+1,0];v.set(i,m*p*t),_.set(u,f*p*t);const r=[t,t,t,t,t,t];x.set(r,g*p*t)}const y=new Ei;y.setAttribute("position",new fi(v,m)),y.setAttribute("uv",new fi(_,f)),y.setAttribute("faceIndex",new fi(x,g)),e.push(y),r>4&&r--}return{lodPlanes:e,sizeLods:n,sigmas:i}}(i)),this._blurMaterial=function(t,e,n){const i=new Float32Array(20),r=new De(0,1,0);return new Xi({name:"SphericalGaussianBlur",defines:{n:20,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/n,CUBEUV_MAX_MIP:`${t}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:i},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:r}},vertexShader:"\n\n\t\tprecision mediump float;\n\t\tprecision mediump int;\n\n\t\tattribute float faceIndex;\n\n\t\tvarying vec3 vOutputDirection;\n\n\t\t// RH coordinate system; PMREM face-indexing convention\n\t\tvec3 getDirection( vec2 uv, float face ) {\n\n\t\t\tuv = 2.0 * uv - 1.0;\n\n\t\t\tvec3 direction = vec3( uv, 1.0 );\n\n\t\t\tif ( face == 0.0 ) {\n\n\t\t\t\tdirection = direction.zyx; // ( 1, v, u ) pos x\n\n\t\t\t} else if ( face == 1.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xz *= -1.0; // ( -u, 1, -v ) pos y\n\n\t\t\t} else if ( face == 2.0 ) {\n\n\t\t\t\tdirection.x *= -1.0; // ( -u, v, 1 ) pos z\n\n\t\t\t} else if ( face == 3.0 ) {\n\n\t\t\t\tdirection = direction.zyx;\n\t\t\t\tdirection.xz *= -1.0; // ( -1, v, -u ) neg x\n\n\t\t\t} else if ( face == 4.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xy *= -1.0; // ( -u, -1, v ) neg y\n\n\t\t\t} else if ( face == 5.0 ) {\n\n\t\t\t\tdirection.z *= -1.0; // ( u, v, -1 ) neg z\n\n\t\t\t}\n\n\t\t\treturn direction;\n\n\t\t}\n\n\t\tvoid main() {\n\n\t\t\tvOutputDirection = getDirection( uv, faceIndex );\n\t\t\tgl_Position = vec4( position, 1.0 );\n\n\t\t}\n\t",fragmentShader:"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\t\t\tuniform int samples;\n\t\t\tuniform float weights[ n ];\n\t\t\tuniform bool latitudinal;\n\t\t\tuniform float dTheta;\n\t\t\tuniform float mipInt;\n\t\t\tuniform vec3 poleAxis;\n\n\t\t\t#define ENVMAP_TYPE_CUBE_UV\n\t\t\t#include \n\n\t\t\tvec3 getSample( float theta, vec3 axis ) {\n\n\t\t\t\tfloat cosTheta = cos( theta );\n\t\t\t\t// Rodrigues' axis-angle rotation\n\t\t\t\tvec3 sampleDirection = vOutputDirection * cosTheta\n\t\t\t\t\t+ cross( axis, vOutputDirection ) * sin( theta )\n\t\t\t\t\t+ axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );\n\n\t\t\t\treturn bilinearCubeUV( envMap, sampleDirection, mipInt );\n\n\t\t\t}\n\n\t\t\tvoid main() {\n\n\t\t\t\tvec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );\n\n\t\t\t\tif ( all( equal( axis, vec3( 0.0 ) ) ) ) {\n\n\t\t\t\t\taxis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );\n\n\t\t\t\t}\n\n\t\t\t\taxis = normalize( axis );\n\n\t\t\t\tgl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t\t\t\tgl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );\n\n\t\t\t\tfor ( int i = 1; i < n; i++ ) {\n\n\t\t\t\t\tif ( i >= samples ) {\n\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tfloat theta = dTheta * float( i );\n\t\t\t\t\tgl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );\n\t\t\t\t\tgl_FragColor.rgb += weights[ i ] * getSample( theta, axis );\n\n\t\t\t\t}\n\n\t\t\t}\n\t\t",blending:0,depthTest:!1,depthWrite:!1})}(i,t,e)}return i}_compileMaterial(t){const e=new Bi(this._lodPlanes[0],t);this._renderer.compile(e,Tr)}_sceneToCubeUV(t,e,n,i){const r=new Ji(90,1,e,n),s=[1,-1,1,1,1,1],a=[1,1,1,-1,-1,-1],o=this._renderer,l=o.autoClear,c=o.toneMapping;o.getClearColor(Er),o.toneMapping=0,o.autoClear=!1;const h=new oi({name:"PMREM.Background",side:1,depthWrite:!1,depthTest:!1}),u=new Bi(new ki,h);let d=!1;const p=t.background;p?p.isColor&&(h.color.copy(p),t.background=null,d=!0):(h.color.copy(Er),d=!0);for(let e=0;e<6;e++){const n=e%3;0===n?(r.up.set(0,s[e],0),r.lookAt(a[e],0,0)):1===n?(r.up.set(0,0,s[e]),r.lookAt(0,a[e],0)):(r.up.set(0,s[e],0),r.lookAt(0,0,a[e]));const l=this._cubeSize;Or(i,n*l,e>2?l:0,l,l),o.setRenderTarget(i),d&&o.render(u,r),o.render(t,r)}u.geometry.dispose(),u.material.dispose(),o.toneMapping=c,o.autoClear=l,t.background=p}_textureToCubeUV(t,e){const n=this._renderer,i=t.mapping===c||t.mapping===h;i?(null===this._cubemapMaterial&&(this._cubemapMaterial=Br()),this._cubemapMaterial.uniforms.flipEnvMap.value=!1===t.isRenderTargetTexture?-1:1):null===this._equirectMaterial&&(this._equirectMaterial=Fr());const r=i?this._cubemapMaterial:this._equirectMaterial,s=new Bi(this._lodPlanes[0],r);r.uniforms.envMap.value=t;const a=this._cubeSize;Or(e,0,0,3*a,2*a),n.setRenderTarget(e),n.render(s,Tr)}_applyPMREM(t){const e=this._renderer,n=e.autoClear;e.autoClear=!1;const i=this._lodPlanes.length;for(let e=1;e20&&console.warn(`sigmaRadians, ${r}, is too large and will clip, as it requested ${m} samples when the maximum is set to 20`);const f=[];let g=0;for(let t=0;t<20;++t){const e=t/p,n=Math.exp(-e*e/2);f.push(n),0===t?g+=n:tv-4?i-v+4:0),4*(this._cubeSize-_),3*_,2*_),o.setRenderTarget(e),o.render(c,Tr)}}function Nr(t,e,n){const i=new Pe(t,e,n);return i.texture.mapping=p,i.texture.name="PMREM.cubeUv",i.scissorTest=!0,i}function Or(t,e,n,i,r){t.viewport.set(e,n,i,r),t.scissor.set(e,n,i,r)}function Fr(){return new Xi({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:"\n\n\t\tprecision mediump float;\n\t\tprecision mediump int;\n\n\t\tattribute float faceIndex;\n\n\t\tvarying vec3 vOutputDirection;\n\n\t\t// RH coordinate system; PMREM face-indexing convention\n\t\tvec3 getDirection( vec2 uv, float face ) {\n\n\t\t\tuv = 2.0 * uv - 1.0;\n\n\t\t\tvec3 direction = vec3( uv, 1.0 );\n\n\t\t\tif ( face == 0.0 ) {\n\n\t\t\t\tdirection = direction.zyx; // ( 1, v, u ) pos x\n\n\t\t\t} else if ( face == 1.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xz *= -1.0; // ( -u, 1, -v ) pos y\n\n\t\t\t} else if ( face == 2.0 ) {\n\n\t\t\t\tdirection.x *= -1.0; // ( -u, v, 1 ) pos z\n\n\t\t\t} else if ( face == 3.0 ) {\n\n\t\t\t\tdirection = direction.zyx;\n\t\t\t\tdirection.xz *= -1.0; // ( -1, v, -u ) neg x\n\n\t\t\t} else if ( face == 4.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xy *= -1.0; // ( -u, -1, v ) neg y\n\n\t\t\t} else if ( face == 5.0 ) {\n\n\t\t\t\tdirection.z *= -1.0; // ( u, v, -1 ) neg z\n\n\t\t\t}\n\n\t\t\treturn direction;\n\n\t\t}\n\n\t\tvoid main() {\n\n\t\t\tvOutputDirection = getDirection( uv, faceIndex );\n\t\t\tgl_Position = vec4( position, 1.0 );\n\n\t\t}\n\t",fragmentShader:"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\n\t\t\t#include \n\n\t\t\tvoid main() {\n\n\t\t\t\tvec3 outputDirection = normalize( vOutputDirection );\n\t\t\t\tvec2 uv = equirectUv( outputDirection );\n\n\t\t\t\tgl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );\n\n\t\t\t}\n\t\t",blending:0,depthTest:!1,depthWrite:!1})}function Br(){return new Xi({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:"\n\n\t\tprecision mediump float;\n\t\tprecision mediump int;\n\n\t\tattribute float faceIndex;\n\n\t\tvarying vec3 vOutputDirection;\n\n\t\t// RH coordinate system; PMREM face-indexing convention\n\t\tvec3 getDirection( vec2 uv, float face ) {\n\n\t\t\tuv = 2.0 * uv - 1.0;\n\n\t\t\tvec3 direction = vec3( uv, 1.0 );\n\n\t\t\tif ( face == 0.0 ) {\n\n\t\t\t\tdirection = direction.zyx; // ( 1, v, u ) pos x\n\n\t\t\t} else if ( face == 1.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xz *= -1.0; // ( -u, 1, -v ) pos y\n\n\t\t\t} else if ( face == 2.0 ) {\n\n\t\t\t\tdirection.x *= -1.0; // ( -u, v, 1 ) pos z\n\n\t\t\t} else if ( face == 3.0 ) {\n\n\t\t\t\tdirection = direction.zyx;\n\t\t\t\tdirection.xz *= -1.0; // ( -1, v, -u ) neg x\n\n\t\t\t} else if ( face == 4.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xy *= -1.0; // ( -u, -1, v ) neg y\n\n\t\t\t} else if ( face == 5.0 ) {\n\n\t\t\t\tdirection.z *= -1.0; // ( u, v, -1 ) neg z\n\n\t\t\t}\n\n\t\t\treturn direction;\n\n\t\t}\n\n\t\tvoid main() {\n\n\t\t\tvOutputDirection = getDirection( uv, faceIndex );\n\t\t\tgl_Position = vec4( position, 1.0 );\n\n\t\t}\n\t",fragmentShader:"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tuniform float flipEnvMap;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform samplerCube envMap;\n\n\t\t\tvoid main() {\n\n\t\t\t\tgl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );\n\n\t\t\t}\n\t\t",blending:0,depthTest:!1,depthWrite:!1})}function zr(t){let e=new WeakMap,n=null;function i(t){const n=t.target;n.removeEventListener("dispose",i);const r=e.get(n);void 0!==r&&(e.delete(n),r.dispose())}return{get:function(r){if(r&&r.isTexture){const s=r.mapping,a=s===u||s===d,o=s===c||s===h;if(a||o){let s=e.get(r);const l=void 0!==s?s.texture.pmremVersion:0;if(r.isRenderTargetTexture&&r.pmremVersion!==l)return null===n&&(n=new Dr(t)),s=a?n.fromEquirectangular(r,s):n.fromCubemap(r,s),s.texture.pmremVersion=r.pmremVersion,e.set(r,s),s.texture;if(void 0!==s)return s.texture;{const l=r.image;return a&&l&&l.height>0||o&&l&&function(t){let e=0;for(let n=0;n<6;n++)void 0!==t[n]&&e++;return 6===e}(l)?(null===n&&(n=new Dr(t)),s=a?n.fromEquirectangular(r):n.fromCubemap(r),s.texture.pmremVersion=r.pmremVersion,e.set(r,s),r.addEventListener("dispose",i),s.texture):null}}}return r},dispose:function(){e=new WeakMap,null!==n&&(n.dispose(),n=null)}}}function kr(t){const e={};function n(n){if(void 0!==e[n])return e[n];let i;switch(n){case"WEBGL_depth_texture":i=t.getExtension("WEBGL_depth_texture")||t.getExtension("MOZ_WEBGL_depth_texture")||t.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":i=t.getExtension("EXT_texture_filter_anisotropic")||t.getExtension("MOZ_EXT_texture_filter_anisotropic")||t.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":i=t.getExtension("WEBGL_compressed_texture_s3tc")||t.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||t.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":i=t.getExtension("WEBGL_compressed_texture_pvrtc")||t.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:i=t.getExtension(n)}return e[n]=i,i}return{has:function(t){return null!==n(t)},init:function(){n("EXT_color_buffer_float"),n("WEBGL_clip_cull_distance"),n("OES_texture_float_linear"),n("EXT_color_buffer_half_float"),n("WEBGL_multisampled_render_to_texture"),n("WEBGL_render_shared_exponent")},get:function(t){const e=n(t);return null===e&&pe("THREE.WebGLRenderer: "+t+" extension not supported."),e}}}function Vr(t,e,n,i){const r={},s=new WeakMap;function a(t){const o=t.target;null!==o.index&&e.remove(o.index);for(const t in o.attributes)e.remove(o.attributes[t]);for(const t in o.morphAttributes){const n=o.morphAttributes[t];for(let t=0,i=n.length;te.maxTextureSize&&(y=Math.ceil(x/e.maxTextureSize),x=e.maxTextureSize);const M=new Float32Array(x*y*4*h),S=new Ie(M,x,y,h);S.type=C,S.needsUpdate=!0;const b=4*_;for(let T=0;T0)return t;const r=e*n;let s=$r[r];if(void 0===s&&(s=new Float32Array(r),$r[r]=s),0!==e){i.toArray(s,0);for(let i=1,r=0;i!==e;++i)r+=n,t[i].toArray(s,r)}return s}function rs(t,e){if(t.length!==e.length)return!1;for(let n=0,i=t.length;n":" "} ${r}: ${n[t]}`)}return i.join("\n")}(t.getShaderSource(e),i)}return r}function ea(t,e){const n=function(t){const e=_e.getPrimaries(_e.workingColorSpace),n=_e.getPrimaries(t);let i;switch(e===n?i="":e===kt&&n===zt?i="LinearDisplayP3ToLinearSRGB":e===zt&&n===kt&&(i="LinearSRGBToLinearDisplayP3"),t){case Dt:case Ot:return[i,"LinearTransferOETF"];case Ut:case Nt:return[i,"sRGBTransferOETF"];default:return console.warn("THREE.WebGLProgram: Unsupported color space:",t),[i,"LinearTransferOETF"]}}(e);return`vec4 ${t}( vec4 value ) { return ${n[0]}( ${n[1]}( value ) ); }`}function na(t,e){let n;switch(e){case 1:n="Linear";break;case 2:n="Reinhard";break;case 3:n="Cineon";break;case 4:n="ACESFilmic";break;case 6:n="AgX";break;case 7:n="Neutral";break;case 5:n="Custom";break;default:console.warn("THREE.WebGLProgram: Unsupported toneMapping:",e),n="Linear"}return"vec3 "+t+"( vec3 color ) { return "+n+"ToneMapping( color ); }"}const ia=new De;function ra(t){return""!==t}function sa(t,e){const n=e.numSpotLightShadows+e.numSpotLightMaps-e.numSpotLightShadowsWithMaps;return t.replace(/NUM_DIR_LIGHTS/g,e.numDirLights).replace(/NUM_SPOT_LIGHTS/g,e.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g,e.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g,n).replace(/NUM_RECT_AREA_LIGHTS/g,e.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g,e.numPointLights).replace(/NUM_HEMI_LIGHTS/g,e.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g,e.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g,e.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g,e.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g,e.numPointLightShadows)}function aa(t,e){return t.replace(/NUM_CLIPPING_PLANES/g,e.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,e.numClippingPlanes-e.numClipIntersection)}const oa=/^[ \t]*#include +<([\w\d./]+)>/gm;function la(t){return t.replace(oa,ha)}const ca=new Map;function ha(t,e){let n=ur[e];if(void 0===n){const t=ca.get(e);if(void 0===t)throw new Error("Can not resolve #include <"+e+">");n=ur[t],console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',e,t)}return la(n)}const ua=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function da(t){return t.replace(ua,pa)}function pa(t,e,n,i){let r="";for(let t=parseInt(e);t0&&(x+="\n"),y=["#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,v].filter(ra).join("\n"),y.length>0&&(y+="\n")):(x=[ma(n),"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,v,n.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",n.batching?"#define USE_BATCHING":"",n.batchingColor?"#define USE_BATCHING_COLOR":"",n.instancing?"#define USE_INSTANCING":"",n.instancingColor?"#define USE_INSTANCING_COLOR":"",n.instancingMorph?"#define USE_INSTANCING_MORPH":"",n.useFog&&n.fog?"#define USE_FOG":"",n.useFog&&n.fogExp2?"#define FOG_EXP2":"",n.map?"#define USE_MAP":"",n.envMap?"#define USE_ENVMAP":"",n.envMap?"#define "+d:"",n.lightMap?"#define USE_LIGHTMAP":"",n.aoMap?"#define USE_AOMAP":"",n.bumpMap?"#define USE_BUMPMAP":"",n.normalMap?"#define USE_NORMALMAP":"",n.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",n.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",n.displacementMap?"#define USE_DISPLACEMENTMAP":"",n.emissiveMap?"#define USE_EMISSIVEMAP":"",n.anisotropy?"#define USE_ANISOTROPY":"",n.anisotropyMap?"#define USE_ANISOTROPYMAP":"",n.clearcoatMap?"#define USE_CLEARCOATMAP":"",n.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",n.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",n.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",n.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",n.specularMap?"#define USE_SPECULARMAP":"",n.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",n.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",n.roughnessMap?"#define USE_ROUGHNESSMAP":"",n.metalnessMap?"#define USE_METALNESSMAP":"",n.alphaMap?"#define USE_ALPHAMAP":"",n.alphaHash?"#define USE_ALPHAHASH":"",n.transmission?"#define USE_TRANSMISSION":"",n.transmissionMap?"#define USE_TRANSMISSIONMAP":"",n.thicknessMap?"#define USE_THICKNESSMAP":"",n.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",n.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",n.mapUv?"#define MAP_UV "+n.mapUv:"",n.alphaMapUv?"#define ALPHAMAP_UV "+n.alphaMapUv:"",n.lightMapUv?"#define LIGHTMAP_UV "+n.lightMapUv:"",n.aoMapUv?"#define AOMAP_UV "+n.aoMapUv:"",n.emissiveMapUv?"#define EMISSIVEMAP_UV "+n.emissiveMapUv:"",n.bumpMapUv?"#define BUMPMAP_UV "+n.bumpMapUv:"",n.normalMapUv?"#define NORMALMAP_UV "+n.normalMapUv:"",n.displacementMapUv?"#define DISPLACEMENTMAP_UV "+n.displacementMapUv:"",n.metalnessMapUv?"#define METALNESSMAP_UV "+n.metalnessMapUv:"",n.roughnessMapUv?"#define ROUGHNESSMAP_UV "+n.roughnessMapUv:"",n.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+n.anisotropyMapUv:"",n.clearcoatMapUv?"#define CLEARCOATMAP_UV "+n.clearcoatMapUv:"",n.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+n.clearcoatNormalMapUv:"",n.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+n.clearcoatRoughnessMapUv:"",n.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+n.iridescenceMapUv:"",n.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+n.iridescenceThicknessMapUv:"",n.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+n.sheenColorMapUv:"",n.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+n.sheenRoughnessMapUv:"",n.specularMapUv?"#define SPECULARMAP_UV "+n.specularMapUv:"",n.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+n.specularColorMapUv:"",n.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+n.specularIntensityMapUv:"",n.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+n.transmissionMapUv:"",n.thicknessMapUv?"#define THICKNESSMAP_UV "+n.thicknessMapUv:"",n.vertexTangents&&!1===n.flatShading?"#define USE_TANGENT":"",n.vertexColors?"#define USE_COLOR":"",n.vertexAlphas?"#define USE_COLOR_ALPHA":"",n.vertexUv1s?"#define USE_UV1":"",n.vertexUv2s?"#define USE_UV2":"",n.vertexUv3s?"#define USE_UV3":"",n.pointsUvs?"#define USE_POINTS_UV":"",n.flatShading?"#define FLAT_SHADED":"",n.skinning?"#define USE_SKINNING":"",n.morphTargets?"#define USE_MORPHTARGETS":"",n.morphNormals&&!1===n.flatShading?"#define USE_MORPHNORMALS":"",n.morphColors?"#define USE_MORPHCOLORS":"",n.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+n.morphTextureStride:"",n.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+n.morphTargetsCount:"",n.doubleSided?"#define DOUBLE_SIDED":"",n.flipSided?"#define FLIP_SIDED":"",n.shadowMapEnabled?"#define USE_SHADOWMAP":"",n.shadowMapEnabled?"#define "+l:"",n.sizeAttenuation?"#define USE_SIZEATTENUATION":"",n.numLightProbes>0?"#define USE_LIGHT_PROBES":"",n.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",n.reverseDepthBuffer?"#define USE_REVERSEDEPTHBUF":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING","\tattribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR","\tattribute vec3 instanceColor;","#endif","#ifdef USE_INSTANCING_MORPH","\tuniform sampler2D morphTexture;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1","\tattribute vec2 uv1;","#endif","#ifdef USE_UV2","\tattribute vec2 uv2;","#endif","#ifdef USE_UV3","\tattribute vec2 uv3;","#endif","#ifdef USE_TANGENT","\tattribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )","\tattribute vec4 color;","#elif defined( USE_COLOR )","\tattribute vec3 color;","#endif","#ifdef USE_SKINNING","\tattribute vec4 skinIndex;","\tattribute vec4 skinWeight;","#endif","\n"].filter(ra).join("\n"),y=[ma(n),"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,v,n.useFog&&n.fog?"#define USE_FOG":"",n.useFog&&n.fogExp2?"#define FOG_EXP2":"",n.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",n.map?"#define USE_MAP":"",n.matcap?"#define USE_MATCAP":"",n.envMap?"#define USE_ENVMAP":"",n.envMap?"#define "+u:"",n.envMap?"#define "+d:"",n.envMap?"#define "+m:"",f?"#define CUBEUV_TEXEL_WIDTH "+f.texelWidth:"",f?"#define CUBEUV_TEXEL_HEIGHT "+f.texelHeight:"",f?"#define CUBEUV_MAX_MIP "+f.maxMip+".0":"",n.lightMap?"#define USE_LIGHTMAP":"",n.aoMap?"#define USE_AOMAP":"",n.bumpMap?"#define USE_BUMPMAP":"",n.normalMap?"#define USE_NORMALMAP":"",n.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",n.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",n.emissiveMap?"#define USE_EMISSIVEMAP":"",n.anisotropy?"#define USE_ANISOTROPY":"",n.anisotropyMap?"#define USE_ANISOTROPYMAP":"",n.clearcoat?"#define USE_CLEARCOAT":"",n.clearcoatMap?"#define USE_CLEARCOATMAP":"",n.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",n.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",n.dispersion?"#define USE_DISPERSION":"",n.iridescence?"#define USE_IRIDESCENCE":"",n.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",n.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",n.specularMap?"#define USE_SPECULARMAP":"",n.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",n.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",n.roughnessMap?"#define USE_ROUGHNESSMAP":"",n.metalnessMap?"#define USE_METALNESSMAP":"",n.alphaMap?"#define USE_ALPHAMAP":"",n.alphaTest?"#define USE_ALPHATEST":"",n.alphaHash?"#define USE_ALPHAHASH":"",n.sheen?"#define USE_SHEEN":"",n.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",n.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",n.transmission?"#define USE_TRANSMISSION":"",n.transmissionMap?"#define USE_TRANSMISSIONMAP":"",n.thicknessMap?"#define USE_THICKNESSMAP":"",n.vertexTangents&&!1===n.flatShading?"#define USE_TANGENT":"",n.vertexColors||n.instancingColor||n.batchingColor?"#define USE_COLOR":"",n.vertexAlphas?"#define USE_COLOR_ALPHA":"",n.vertexUv1s?"#define USE_UV1":"",n.vertexUv2s?"#define USE_UV2":"",n.vertexUv3s?"#define USE_UV3":"",n.pointsUvs?"#define USE_POINTS_UV":"",n.gradientMap?"#define USE_GRADIENTMAP":"",n.flatShading?"#define FLAT_SHADED":"",n.doubleSided?"#define DOUBLE_SIDED":"",n.flipSided?"#define FLIP_SIDED":"",n.shadowMapEnabled?"#define USE_SHADOWMAP":"",n.shadowMapEnabled?"#define "+l:"",n.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",n.numLightProbes>0?"#define USE_LIGHT_PROBES":"",n.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",n.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",n.reverseDepthBuffer?"#define USE_REVERSEDEPTHBUF":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",0!==n.toneMapping?"#define TONE_MAPPING":"",0!==n.toneMapping?ur.tonemapping_pars_fragment:"",0!==n.toneMapping?na("toneMapping",n.toneMapping):"",n.dithering?"#define DITHERING":"",n.opaque?"#define OPAQUE":"",ur.colorspace_pars_fragment,ea("linearToOutputTexel",n.outputColorSpace),(_e.getLuminanceCoefficients(ia),["float luminance( const in vec3 rgb ) {",`\tconst vec3 weights = vec3( ${ia.x.toFixed(4)}, ${ia.y.toFixed(4)}, ${ia.z.toFixed(4)} );`,"\treturn dot( weights, rgb );","}"].join("\n")),n.useDepthPacking?"#define DEPTH_PACKING "+n.depthPacking:"","\n"].filter(ra).join("\n")),a=la(a),a=sa(a,n),a=aa(a,n),o=la(o),o=sa(o,n),o=aa(o,n),a=da(a),o=da(o),!0!==n.isRawShaderMaterial&&(M="#version 300 es\n",x=[g,"#define attribute in","#define varying out","#define texture2D texture"].join("\n")+"\n"+x,y=["#define varying in",n.glslVersion===Gt?"":"layout(location = 0) out highp vec4 pc_fragColor;",n.glslVersion===Gt?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join("\n")+"\n"+y);const S=M+x+a,b=M+y+o,w=$s(r,r.VERTEX_SHADER,S),T=$s(r,r.FRAGMENT_SHADER,b);function E(e){if(t.debug.checkShaderErrors){const n=r.getProgramInfoLog(_).trim(),i=r.getShaderInfoLog(w).trim(),s=r.getShaderInfoLog(T).trim();let a=!0,o=!0;if(!1===r.getProgramParameter(_,r.LINK_STATUS))if(a=!1,"function"==typeof t.debug.onShaderError)t.debug.onShaderError(r,_,w,T);else{const t=ta(r,w,"vertex"),i=ta(r,T,"fragment");console.error("THREE.WebGLProgram: Shader Error "+r.getError()+" - VALIDATE_STATUS "+r.getProgramParameter(_,r.VALIDATE_STATUS)+"\n\nMaterial Name: "+e.name+"\nMaterial Type: "+e.type+"\n\nProgram Info Log: "+n+"\n"+t+"\n"+i)}else""!==n?console.warn("THREE.WebGLProgram: Program Info Log:",n):""!==i&&""!==s||(o=!1);o&&(e.diagnostics={runnable:a,programLog:n,vertexShader:{log:i,prefix:x},fragmentShader:{log:s,prefix:y}})}r.deleteShader(w),r.deleteShader(T),A=new Ks(r,_),R=function(t,e){const n={},i=t.getProgramParameter(e,t.ACTIVE_ATTRIBUTES);for(let r=0;r0,Y=s.clearcoat>0,Z=s.dispersion>0,J=s.iridescence>0,K=s.sheen>0,$=s.transmission>0,Q=q&&!!s.anisotropyMap,tt=Y&&!!s.clearcoatMap,et=Y&&!!s.clearcoatNormalMap,nt=Y&&!!s.clearcoatRoughnessMap,it=J&&!!s.iridescenceMap,rt=J&&!!s.iridescenceThicknessMap,st=K&&!!s.sheenColorMap,at=K&&!!s.sheenRoughnessMap,ot=!!s.specularMap,lt=!!s.specularColorMap,ct=!!s.specularIntensityMap,ht=$&&!!s.transmissionMap,ut=$&&!!s.thicknessMap,dt=!!s.gradientMap,pt=!!s.alphaMap,mt=s.alphaTest>0,ft=!!s.alphaHash,gt=!!s.extensions;let vt=0;s.toneMapped&&(null!==U&&!0!==U.isXRRenderTarget||(vt=t.toneMapping));const _t={shaderID:T,shaderType:s.type,shaderName:s.name,vertexShader:R,fragmentShader:C,defines:s.defines,customVertexShaderID:P,customFragmentShaderID:I,isRawShaderMaterial:!0===s.isRawShaderMaterial,glslVersion:s.glslVersion,precision:f,batching:N,batchingColor:N&&null!==x._colorsTexture,instancing:D,instancingColor:D&&null!==x.instanceColor,instancingMorph:D&&null!==x.morphTexture,supportsVertexTextures:m,outputColorSpace:null===U?t.outputColorSpace:!0===U.isXRRenderTarget?U.texture.colorSpace:Dt,alphaToCoverage:!!s.alphaToCoverage,map:O,matcap:F,envMap:B,envMapMode:B&&b.mapping,envMapCubeUVHeight:w,aoMap:z,lightMap:k,bumpMap:V,normalMap:H,displacementMap:m&&G,emissiveMap:W,normalMapObjectSpace:H&&1===s.normalMapType,normalMapTangentSpace:H&&0===s.normalMapType,metalnessMap:X,roughnessMap:j,anisotropy:q,anisotropyMap:Q,clearcoat:Y,clearcoatMap:tt,clearcoatNormalMap:et,clearcoatRoughnessMap:nt,dispersion:Z,iridescence:J,iridescenceMap:it,iridescenceThicknessMap:rt,sheen:K,sheenColorMap:st,sheenRoughnessMap:at,specularMap:ot,specularColorMap:lt,specularIntensityMap:ct,transmission:$,transmissionMap:ht,thicknessMap:ut,gradientMap:dt,opaque:!1===s.transparent&&1===s.blending&&!1===s.alphaToCoverage,alphaMap:pt,alphaTest:mt,alphaHash:ft,combine:s.combine,mapUv:O&&v(s.map.channel),aoMapUv:z&&v(s.aoMap.channel),lightMapUv:k&&v(s.lightMap.channel),bumpMapUv:V&&v(s.bumpMap.channel),normalMapUv:H&&v(s.normalMap.channel),displacementMapUv:G&&v(s.displacementMap.channel),emissiveMapUv:W&&v(s.emissiveMap.channel),metalnessMapUv:X&&v(s.metalnessMap.channel),roughnessMapUv:j&&v(s.roughnessMap.channel),anisotropyMapUv:Q&&v(s.anisotropyMap.channel),clearcoatMapUv:tt&&v(s.clearcoatMap.channel),clearcoatNormalMapUv:et&&v(s.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:nt&&v(s.clearcoatRoughnessMap.channel),iridescenceMapUv:it&&v(s.iridescenceMap.channel),iridescenceThicknessMapUv:rt&&v(s.iridescenceThicknessMap.channel),sheenColorMapUv:st&&v(s.sheenColorMap.channel),sheenRoughnessMapUv:at&&v(s.sheenRoughnessMap.channel),specularMapUv:ot&&v(s.specularMap.channel),specularColorMapUv:lt&&v(s.specularColorMap.channel),specularIntensityMapUv:ct&&v(s.specularIntensityMap.channel),transmissionMapUv:ht&&v(s.transmissionMap.channel),thicknessMapUv:ut&&v(s.thicknessMap.channel),alphaMapUv:pt&&v(s.alphaMap.channel),vertexTangents:!!M.attributes.tangent&&(H||q),vertexColors:s.vertexColors,vertexAlphas:!0===s.vertexColors&&!!M.attributes.color&&4===M.attributes.color.itemSize,pointsUvs:!0===x.isPoints&&!!M.attributes.uv&&(O||pt),fog:!!y,useFog:!0===s.fog,fogExp2:!!y&&y.isFogExp2,flatShading:!0===s.flatShading,sizeAttenuation:!0===s.sizeAttenuation,logarithmicDepthBuffer:u,reverseDepthBuffer:d,skinning:!0===x.isSkinnedMesh,morphTargets:void 0!==M.morphAttributes.position,morphNormals:void 0!==M.morphAttributes.normal,morphColors:void 0!==M.morphAttributes.color,morphTargetsCount:A,morphTextureStride:L,numDirLights:o.directional.length,numPointLights:o.point.length,numSpotLights:o.spot.length,numSpotLightMaps:o.spotLightMap.length,numRectAreaLights:o.rectArea.length,numHemiLights:o.hemi.length,numDirLightShadows:o.directionalShadowMap.length,numPointLightShadows:o.pointShadowMap.length,numSpotLightShadows:o.spotShadowMap.length,numSpotLightShadowsWithMaps:o.numSpotLightShadowsWithMaps,numLightProbes:o.numLightProbes,numClippingPlanes:a.numPlanes,numClipIntersection:a.numIntersection,dithering:s.dithering,shadowMapEnabled:t.shadowMap.enabled&&h.length>0,shadowMapType:t.shadowMap.type,toneMapping:vt,decodeVideoTexture:O&&!0===s.map.isVideoTexture&&_e.getTransfer(s.map.colorSpace)===Bt,premultipliedAlpha:s.premultipliedAlpha,doubleSided:2===s.side,flipSided:1===s.side,useDepthPacking:s.depthPacking>=0,depthPacking:s.depthPacking||0,index0AttributeName:s.index0AttributeName,extensionClipCullDistance:gt&&!0===s.extensions.clipCullDistance&&i.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(gt&&!0===s.extensions.multiDraw||N)&&i.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:i.has("KHR_parallel_shader_compile"),customProgramCacheKey:s.customProgramCacheKey()};return _t.vertexUv1s=c.has(1),_t.vertexUv2s=c.has(2),_t.vertexUv3s=c.has(3),c.clear(),_t},getProgramCacheKey:function(e){const n=[];if(e.shaderID?n.push(e.shaderID):(n.push(e.customVertexShaderID),n.push(e.customFragmentShaderID)),void 0!==e.defines)for(const t in e.defines)n.push(t),n.push(e.defines[t]);return!1===e.isRawShaderMaterial&&(function(t,e){t.push(e.precision),t.push(e.outputColorSpace),t.push(e.envMapMode),t.push(e.envMapCubeUVHeight),t.push(e.mapUv),t.push(e.alphaMapUv),t.push(e.lightMapUv),t.push(e.aoMapUv),t.push(e.bumpMapUv),t.push(e.normalMapUv),t.push(e.displacementMapUv),t.push(e.emissiveMapUv),t.push(e.metalnessMapUv),t.push(e.roughnessMapUv),t.push(e.anisotropyMapUv),t.push(e.clearcoatMapUv),t.push(e.clearcoatNormalMapUv),t.push(e.clearcoatRoughnessMapUv),t.push(e.iridescenceMapUv),t.push(e.iridescenceThicknessMapUv),t.push(e.sheenColorMapUv),t.push(e.sheenRoughnessMapUv),t.push(e.specularMapUv),t.push(e.specularColorMapUv),t.push(e.specularIntensityMapUv),t.push(e.transmissionMapUv),t.push(e.thicknessMapUv),t.push(e.combine),t.push(e.fogExp2),t.push(e.sizeAttenuation),t.push(e.morphTargetsCount),t.push(e.morphAttributeCount),t.push(e.numDirLights),t.push(e.numPointLights),t.push(e.numSpotLights),t.push(e.numSpotLightMaps),t.push(e.numHemiLights),t.push(e.numRectAreaLights),t.push(e.numDirLightShadows),t.push(e.numPointLightShadows),t.push(e.numSpotLightShadows),t.push(e.numSpotLightShadowsWithMaps),t.push(e.numLightProbes),t.push(e.shadowMapType),t.push(e.toneMapping),t.push(e.numClippingPlanes),t.push(e.numClipIntersection),t.push(e.depthPacking)}(n,e),function(t,e){o.disableAll(),e.supportsVertexTextures&&o.enable(0),e.instancing&&o.enable(1),e.instancingColor&&o.enable(2),e.instancingMorph&&o.enable(3),e.matcap&&o.enable(4),e.envMap&&o.enable(5),e.normalMapObjectSpace&&o.enable(6),e.normalMapTangentSpace&&o.enable(7),e.clearcoat&&o.enable(8),e.iridescence&&o.enable(9),e.alphaTest&&o.enable(10),e.vertexColors&&o.enable(11),e.vertexAlphas&&o.enable(12),e.vertexUv1s&&o.enable(13),e.vertexUv2s&&o.enable(14),e.vertexUv3s&&o.enable(15),e.vertexTangents&&o.enable(16),e.anisotropy&&o.enable(17),e.alphaHash&&o.enable(18),e.batching&&o.enable(19),e.dispersion&&o.enable(20),e.batchingColor&&o.enable(21),t.push(o.mask),o.disableAll(),e.fog&&o.enable(0),e.useFog&&o.enable(1),e.flatShading&&o.enable(2),e.logarithmicDepthBuffer&&o.enable(3),e.reverseDepthBuffer&&o.enable(4),e.skinning&&o.enable(5),e.morphTargets&&o.enable(6),e.morphNormals&&o.enable(7),e.morphColors&&o.enable(8),e.premultipliedAlpha&&o.enable(9),e.shadowMapEnabled&&o.enable(10),e.doubleSided&&o.enable(11),e.flipSided&&o.enable(12),e.useDepthPacking&&o.enable(13),e.dithering&&o.enable(14),e.transmission&&o.enable(15),e.sheen&&o.enable(16),e.opaque&&o.enable(17),e.pointsUvs&&o.enable(18),e.decodeVideoTexture&&o.enable(19),e.alphaToCoverage&&o.enable(20),t.push(o.mask)}(n,e),n.push(t.outputColorSpace)),n.push(e.customProgramCacheKey),n.join()},getUniforms:function(t){const e=g[t.type];let n;if(e){const t=pr[e];n=Wi.clone(t.uniforms)}else n=t.uniforms;return n},acquireProgram:function(e,n){let i;for(let t=0,e=h.length;t0?i.push(h):!0===a.transparent?r.push(h):n.push(h)},unshift:function(t,e,a,o,l,c){const h=s(t,e,a,o,l,c);a.transmission>0?i.unshift(h):!0===a.transparent?r.unshift(h):n.unshift(h)},finish:function(){for(let n=e,i=t.length;n1&&n.sort(t||Ma),i.length>1&&i.sort(e||Sa),r.length>1&&r.sort(e||Sa)}}}function wa(){let t=new WeakMap;return{get:function(e,n){const i=t.get(e);let r;return void 0===i?(r=new ba,t.set(e,[r])):n>=i.length?(r=new ba,i.push(r)):r=i[n],r},dispose:function(){t=new WeakMap}}}function Ta(){const t={};return{get:function(e){if(void 0!==t[e.id])return t[e.id];let n;switch(e.type){case"DirectionalLight":n={direction:new De,color:new ii};break;case"SpotLight":n={position:new De,direction:new De,color:new ii,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":n={position:new De,color:new ii,distance:0,decay:0};break;case"HemisphereLight":n={direction:new De,skyColor:new ii,groundColor:new ii};break;case"RectAreaLight":n={color:new ii,position:new De,halfWidth:new De,halfHeight:new De}}return t[e.id]=n,n}}}let Ea=0;function Aa(t,e){return(e.castShadow?2:0)-(t.castShadow?2:0)+(e.map?1:0)-(t.map?1:0)}function Ra(t){const e=new Ta,n=function(){const t={};return{get:function(e){if(void 0!==t[e.id])return t[e.id];let n;switch(e.type){case"DirectionalLight":case"SpotLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new re};break;case"PointLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new re,shadowCameraNear:1,shadowCameraFar:1e3}}return t[e.id]=n,n}}}(),i={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let t=0;t<9;t++)i.probe.push(new De);const r=new De,s=new un,a=new un;return{setup:function(r){let s=0,a=0,o=0;for(let t=0;t<9;t++)i.probe[t].set(0,0,0);let l=0,c=0,h=0,u=0,d=0,p=0,m=0,f=0,g=0,v=0,_=0;r.sort(Aa);for(let t=0,x=r.length;t0&&(!0===t.has("OES_texture_float_linear")?(i.rectAreaLTC1=dr.LTC_FLOAT_1,i.rectAreaLTC2=dr.LTC_FLOAT_2):(i.rectAreaLTC1=dr.LTC_HALF_1,i.rectAreaLTC2=dr.LTC_HALF_2)),i.ambient[0]=s,i.ambient[1]=a,i.ambient[2]=o;const x=i.hash;x.directionalLength===l&&x.pointLength===c&&x.spotLength===h&&x.rectAreaLength===u&&x.hemiLength===d&&x.numDirectionalShadows===p&&x.numPointShadows===m&&x.numSpotShadows===f&&x.numSpotMaps===g&&x.numLightProbes===_||(i.directional.length=l,i.spot.length=h,i.rectArea.length=u,i.point.length=c,i.hemi.length=d,i.directionalShadow.length=p,i.directionalShadowMap.length=p,i.pointShadow.length=m,i.pointShadowMap.length=m,i.spotShadow.length=f,i.spotShadowMap.length=f,i.directionalShadowMatrix.length=p,i.pointShadowMatrix.length=m,i.spotLightMatrix.length=f+g-v,i.spotLightMap.length=g,i.numSpotLightShadowsWithMaps=v,i.numLightProbes=_,x.directionalLength=l,x.pointLength=c,x.spotLength=h,x.rectAreaLength=u,x.hemiLength=d,x.numDirectionalShadows=p,x.numPointShadows=m,x.numSpotShadows=f,x.numSpotMaps=g,x.numLightProbes=_,i.version=Ea++)},setupView:function(t,e){let n=0,o=0,l=0,c=0,h=0;const u=e.matrixWorldInverse;for(let e=0,d=t.length;e=r.length?(s=new Ca(t),r.push(s)):s=r[i],s},dispose:function(){e=new WeakMap}}}class Ia extends ai{constructor(t){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=3200,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(t)}copy(t){return super.copy(t),this.depthPacking=t.depthPacking,this.map=t.map,this.alphaMap=t.alphaMap,this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this}}class La extends ai{constructor(t){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(t)}copy(t){return super.copy(t),this.map=t.map,this.alphaMap=t.alphaMap,this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this}}function Ua(t,e,n){let i=new or;const r=new re,s=new re,a=new Re,o=new Ia({depthPacking:3201}),l=new La,c={},h=n.maxTextureSize,u={0:1,1:0,2:2},d=new Xi({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new re},radius:{value:4}},vertexShader:"void main() {\n\tgl_Position = vec4( position, 1.0 );\n}",fragmentShader:"uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include \nvoid main() {\n\tconst float samples = float( VSM_SAMPLES );\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );\n\tfloat uvStart = samples <= 1.0 ? 0.0 : - 1.0;\n\tfor ( float i = 0.0; i < samples; i ++ ) {\n\t\tfloat uvOffset = uvStart + i * uvStride;\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean / samples;\n\tsquared_mean = squared_mean / samples;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}"}),p=d.clone();p.defines.HORIZONTAL_PASS=1;const m=new Ei;m.setAttribute("position",new fi(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const f=new Bi(m,d),g=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=1;let _=this.type;function x(n,i){const s=e.update(f);d.defines.VSM_SAMPLES!==n.blurSamples&&(d.defines.VSM_SAMPLES=n.blurSamples,p.defines.VSM_SAMPLES=n.blurSamples,d.needsUpdate=!0,p.needsUpdate=!0),null===n.mapPass&&(n.mapPass=new Pe(r.x,r.y)),d.uniforms.shadow_pass.value=n.map.texture,d.uniforms.resolution.value=n.mapSize,d.uniforms.radius.value=n.radius,t.setRenderTarget(n.mapPass),t.clear(),t.renderBufferDirect(i,null,s,d,f,null),p.uniforms.shadow_pass.value=n.mapPass.texture,p.uniforms.resolution.value=n.mapSize,p.uniforms.radius.value=n.radius,t.setRenderTarget(n.map),t.clear(),t.renderBufferDirect(i,null,s,p,f,null)}function y(e,n,i,r){let s=null;const a=!0===i.isPointLight?e.customDistanceMaterial:e.customDepthMaterial;if(void 0!==a)s=a;else if(s=!0===i.isPointLight?l:o,t.localClippingEnabled&&!0===n.clipShadows&&Array.isArray(n.clippingPlanes)&&0!==n.clippingPlanes.length||n.displacementMap&&0!==n.displacementScale||n.alphaMap&&n.alphaTest>0||n.map&&n.alphaTest>0){const t=s.uuid,e=n.uuid;let i=c[t];void 0===i&&(i={},c[t]=i);let r=i[e];void 0===r&&(r=s.clone(),i[e]=r,n.addEventListener("dispose",S)),s=r}return s.visible=n.visible,s.wireframe=n.wireframe,s.side=3===r?null!==n.shadowSide?n.shadowSide:n.side:null!==n.shadowSide?n.shadowSide:u[n.side],s.alphaMap=n.alphaMap,s.alphaTest=n.alphaTest,s.map=n.map,s.clipShadows=n.clipShadows,s.clippingPlanes=n.clippingPlanes,s.clipIntersection=n.clipIntersection,s.displacementMap=n.displacementMap,s.displacementScale=n.displacementScale,s.displacementBias=n.displacementBias,s.wireframeLinewidth=n.wireframeLinewidth,s.linewidth=n.linewidth,!0===i.isPointLight&&!0===s.isMeshDistanceMaterial&&(t.properties.get(s).light=i),s}function M(n,r,s,a,o){if(!1===n.visible)return;if(n.layers.test(r.layers)&&(n.isMesh||n.isLine||n.isPoints)&&(n.castShadow||n.receiveShadow&&3===o)&&(!n.frustumCulled||i.intersectsObject(n))){n.modelViewMatrix.multiplyMatrices(s.matrixWorldInverse,n.matrixWorld);const i=e.update(n),l=n.material;if(Array.isArray(l)){const e=i.groups;for(let c=0,h=e.length;ch||r.y>h)&&(r.x>h&&(s.x=Math.floor(h/f.x),r.x=s.x*f.x,u.mapSize.x=s.x),r.y>h&&(s.y=Math.floor(h/f.y),r.y=s.y*f.y,u.mapSize.y=s.y)),null===u.map||!0===p||!0===m){const t=3!==this.type?{minFilter:v,magFilter:v}:{};null!==u.map&&u.map.dispose(),u.map=new Pe(r.x,r.y,t),u.map.texture.name=c.name+".shadowMap",u.camera.updateProjectionMatrix()}t.setRenderTarget(u.map),t.clear();const g=u.getViewportCount();for(let t=0;t=1):-1!==U.indexOf("OpenGL ES")&&(L=parseFloat(/^OpenGL ES (\d)/.exec(U)[1]),I=L>=2);let D=null,N={};const O=t.getParameter(t.SCISSOR_BOX),F=t.getParameter(t.VIEWPORT),B=(new Re).fromArray(O),z=(new Re).fromArray(F);function k(e,n,i,r){const s=new Uint8Array(4),a=t.createTexture();t.bindTexture(e,a),t.texParameteri(e,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(e,t.TEXTURE_MAG_FILTER,t.NEAREST);for(let a=0;ae?(t.repeat.x=1,t.repeat.y=n/e,t.offset.x=0,t.offset.y=(1-t.repeat.y)/2):(t.repeat.x=e/n,t.repeat.y=1,t.offset.x=(1-t.repeat.x)/2,t.offset.y=0),t},cover:function(t,e){const n=t.image&&t.image.width?t.image.width/t.image.height:1;return n>e?(t.repeat.x=e/n,t.repeat.y=1,t.offset.x=(1-t.repeat.x)/2,t.offset.y=0):(t.repeat.x=1,t.repeat.y=n/e,t.offset.x=0,t.offset.y=(1-t.repeat.y)/2),t},fill:function(t){return t.repeat.x=1,t.repeat.y=1,t.offset.x=0,t.offset.y=0,t},getByteLength:Oa};function Ba(t,e,n,i,r,s,a){const o=e.has("WEBGL_multisampled_render_to_texture")?e.get("WEBGL_multisampled_render_to_texture"):null,l="undefined"!=typeof navigator&&/OculusBrowser/g.test(navigator.userAgent),c=new re,h=new WeakMap;let u;const d=new WeakMap;let p=!1;try{p="undefined"!=typeof OffscreenCanvas&&null!==new OffscreenCanvas(1,1).getContext("2d")}catch(t){}function w(t,e){return p?new OffscreenCanvas(t,e):he("canvas")}function T(t,e,n){let i=1;const r=it(t);if((r.width>n||r.height>n)&&(i=n/Math.max(r.width,r.height)),i<1){if("undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&t instanceof ImageBitmap||"undefined"!=typeof VideoFrame&&t instanceof VideoFrame){const n=Math.floor(i*r.width),s=Math.floor(i*r.height);void 0===u&&(u=w(n,s));const a=e?w(n,s):u;return a.width=n,a.height=s,a.getContext("2d").drawImage(t,0,0,n,s),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+r.width+"x"+r.height+") to ("+n+"x"+s+")."),a}return"data"in t&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+r.width+"x"+r.height+")."),t}return t}function A(t){return t.generateMipmaps&&t.minFilter!==v&&t.minFilter!==y}function P(e){t.generateMipmap(e)}function I(n,i,r,s,a=!1){if(null!==n){if(void 0!==t[n])return t[n];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+n+"'")}let o=i;if(i===t.RED&&(r===t.FLOAT&&(o=t.R32F),r===t.HALF_FLOAT&&(o=t.R16F),r===t.UNSIGNED_BYTE&&(o=t.R8)),i===t.RED_INTEGER&&(r===t.UNSIGNED_BYTE&&(o=t.R8UI),r===t.UNSIGNED_SHORT&&(o=t.R16UI),r===t.UNSIGNED_INT&&(o=t.R32UI),r===t.BYTE&&(o=t.R8I),r===t.SHORT&&(o=t.R16I),r===t.INT&&(o=t.R32I)),i===t.RG&&(r===t.FLOAT&&(o=t.RG32F),r===t.HALF_FLOAT&&(o=t.RG16F),r===t.UNSIGNED_BYTE&&(o=t.RG8)),i===t.RG_INTEGER&&(r===t.UNSIGNED_BYTE&&(o=t.RG8UI),r===t.UNSIGNED_SHORT&&(o=t.RG16UI),r===t.UNSIGNED_INT&&(o=t.RG32UI),r===t.BYTE&&(o=t.RG8I),r===t.SHORT&&(o=t.RG16I),r===t.INT&&(o=t.RG32I)),i===t.RGB_INTEGER&&(r===t.UNSIGNED_BYTE&&(o=t.RGB8UI),r===t.UNSIGNED_SHORT&&(o=t.RGB16UI),r===t.UNSIGNED_INT&&(o=t.RGB32UI),r===t.BYTE&&(o=t.RGB8I),r===t.SHORT&&(o=t.RGB16I),r===t.INT&&(o=t.RGB32I)),i===t.RGBA_INTEGER&&(r===t.UNSIGNED_BYTE&&(o=t.RGBA8UI),r===t.UNSIGNED_SHORT&&(o=t.RGBA16UI),r===t.UNSIGNED_INT&&(o=t.RGBA32UI),r===t.BYTE&&(o=t.RGBA8I),r===t.SHORT&&(o=t.RGBA16I),r===t.INT&&(o=t.RGBA32I)),i===t.RGB&&r===t.UNSIGNED_INT_5_9_9_9_REV&&(o=t.RGB9_E5),i===t.RGBA){const e=a?Ft:_e.getTransfer(s);r===t.FLOAT&&(o=t.RGBA32F),r===t.HALF_FLOAT&&(o=t.RGBA16F),r===t.UNSIGNED_BYTE&&(o=e===Bt?t.SRGB8_ALPHA8:t.RGBA8),r===t.UNSIGNED_SHORT_4_4_4_4&&(o=t.RGBA4),r===t.UNSIGNED_SHORT_5_5_5_1&&(o=t.RGB5_A1)}return o!==t.R16F&&o!==t.R32F&&o!==t.RG16F&&o!==t.RG32F&&o!==t.RGBA16F&&o!==t.RGBA32F||e.get("EXT_color_buffer_float"),o}function L(e,n){let i;return e?null===n||n===R||n===U?i=t.DEPTH24_STENCIL8:n===C?i=t.DEPTH32F_STENCIL8:n===E&&(i=t.DEPTH24_STENCIL8,console.warn("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):null===n||n===R||n===U?i=t.DEPTH_COMPONENT24:n===C?i=t.DEPTH_COMPONENT32F:n===E&&(i=t.DEPTH_COMPONENT16),i}function D(t,e){return!0===A(t)||t.isFramebufferTexture&&t.minFilter!==v&&t.minFilter!==y?Math.log2(Math.max(e.width,e.height))+1:void 0!==t.mipmaps&&t.mipmaps.length>0?t.mipmaps.length:t.isCompressedTexture&&Array.isArray(t.image)?e.mipmaps.length:1}function N(t){const e=t.target;e.removeEventListener("dispose",N),function(t){const e=i.get(t);if(void 0===e.__webglInit)return;const n=t.source,r=d.get(n);if(r){const i=r[e.__cacheKey];i.usedTimes--,0===i.usedTimes&&B(t),0===Object.keys(r).length&&d.delete(n)}i.remove(t)}(e),e.isVideoTexture&&h.delete(e)}function O(e){const n=e.target;n.removeEventListener("dispose",O),function(e){const n=i.get(e);if(e.depthTexture&&e.depthTexture.dispose(),e.isWebGLCubeRenderTarget)for(let e=0;e<6;e++){if(Array.isArray(n.__webglFramebuffer[e]))for(let i=0;i0&&s.__version!==e.version){const t=e.image;if(null===t)console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");else{if(!1!==t.complete)return void Y(s,e,r);console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete")}}n.bindTexture(t.TEXTURE_2D,s.__webglTexture,t.TEXTURE0+r)}const G={[m]:t.REPEAT,[f]:t.CLAMP_TO_EDGE,[g]:t.MIRRORED_REPEAT},W={[v]:t.NEAREST,[_]:t.NEAREST_MIPMAP_NEAREST,[x]:t.NEAREST_MIPMAP_LINEAR,[y]:t.LINEAR,[M]:t.LINEAR_MIPMAP_NEAREST,[S]:t.LINEAR_MIPMAP_LINEAR},X={512:t.NEVER,519:t.ALWAYS,513:t.LESS,515:t.LEQUAL,514:t.EQUAL,518:t.GEQUAL,516:t.GREATER,517:t.NOTEQUAL};function j(n,s){if(s.type!==C||!1!==e.has("OES_texture_float_linear")||s.magFilter!==y&&s.magFilter!==M&&s.magFilter!==x&&s.magFilter!==S&&s.minFilter!==y&&s.minFilter!==M&&s.minFilter!==x&&s.minFilter!==S||console.warn("THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),t.texParameteri(n,t.TEXTURE_WRAP_S,G[s.wrapS]),t.texParameteri(n,t.TEXTURE_WRAP_T,G[s.wrapT]),n!==t.TEXTURE_3D&&n!==t.TEXTURE_2D_ARRAY||t.texParameteri(n,t.TEXTURE_WRAP_R,G[s.wrapR]),t.texParameteri(n,t.TEXTURE_MAG_FILTER,W[s.magFilter]),t.texParameteri(n,t.TEXTURE_MIN_FILTER,W[s.minFilter]),s.compareFunction&&(t.texParameteri(n,t.TEXTURE_COMPARE_MODE,t.COMPARE_REF_TO_TEXTURE),t.texParameteri(n,t.TEXTURE_COMPARE_FUNC,X[s.compareFunction])),!0===e.has("EXT_texture_filter_anisotropic")){if(s.magFilter===v)return;if(s.minFilter!==x&&s.minFilter!==S)return;if(s.type===C&&!1===e.has("OES_texture_float_linear"))return;if(s.anisotropy>1||i.get(s).__currentAnisotropy){const a=e.get("EXT_texture_filter_anisotropic");t.texParameterf(n,a.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(s.anisotropy,r.getMaxAnisotropy())),i.get(s).__currentAnisotropy=s.anisotropy}}}function q(e,n){let i=!1;void 0===e.__webglInit&&(e.__webglInit=!0,n.addEventListener("dispose",N));const r=n.source;let s=d.get(r);void 0===s&&(s={},d.set(r,s));const o=function(t){const e=[];return e.push(t.wrapS),e.push(t.wrapT),e.push(t.wrapR||0),e.push(t.magFilter),e.push(t.minFilter),e.push(t.anisotropy),e.push(t.internalFormat),e.push(t.format),e.push(t.type),e.push(t.generateMipmaps),e.push(t.premultiplyAlpha),e.push(t.flipY),e.push(t.unpackAlignment),e.push(t.colorSpace),e.join()}(n);if(o!==e.__cacheKey){void 0===s[o]&&(s[o]={texture:t.createTexture(),usedTimes:0},a.memory.textures++,i=!0),s[o].usedTimes++;const r=s[e.__cacheKey];void 0!==r&&(s[e.__cacheKey].usedTimes--,0===r.usedTimes&&B(n)),e.__cacheKey=o,e.__webglTexture=s[o].texture}return i}function Y(e,a,o){let l=t.TEXTURE_2D;(a.isDataArrayTexture||a.isCompressedArrayTexture)&&(l=t.TEXTURE_2D_ARRAY),a.isData3DTexture&&(l=t.TEXTURE_3D);const c=q(e,a),h=a.source;n.bindTexture(l,e.__webglTexture,t.TEXTURE0+o);const u=i.get(h);if(h.version!==u.__version||!0===c){n.activeTexture(t.TEXTURE0+o);const e=_e.getPrimaries(_e.workingColorSpace),i=a.colorSpace===Lt?null:_e.getPrimaries(a.colorSpace),d=a.colorSpace===Lt||e===i?t.NONE:t.BROWSER_DEFAULT_WEBGL;t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,a.flipY),t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,a.premultiplyAlpha),t.pixelStorei(t.UNPACK_ALIGNMENT,a.unpackAlignment),t.pixelStorei(t.UNPACK_COLORSPACE_CONVERSION_WEBGL,d);let p=T(a.image,!1,r.maxTextureSize);p=nt(a,p);const m=s.convert(a.format,a.colorSpace),f=s.convert(a.type);let g,v=I(a.internalFormat,m,f,a.colorSpace,a.isVideoTexture);j(l,a);const _=a.mipmaps,x=!0!==a.isVideoTexture,y=void 0===u.__version||!0===c,M=h.dataReady,S=D(a,p);if(a.isDepthTexture)v=L(a.format===V,a.type),y&&(x?n.texStorage2D(t.TEXTURE_2D,1,v,p.width,p.height):n.texImage2D(t.TEXTURE_2D,0,v,p.width,p.height,0,m,f,null));else if(a.isDataTexture)if(_.length>0){x&&y&&n.texStorage2D(t.TEXTURE_2D,S,v,_[0].width,_[0].height);for(let e=0,i=_.length;e0){const i=Oa(g.width,g.height,a.format,a.type);for(const r of a.layerUpdates){const s=g.data.subarray(r*i/g.data.BYTES_PER_ELEMENT,(r+1)*i/g.data.BYTES_PER_ELEMENT);n.compressedTexSubImage3D(t.TEXTURE_2D_ARRAY,e,0,0,r,g.width,g.height,1,m,s,0,0)}a.clearLayerUpdates()}else n.compressedTexSubImage3D(t.TEXTURE_2D_ARRAY,e,0,0,0,g.width,g.height,p.depth,m,g.data,0,0)}else n.compressedTexImage3D(t.TEXTURE_2D_ARRAY,e,v,g.width,g.height,p.depth,0,g.data,0,0);else console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else x?M&&n.texSubImage3D(t.TEXTURE_2D_ARRAY,e,0,0,0,g.width,g.height,p.depth,m,f,g.data):n.texImage3D(t.TEXTURE_2D_ARRAY,e,v,g.width,g.height,p.depth,0,m,f,g.data)}else{x&&y&&n.texStorage2D(t.TEXTURE_2D,S,v,_[0].width,_[0].height);for(let e=0,i=_.length;e0){const e=Oa(p.width,p.height,a.format,a.type);for(const i of a.layerUpdates){const r=p.data.subarray(i*e/p.data.BYTES_PER_ELEMENT,(i+1)*e/p.data.BYTES_PER_ELEMENT);n.texSubImage3D(t.TEXTURE_2D_ARRAY,0,0,0,i,p.width,p.height,1,m,f,r)}a.clearLayerUpdates()}else n.texSubImage3D(t.TEXTURE_2D_ARRAY,0,0,0,0,p.width,p.height,p.depth,m,f,p.data)}else n.texImage3D(t.TEXTURE_2D_ARRAY,0,v,p.width,p.height,p.depth,0,m,f,p.data);else if(a.isData3DTexture)x?(y&&n.texStorage3D(t.TEXTURE_3D,S,v,p.width,p.height,p.depth),M&&n.texSubImage3D(t.TEXTURE_3D,0,0,0,0,p.width,p.height,p.depth,m,f,p.data)):n.texImage3D(t.TEXTURE_3D,0,v,p.width,p.height,p.depth,0,m,f,p.data);else if(a.isFramebufferTexture){if(y)if(x)n.texStorage2D(t.TEXTURE_2D,S,v,p.width,p.height);else{let e=p.width,i=p.height;for(let r=0;r>=1,i>>=1}}else if(_.length>0){if(x&&y){const e=it(_[0]);n.texStorage2D(t.TEXTURE_2D,S,v,e.width,e.height)}for(let e=0,i=_.length;e>h),i=Math.max(1,r.height>>h);c===t.TEXTURE_3D||c===t.TEXTURE_2D_ARRAY?n.texImage3D(c,h,p,e,i,r.depth,0,u,d,null):n.texImage2D(c,h,p,e,i,0,u,d,null)}n.bindFramebuffer(t.FRAMEBUFFER,e),et(r)?o.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,l,c,i.get(a).__webglTexture,0,tt(r)):(c===t.TEXTURE_2D||c>=t.TEXTURE_CUBE_MAP_POSITIVE_X&&c<=t.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&t.framebufferTexture2D(t.FRAMEBUFFER,l,c,i.get(a).__webglTexture,h),n.bindFramebuffer(t.FRAMEBUFFER,null)}function J(e,n,i){if(t.bindRenderbuffer(t.RENDERBUFFER,e),n.depthBuffer){const r=n.depthTexture,s=r&&r.isDepthTexture?r.type:null,a=L(n.stencilBuffer,s),l=n.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,c=tt(n);et(n)?o.renderbufferStorageMultisampleEXT(t.RENDERBUFFER,c,a,n.width,n.height):i?t.renderbufferStorageMultisample(t.RENDERBUFFER,c,a,n.width,n.height):t.renderbufferStorage(t.RENDERBUFFER,a,n.width,n.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,l,t.RENDERBUFFER,e)}else{const e=n.textures;for(let r=0;r{delete r.__boundDepthTexture,delete r.__depthDisposeCallback,t.removeEventListener("dispose",e)};t.addEventListener("dispose",e),r.__depthDisposeCallback=e}r.__boundDepthTexture=t}if(e.depthTexture&&!r.__autoAllocateDepthBuffer){if(s)throw new Error("target.depthTexture not supported in Cube render targets");!function(e,r){if(r&&r.isWebGLCubeRenderTarget)throw new Error("Depth Texture with cube render targets is not supported");if(n.bindFramebuffer(t.FRAMEBUFFER,e),!r.depthTexture||!r.depthTexture.isDepthTexture)throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");i.get(r.depthTexture).__webglTexture&&r.depthTexture.image.width===r.width&&r.depthTexture.image.height===r.height||(r.depthTexture.image.width=r.width,r.depthTexture.image.height=r.height,r.depthTexture.needsUpdate=!0),H(r.depthTexture,0);const s=i.get(r.depthTexture).__webglTexture,a=tt(r);if(r.depthTexture.format===k)et(r)?o.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,t.DEPTH_ATTACHMENT,t.TEXTURE_2D,s,0,a):t.framebufferTexture2D(t.FRAMEBUFFER,t.DEPTH_ATTACHMENT,t.TEXTURE_2D,s,0);else{if(r.depthTexture.format!==V)throw new Error("Unknown depthTexture format");et(r)?o.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.TEXTURE_2D,s,0,a):t.framebufferTexture2D(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.TEXTURE_2D,s,0)}}(r.__webglFramebuffer,e)}else if(s){r.__webglDepthbuffer=[];for(let i=0;i<6;i++)if(n.bindFramebuffer(t.FRAMEBUFFER,r.__webglFramebuffer[i]),void 0===r.__webglDepthbuffer[i])r.__webglDepthbuffer[i]=t.createRenderbuffer(),J(r.__webglDepthbuffer[i],e,!1);else{const n=e.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,s=r.__webglDepthbuffer[i];t.bindRenderbuffer(t.RENDERBUFFER,s),t.framebufferRenderbuffer(t.FRAMEBUFFER,n,t.RENDERBUFFER,s)}}else if(n.bindFramebuffer(t.FRAMEBUFFER,r.__webglFramebuffer),void 0===r.__webglDepthbuffer)r.__webglDepthbuffer=t.createRenderbuffer(),J(r.__webglDepthbuffer,e,!1);else{const n=e.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,i=r.__webglDepthbuffer;t.bindRenderbuffer(t.RENDERBUFFER,i),t.framebufferRenderbuffer(t.FRAMEBUFFER,n,t.RENDERBUFFER,i)}n.bindFramebuffer(t.FRAMEBUFFER,null)}const $=[],Q=[];function tt(t){return Math.min(r.maxSamples,t.samples)}function et(t){const n=i.get(t);return t.samples>0&&!0===e.has("WEBGL_multisampled_render_to_texture")&&!1!==n.__useRenderToTexture}function nt(t,e){const n=t.colorSpace,i=t.format,r=t.type;return!0===t.isCompressedTexture||!0===t.isVideoTexture||n!==Dt&&n!==Lt&&(_e.getTransfer(n)===Bt?i===F&&r===b||console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):console.error("THREE.WebGLTextures: Unsupported texture color space:",n)),e}function it(t){return"undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement?(c.width=t.naturalWidth||t.width,c.height=t.naturalHeight||t.height):"undefined"!=typeof VideoFrame&&t instanceof VideoFrame?(c.width=t.displayWidth,c.height=t.displayHeight):(c.width=t.width,c.height=t.height),c}this.allocateTextureUnit=function(){const t=z;return t>=r.maxTextures&&console.warn("THREE.WebGLTextures: Trying to use "+t+" texture units while this GPU supports only "+r.maxTextures),z+=1,t},this.resetTextureUnits=function(){z=0},this.setTexture2D=H,this.setTexture2DArray=function(e,r){const s=i.get(e);e.version>0&&s.__version!==e.version?Y(s,e,r):n.bindTexture(t.TEXTURE_2D_ARRAY,s.__webglTexture,t.TEXTURE0+r)},this.setTexture3D=function(e,r){const s=i.get(e);e.version>0&&s.__version!==e.version?Y(s,e,r):n.bindTexture(t.TEXTURE_3D,s.__webglTexture,t.TEXTURE0+r)},this.setTextureCube=function(e,a){const o=i.get(e);e.version>0&&o.__version!==e.version?function(e,a,o){if(6!==a.image.length)return;const l=q(e,a),c=a.source;n.bindTexture(t.TEXTURE_CUBE_MAP,e.__webglTexture,t.TEXTURE0+o);const h=i.get(c);if(c.version!==h.__version||!0===l){n.activeTexture(t.TEXTURE0+o);const e=_e.getPrimaries(_e.workingColorSpace),i=a.colorSpace===Lt?null:_e.getPrimaries(a.colorSpace),u=a.colorSpace===Lt||e===i?t.NONE:t.BROWSER_DEFAULT_WEBGL;t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,a.flipY),t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,a.premultiplyAlpha),t.pixelStorei(t.UNPACK_ALIGNMENT,a.unpackAlignment),t.pixelStorei(t.UNPACK_COLORSPACE_CONVERSION_WEBGL,u);const d=a.isCompressedTexture||a.image[0].isCompressedTexture,p=a.image[0]&&a.image[0].isDataTexture,m=[];for(let t=0;t<6;t++)m[t]=d||p?p?a.image[t].image:a.image[t]:T(a.image[t],!0,r.maxCubemapSize),m[t]=nt(a,m[t]);const f=m[0],g=s.convert(a.format,a.colorSpace),v=s.convert(a.type),_=I(a.internalFormat,g,v,a.colorSpace),x=!0!==a.isVideoTexture,y=void 0===h.__version||!0===l,M=c.dataReady;let S,b=D(a,f);if(j(t.TEXTURE_CUBE_MAP,a),d){x&&y&&n.texStorage2D(t.TEXTURE_CUBE_MAP,b,_,f.width,f.height);for(let e=0;e<6;e++){S=m[e].mipmaps;for(let i=0;i0&&b++;const e=it(m[0]);n.texStorage2D(t.TEXTURE_CUBE_MAP,b,_,e.width,e.height)}for(let e=0;e<6;e++)if(p){x?M&&n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,0,0,m[e].width,m[e].height,g,v,m[e].data):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,_,m[e].width,m[e].height,0,g,v,m[e].data);for(let i=0;i1;if(u||(void 0===l.__webglTexture&&(l.__webglTexture=t.createTexture()),l.__version=r.version,a.memory.textures++),h){o.__webglFramebuffer=[];for(let e=0;e<6;e++)if(r.mipmaps&&r.mipmaps.length>0){o.__webglFramebuffer[e]=[];for(let n=0;n0){o.__webglFramebuffer=[];for(let e=0;e0&&!1===et(e)){o.__webglMultisampledFramebuffer=t.createFramebuffer(),o.__webglColorRenderbuffer=[],n.bindFramebuffer(t.FRAMEBUFFER,o.__webglMultisampledFramebuffer);for(let n=0;n0)for(let i=0;i0)for(let n=0;n0)if(!1===et(e)){const r=e.textures,s=e.width,a=e.height;let o=t.COLOR_BUFFER_BIT;const c=e.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,h=i.get(e),u=r.length>1;if(u)for(let e=0;eo+c?(l.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:t.handedness,target:this})):!l.inputState.pinching&&a<=o-c&&(l.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:t.handedness,target:this}))}else null!==o&&t.gripSpace&&(r=e.getPose(t.gripSpace,n),null!==r&&(o.matrix.fromArray(r.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,r.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(r.linearVelocity)):o.hasLinearVelocity=!1,r.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(r.angularVelocity)):o.hasAngularVelocity=!1));null!==a&&(i=e.getPose(t.targetRaySpace,n),null===i&&null!==r&&(i=r),null!==i&&(a.matrix.fromArray(i.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),a.matrixWorldNeedsUpdate=!0,i.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(i.linearVelocity)):a.hasLinearVelocity=!1,i.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(i.angularVelocity)):a.hasAngularVelocity=!1,this.dispatchEvent(Ha)))}return null!==a&&(a.visible=null!==i),null!==o&&(o.visible=null!==r),null!==l&&(l.visible=null!==s),this}_getHandJoint(t,e){if(void 0===t.joints[e.jointName]){const n=new Va;n.matrixAutoUpdate=!1,n.visible=!1,t.joints[e.jointName]=n,t.add(n)}return t.joints[e.jointName]}}class Wa{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(t,e,n){if(null===this.texture){const i=new Ae;t.properties.get(i).__webglTexture=e.texture,e.depthNear==n.depthNear&&e.depthFar==n.depthFar||(this.depthNear=e.depthNear,this.depthFar=e.depthFar),this.texture=i}}getMesh(t){if(null!==this.texture&&null===this.mesh){const e=t.cameras[0].viewport,n=new Xi({vertexShader:"\nvoid main() {\n\n\tgl_Position = vec4( position, 1.0 );\n\n}",fragmentShader:"\nuniform sampler2DArray depthColor;\nuniform float depthWidth;\nuniform float depthHeight;\n\nvoid main() {\n\n\tvec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight );\n\n\tif ( coord.x >= 1.0 ) {\n\n\t\tgl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r;\n\n\t} else {\n\n\t\tgl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r;\n\n\t}\n\n}",uniforms:{depthColor:{value:this.texture},depthWidth:{value:e.z},depthHeight:{value:e.w}}});this.mesh=new Bi(new hr(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class Xa extends jt{constructor(t,e){super();const n=this;let i=null,r=1,s=null,a="local-floor",o=1,l=null,c=null,h=null,u=null,d=null,p=null;const m=new Wa,f=e.getContextAttributes();let g=null,v=null;const _=[],x=[],y=new re;let M=null;const S=new Ji;S.layers.enable(1),S.viewport=new Re;const w=new Ji;w.layers.enable(2),w.viewport=new Re;const T=[S,w],E=new ka;E.layers.enable(1),E.layers.enable(2);let A=null,C=null;function P(t){const e=x.indexOf(t.inputSource);if(-1===e)return;const n=_[e];void 0!==n&&(n.update(t.inputSource,t.frame,l||s),n.dispatchEvent({type:t.type,data:t.inputSource}))}function I(){i.removeEventListener("select",P),i.removeEventListener("selectstart",P),i.removeEventListener("selectend",P),i.removeEventListener("squeeze",P),i.removeEventListener("squeezestart",P),i.removeEventListener("squeezeend",P),i.removeEventListener("end",I),i.removeEventListener("inputsourceschange",L);for(let t=0;t<_.length;t++){const e=x[t];null!==e&&(x[t]=null,_[t].disconnect(e))}A=null,C=null,m.reset(),t.setRenderTarget(g),d=null,u=null,h=null,i=null,v=null,z.stop(),n.isPresenting=!1,t.setPixelRatio(M),t.setSize(y.width,y.height,!1),n.dispatchEvent({type:"sessionend"})}function L(t){for(let e=0;e=0&&(x[i]=null,_[i].disconnect(n))}for(let e=0;e=x.length){x.push(n),i=t;break}if(null===x[t]){x[t]=n,i=t;break}}if(-1===i)break}const r=_[i];r&&r.connect(n)}}this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(t){let e=_[t];return void 0===e&&(e=new Ga,_[t]=e),e.getTargetRaySpace()},this.getControllerGrip=function(t){let e=_[t];return void 0===e&&(e=new Ga,_[t]=e),e.getGripSpace()},this.getHand=function(t){let e=_[t];return void 0===e&&(e=new Ga,_[t]=e),e.getHandSpace()},this.setFramebufferScaleFactor=function(t){r=t,!0===n.isPresenting&&console.warn("THREE.WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(t){a=t,!0===n.isPresenting&&console.warn("THREE.WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return l||s},this.setReferenceSpace=function(t){l=t},this.getBaseLayer=function(){return null!==u?u:d},this.getBinding=function(){return h},this.getFrame=function(){return p},this.getSession=function(){return i},this.setSession=async function(c){if(i=c,null!==i){if(g=t.getRenderTarget(),i.addEventListener("select",P),i.addEventListener("selectstart",P),i.addEventListener("selectend",P),i.addEventListener("squeeze",P),i.addEventListener("squeezestart",P),i.addEventListener("squeezeend",P),i.addEventListener("end",I),i.addEventListener("inputsourceschange",L),!0!==f.xrCompatible&&await e.makeXRCompatible(),M=t.getPixelRatio(),t.getSize(y),void 0===i.renderState.layers){const n={antialias:f.antialias,alpha:!0,depth:f.depth,stencil:f.stencil,framebufferScaleFactor:r};d=new XRWebGLLayer(i,e,n),i.updateRenderState({baseLayer:d}),t.setPixelRatio(1),t.setSize(d.framebufferWidth,d.framebufferHeight,!1),v=new Pe(d.framebufferWidth,d.framebufferHeight,{format:F,type:b,colorSpace:t.outputColorSpace,stencilBuffer:f.stencil})}else{let n=null,s=null,a=null;f.depth&&(a=f.stencil?e.DEPTH24_STENCIL8:e.DEPTH_COMPONENT24,n=f.stencil?V:k,s=f.stencil?U:R);const o={colorFormat:e.RGBA8,depthFormat:a,scaleFactor:r};h=new XRWebGLBinding(i,e),u=h.createProjectionLayer(o),i.updateRenderState({layers:[u]}),t.setPixelRatio(1),t.setSize(u.textureWidth,u.textureHeight,!1),v=new Pe(u.textureWidth,u.textureHeight,{format:F,type:b,depthTexture:new jr(u.textureWidth,u.textureHeight,s,void 0,void 0,void 0,void 0,void 0,void 0,n),stencilBuffer:f.stencil,colorSpace:t.outputColorSpace,samples:f.antialias?4:0,resolveDepthBuffer:!1===u.ignoreDepthValues})}v.isXRRenderTarget=!0,this.setFoveation(o),l=null,s=await i.requestReferenceSpace(a),z.setContext(i),z.start(),n.isPresenting=!0,n.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(null!==i)return i.environmentBlendMode},this.getDepthTexture=function(){return m.getDepthTexture()};const D=new De,N=new De;function O(t,e){null===e?t.matrixWorld.copy(t.matrix):t.matrixWorld.multiplyMatrices(e.matrixWorld,t.matrix),t.matrixWorldInverse.copy(t.matrixWorld).invert()}this.updateCamera=function(t){if(null===i)return;let e=t.near,n=t.far;null!==m.texture&&(m.depthNear>0&&(e=m.depthNear),m.depthFar>0&&(n=m.depthFar)),E.near=w.near=S.near=e,E.far=w.far=S.far=n,A===E.near&&C===E.far||(i.updateRenderState({depthNear:E.near,depthFar:E.far}),A=E.near,C=E.far);const r=t.parent,s=E.cameras;O(E,r);for(let t=0;t0&&(t.alphaTest.value=i.alphaTest);const r=e.get(i),s=r.envMap,a=r.envMapRotation;s&&(t.envMap.value=s,ja.copy(a),ja.x*=-1,ja.y*=-1,ja.z*=-1,s.isCubeTexture&&!1===s.isRenderTargetTexture&&(ja.y*=-1,ja.z*=-1),t.envMapRotation.value.setFromMatrix4(qa.makeRotationFromEuler(ja)),t.flipEnvMap.value=s.isCubeTexture&&!1===s.isRenderTargetTexture?-1:1,t.reflectivity.value=i.reflectivity,t.ior.value=i.ior,t.refractionRatio.value=i.refractionRatio),i.lightMap&&(t.lightMap.value=i.lightMap,t.lightMapIntensity.value=i.lightMapIntensity,n(i.lightMap,t.lightMapTransform)),i.aoMap&&(t.aoMap.value=i.aoMap,t.aoMapIntensity.value=i.aoMapIntensity,n(i.aoMap,t.aoMapTransform))}return{refreshFogUniforms:function(e,n){n.color.getRGB(e.fogColor.value,Gi(t)),n.isFog?(e.fogNear.value=n.near,e.fogFar.value=n.far):n.isFogExp2&&(e.fogDensity.value=n.density)},refreshMaterialUniforms:function(t,r,s,a,o){r.isMeshBasicMaterial||r.isMeshLambertMaterial?i(t,r):r.isMeshToonMaterial?(i(t,r),function(t,e){e.gradientMap&&(t.gradientMap.value=e.gradientMap)}(t,r)):r.isMeshPhongMaterial?(i(t,r),function(t,e){t.specular.value.copy(e.specular),t.shininess.value=Math.max(e.shininess,1e-4)}(t,r)):r.isMeshStandardMaterial?(i(t,r),function(t,e){t.metalness.value=e.metalness,e.metalnessMap&&(t.metalnessMap.value=e.metalnessMap,n(e.metalnessMap,t.metalnessMapTransform)),t.roughness.value=e.roughness,e.roughnessMap&&(t.roughnessMap.value=e.roughnessMap,n(e.roughnessMap,t.roughnessMapTransform)),e.envMap&&(t.envMapIntensity.value=e.envMapIntensity)}(t,r),r.isMeshPhysicalMaterial&&function(t,e,i){t.ior.value=e.ior,e.sheen>0&&(t.sheenColor.value.copy(e.sheenColor).multiplyScalar(e.sheen),t.sheenRoughness.value=e.sheenRoughness,e.sheenColorMap&&(t.sheenColorMap.value=e.sheenColorMap,n(e.sheenColorMap,t.sheenColorMapTransform)),e.sheenRoughnessMap&&(t.sheenRoughnessMap.value=e.sheenRoughnessMap,n(e.sheenRoughnessMap,t.sheenRoughnessMapTransform))),e.clearcoat>0&&(t.clearcoat.value=e.clearcoat,t.clearcoatRoughness.value=e.clearcoatRoughness,e.clearcoatMap&&(t.clearcoatMap.value=e.clearcoatMap,n(e.clearcoatMap,t.clearcoatMapTransform)),e.clearcoatRoughnessMap&&(t.clearcoatRoughnessMap.value=e.clearcoatRoughnessMap,n(e.clearcoatRoughnessMap,t.clearcoatRoughnessMapTransform)),e.clearcoatNormalMap&&(t.clearcoatNormalMap.value=e.clearcoatNormalMap,n(e.clearcoatNormalMap,t.clearcoatNormalMapTransform),t.clearcoatNormalScale.value.copy(e.clearcoatNormalScale),1===e.side&&t.clearcoatNormalScale.value.negate())),e.dispersion>0&&(t.dispersion.value=e.dispersion),e.iridescence>0&&(t.iridescence.value=e.iridescence,t.iridescenceIOR.value=e.iridescenceIOR,t.iridescenceThicknessMinimum.value=e.iridescenceThicknessRange[0],t.iridescenceThicknessMaximum.value=e.iridescenceThicknessRange[1],e.iridescenceMap&&(t.iridescenceMap.value=e.iridescenceMap,n(e.iridescenceMap,t.iridescenceMapTransform)),e.iridescenceThicknessMap&&(t.iridescenceThicknessMap.value=e.iridescenceThicknessMap,n(e.iridescenceThicknessMap,t.iridescenceThicknessMapTransform))),e.transmission>0&&(t.transmission.value=e.transmission,t.transmissionSamplerMap.value=i.texture,t.transmissionSamplerSize.value.set(i.width,i.height),e.transmissionMap&&(t.transmissionMap.value=e.transmissionMap,n(e.transmissionMap,t.transmissionMapTransform)),t.thickness.value=e.thickness,e.thicknessMap&&(t.thicknessMap.value=e.thicknessMap,n(e.thicknessMap,t.thicknessMapTransform)),t.attenuationDistance.value=e.attenuationDistance,t.attenuationColor.value.copy(e.attenuationColor)),e.anisotropy>0&&(t.anisotropyVector.value.set(e.anisotropy*Math.cos(e.anisotropyRotation),e.anisotropy*Math.sin(e.anisotropyRotation)),e.anisotropyMap&&(t.anisotropyMap.value=e.anisotropyMap,n(e.anisotropyMap,t.anisotropyMapTransform))),t.specularIntensity.value=e.specularIntensity,t.specularColor.value.copy(e.specularColor),e.specularColorMap&&(t.specularColorMap.value=e.specularColorMap,n(e.specularColorMap,t.specularColorMapTransform)),e.specularIntensityMap&&(t.specularIntensityMap.value=e.specularIntensityMap,n(e.specularIntensityMap,t.specularIntensityMapTransform))}(t,r,o)):r.isMeshMatcapMaterial?(i(t,r),function(t,e){e.matcap&&(t.matcap.value=e.matcap)}(t,r)):r.isMeshDepthMaterial?i(t,r):r.isMeshDistanceMaterial?(i(t,r),function(t,n){const i=e.get(n).light;t.referencePosition.value.setFromMatrixPosition(i.matrixWorld),t.nearDistance.value=i.shadow.camera.near,t.farDistance.value=i.shadow.camera.far}(t,r)):r.isMeshNormalMaterial?i(t,r):r.isLineBasicMaterial?(function(t,e){t.diffuse.value.copy(e.color),t.opacity.value=e.opacity,e.map&&(t.map.value=e.map,n(e.map,t.mapTransform))}(t,r),r.isLineDashedMaterial&&function(t,e){t.dashSize.value=e.dashSize,t.totalSize.value=e.dashSize+e.gapSize,t.scale.value=e.scale}(t,r)):r.isPointsMaterial?function(t,e,i,r){t.diffuse.value.copy(e.color),t.opacity.value=e.opacity,t.size.value=e.size*i,t.scale.value=.5*r,e.map&&(t.map.value=e.map,n(e.map,t.uvTransform)),e.alphaMap&&(t.alphaMap.value=e.alphaMap,n(e.alphaMap,t.alphaMapTransform)),e.alphaTest>0&&(t.alphaTest.value=e.alphaTest)}(t,r,s,a):r.isSpriteMaterial?function(t,e){t.diffuse.value.copy(e.color),t.opacity.value=e.opacity,t.rotation.value=e.rotation,e.map&&(t.map.value=e.map,n(e.map,t.mapTransform)),e.alphaMap&&(t.alphaMap.value=e.alphaMap,n(e.alphaMap,t.alphaMapTransform)),e.alphaTest>0&&(t.alphaTest.value=e.alphaTest)}(t,r):r.isShadowMaterial?(t.color.value.copy(r.color),t.opacity.value=r.opacity):r.isShaderMaterial&&(r.uniformsNeedUpdate=!1)}}}function Za(t,e,n,i){let r={},s={},a=[];const o=t.getParameter(t.MAX_UNIFORM_BUFFER_BINDINGS);function l(t,e,n,i){const r=t.value,s=e+"_"+n;if(void 0===i[s])return i[s]="number"==typeof r||"boolean"==typeof r?r:r.clone(),!0;{const t=i[s];if("number"==typeof r||"boolean"==typeof r){if(t!==r)return i[s]=r,!0}else if(!1===t.equals(r))return t.copy(r),!0}return!1}function c(t){const e={boundary:0,storage:0};return"number"==typeof t||"boolean"==typeof t?(e.boundary=4,e.storage=4):t.isVector2?(e.boundary=8,e.storage=8):t.isVector3||t.isColor?(e.boundary=16,e.storage=12):t.isVector4?(e.boundary=16,e.storage=16):t.isMatrix3?(e.boundary=48,e.storage=48):t.isMatrix4?(e.boundary=64,e.storage=64):t.isTexture?console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."):console.warn("THREE.WebGLRenderer: Unsupported uniform value type.",t),e}function h(e){const n=e.target;n.removeEventListener("dispose",h);const i=a.indexOf(n.__bindingPointIndex);a.splice(i,1),t.deleteBuffer(r[n.id]),delete r[n.id],delete s[n.id]}return{bind:function(t,e){const n=e.program;i.uniformBlockBinding(t,n)},update:function(n,u){let d=r[n.id];void 0===d&&(function(t){const e=t.uniforms;let n=0;for(let t=0,i=e.length;t0&&(n+=16-i),t.__size=n,t.__cache={}}(n),d=function(e){const n=function(){for(let t=0;t0&&(e.object.backgroundBlurriness=this.backgroundBlurriness),1!==this.backgroundIntensity&&(e.object.backgroundIntensity=this.backgroundIntensity),e.object.backgroundRotation=this.backgroundRotation.toArray(),1!==this.environmentIntensity&&(e.object.environmentIntensity=this.environmentIntensity),e.object.environmentRotation=this.environmentRotation.toArray(),e}}class Qa{constructor(t,e){this.isInterleavedBuffer=!0,this.array=t,this.stride=e,this.count=void 0!==t?t.length/e:0,this.usage=Ht,this.updateRanges=[],this.version=0,this.uuid=Kt()}onUploadCallback(){}set needsUpdate(t){!0===t&&this.version++}setUsage(t){return this.usage=t,this}addUpdateRange(t,e){this.updateRanges.push({start:t,count:e})}clearUpdateRanges(){this.updateRanges.length=0}copy(t){return this.array=new t.array.constructor(t.array),this.count=t.count,this.stride=t.stride,this.usage=t.usage,this}copyAt(t,e,n){t*=this.stride,n*=e.stride;for(let i=0,r=this.stride;it.far||e.push({distance:o,point:ro.clone(),uv:$n.getInterpolation(ro,ho,uo,po,mo,fo,go,new re),face:null,object:this})}copy(t,e){return super.copy(t,e),void 0!==t.center&&this.center.copy(t.center),this.material=t.material,this}}function _o(t,e,n,i,r,s){oo.subVectors(t,n).addScalar(.5).multiply(i),void 0!==r?(lo.x=s*oo.x-r*oo.y,lo.y=r*oo.x+s*oo.y):lo.copy(oo),t.copy(e),t.x+=lo.x,t.y+=lo.y,t.applyMatrix4(co)}const xo=new De,yo=new De;class Mo extends Bn{constructor(){super(),this._currentLevel=0,this.type="LOD",Object.defineProperties(this,{levels:{enumerable:!0,value:[]},isLOD:{value:!0}}),this.autoUpdate=!0}copy(t){super.copy(t,!1);const e=t.levels;for(let t=0,n=e.length;t0){let n,i;for(n=1,i=e.length;n0){xo.setFromMatrixPosition(this.matrixWorld);const n=t.ray.origin.distanceTo(xo);this.getObjectForDistance(n).raycast(t,e)}}update(t){const e=this.levels;if(e.length>1){xo.setFromMatrixPosition(t.matrixWorld),yo.setFromMatrixPosition(this.matrixWorld);const n=xo.distanceTo(yo)/t.zoom;let i,r;for(e[0].object.visible=!0,i=1,r=e.length;i=t))break;e[i-1].object.visible=!1,e[i].object.visible=!0}for(this._currentLevel=i-1;i=i.length&&i.push({start:-1,count:-1,z:-1,index:-1});const s=i[this.index];r.push(s),this.index++,s.start=t.start,s.count=t.count,s.z=e,s.index=n}reset(){this.list.length=0,this.index=0}}const Zo=new un,Jo=new un,Ko=new un,$o=new ii(1,1,1),Qo=new un,tl=new or,el=new Fe,nl=new en,il=new De,rl=new De,sl=new De,al=new Yo,ol=new Bi,ll=[];function cl(t,e,n=0){const i=e.itemSize;if(t.isInterleavedBufferAttribute||t.array.constructor!==e.array.constructor){const r=t.count;for(let s=0;s65535?new Uint32Array(i):new Uint16Array(i);e.setIndex(new fi(t,1))}this._geometryInitialized=!0}}_validateGeometry(t){const e=this.geometry;if(Boolean(t.getIndex())!==Boolean(e.getIndex()))throw new Error('BatchedMesh: All geometries must consistently have "index".');for(const n in e.attributes){if(!t.hasAttribute(n))throw new Error(`BatchedMesh: Added geometry missing "${n}". All geometries must have consistent attributes.`);const i=t.getAttribute(n),r=e.getAttribute(n);if(i.itemSize!==r.itemSize||i.normalized!==r.normalized)throw new Error("BatchedMesh: All attributes must have a consistent itemSize and normalized value.")}}setCustomSort(t){return this.customSort=t,this}computeBoundingBox(){null===this.boundingBox&&(this.boundingBox=new Fe);const t=this.boundingBox,e=this._drawInfo;t.makeEmpty();for(let n=0,i=e.length;n=this.maxInstanceCount&&0===this._availableInstanceIds.length)throw new Error("BatchedMesh: Maximum item count reached.");const e={visible:!0,active:!0,geometryIndex:t};let n=null;this._availableInstanceIds.length>0?(n=this._availableInstanceIds.pop(),this._drawInfo[n]=e):(n=this._drawInfo.length,this._drawInfo.push(e));const i=this._matricesTexture,r=i.image.data;Ko.toArray(r,16*n),i.needsUpdate=!0;const s=this._colorsTexture;return s&&($o.toArray(s.image.data,4*n),s.needsUpdate=!0),n}addGeometry(t,e=-1,n=-1){if(this._initializeGeometry(t),this._validateGeometry(t),this._drawInfo.length>=this._maxInstanceCount)throw new Error("BatchedMesh: Maximum item count reached.");const i={vertexStart:-1,vertexCount:-1,indexStart:-1,indexCount:-1};let r=null;const s=this._reservedRanges,a=this._drawRanges,o=this._bounds;0!==this._geometryCount&&(r=s[s.length-1]),i.vertexCount=-1===e?t.getAttribute("position").count:e,i.vertexStart=null===r?0:r.vertexStart+r.vertexCount;const l=t.getIndex(),c=null!==l;if(c&&(i.indexCount=-1===n?l.count:n,i.indexStart=null===r?0:r.indexStart+r.indexCount),-1!==i.indexStart&&i.indexStart+i.indexCount>this._maxIndexCount||i.vertexStart+i.vertexCount>this._maxVertexCount)throw new Error("BatchedMesh: Reserved space request exceeds the maximum buffer size.");const h=this._geometryCount;return this._geometryCount++,s.push(i),a.push({start:c?i.indexStart:i.vertexStart,count:-1}),o.push({boxInitialized:!1,box:new Fe,sphereInitialized:!1,sphere:new en}),this.setGeometryAt(h,t),h}setGeometryAt(t,e){if(t>=this._geometryCount)throw new Error("BatchedMesh: Maximum geometry count reached.");this._validateGeometry(e);const n=this.geometry,i=null!==n.getIndex(),r=n.getIndex(),s=e.getIndex(),a=this._reservedRanges[t];if(i&&s.count>a.indexCount||e.attributes.position.count>a.vertexCount)throw new Error("BatchedMesh: Reserved space not large enough for provided geometry.");const o=a.vertexStart,l=a.vertexCount;for(const t in n.attributes){const i=e.getAttribute(t),r=n.getAttribute(t);cl(i,r,o);const s=i.itemSize;for(let t=i.count,e=l;t=e.length||!1===e[t].active||(e[t].active=!1,this._availableInstanceIds.push(t),this._visibilityChanged=!0),this}getBoundingBoxAt(t,e){if(t>=this._geometryCount)return null;const n=this._bounds[t],i=n.box,r=this.geometry;if(!1===n.boxInitialized){i.makeEmpty();const e=r.index,s=r.attributes.position,a=this._drawRanges[t];for(let t=a.start,n=a.start+a.count;t=this._geometryCount)return null;const n=this._bounds[t],i=n.sphere,r=this.geometry;if(!1===n.sphereInitialized){i.makeEmpty(),this.getBoundingBoxAt(t,el),el.getCenter(i.center);const e=r.index,s=r.attributes.position,a=this._drawRanges[t];let o=0;for(let t=a.start,n=a.start+a.count;t=n.length||!1===n[t].active||(e.toArray(r,16*t),i.needsUpdate=!0),this}getMatrixAt(t,e){const n=this._drawInfo,i=this._matricesTexture.image.data;return t>=n.length||!1===n[t].active?null:e.fromArray(i,16*t)}setColorAt(t,e){null===this._colorsTexture&&this._initColorsTexture();const n=this._colorsTexture,i=this._colorsTexture.image.data,r=this._drawInfo;return t>=r.length||!1===r[t].active||(e.toArray(i,4*t),n.needsUpdate=!0),this}getColorAt(t,e){const n=this._colorsTexture.image.data,i=this._drawInfo;return t>=i.length||!1===i[t].active?null:e.fromArray(n,4*t)}setVisibleAt(t,e){const n=this._drawInfo;return t>=n.length||!1===n[t].active||n[t].visible===e||(n[t].visible=e,this._visibilityChanged=!0),this}getVisibleAt(t){const e=this._drawInfo;return!(t>=e.length||!1===e[t].active)&&e[t].visible}setGeometryIdAt(t,e){const n=this._drawInfo;return t>=n.length||!1===n[t].active||e<0||e>=this._geometryCount?null:(n[t].geometryIndex=e,this)}getGeometryIdAt(t){const e=this._drawInfo;return t>=e.length||!1===e[t].active?-1:e[t].geometryIndex}getGeometryRangeAt(t,e={}){if(t<0||t>=this._geometryCount)return null;const n=this._drawRanges[t];return e.start=n.start,e.count=n.count,e}raycast(t,e){const n=this._drawInfo,i=this._drawRanges,r=this.matrixWorld,s=this.geometry;ol.material=this.material,ol.geometry.index=s.index,ol.geometry.attributes=s.attributes,null===ol.geometry.boundingBox&&(ol.geometry.boundingBox=new Fe),null===ol.geometry.boundingSphere&&(ol.geometry.boundingSphere=new en);for(let s=0,a=n.length;s({...t}))),this._reservedRanges=t._reservedRanges.map((t=>({...t}))),this._drawInfo=t._drawInfo.map((t=>({...t}))),this._bounds=t._bounds.map((t=>({boxInitialized:t.boxInitialized,box:t.box.clone(),sphereInitialized:t.sphereInitialized,sphere:t.sphere.clone()}))),this._maxInstanceCount=t._maxInstanceCount,this._maxVertexCount=t._maxVertexCount,this._maxIndexCount=t._maxIndexCount,this._geometryInitialized=t._geometryInitialized,this._geometryCount=t._geometryCount,this._multiDrawCounts=t._multiDrawCounts.slice(),this._multiDrawStarts=t._multiDrawStarts.slice(),this._matricesTexture=t._matricesTexture.clone(),this._matricesTexture.image.data=this._matricesTexture.image.data.slice(),null!==this._colorsTexture&&(this._colorsTexture=t._colorsTexture.clone(),this._colorsTexture.image.data=this._colorsTexture.image.data.slice()),this}dispose(){return this.geometry.dispose(),this._matricesTexture.dispose(),this._matricesTexture=null,this._indirectTexture.dispose(),this._indirectTexture=null,null!==this._colorsTexture&&(this._colorsTexture.dispose(),this._colorsTexture=null),this}onBeforeRender(t,e,n,i,r){if(!this._visibilityChanged&&!this.perObjectFrustumCulled&&!this.sortObjects)return;const s=i.getIndex(),a=null===s?1:s.array.BYTES_PER_ELEMENT,o=this._drawInfo,l=this._multiDrawStarts,c=this._multiDrawCounts,h=this._drawRanges,u=this.perObjectFrustumCulled,d=this._indirectTexture,p=d.image.data;u&&(Qo.multiplyMatrices(n.projectionMatrix,n.matrixWorldInverse).multiply(this.matrixWorld),tl.setFromProjectionMatrix(Qo,t.coordinateSystem));let m=0;if(this.sortObjects){Jo.copy(this.matrixWorld).invert(),il.setFromMatrixPosition(n.matrixWorld).applyMatrix4(Jo),rl.set(0,0,-1).transformDirection(n.matrixWorld).transformDirection(Jo);for(let t=0,e=o.length;t0){const n=t[e[0]];if(void 0!==n){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let t=0,e=n.length;ti)return;vl.applyMatrix4(t.matrixWorld);const o=e.ray.origin.distanceTo(vl);return oe.far?void 0:{distance:o,point:_l.clone().applyMatrix4(t.matrixWorld),index:r,face:null,faceIndex:null,barycoord:null,object:t}}const Ml=new De,Sl=new De;class bl extends xl{constructor(t,e){super(t,e),this.isLineSegments=!0,this.type="LineSegments"}computeLineDistances(){const t=this.geometry;if(null===t.index){const e=t.attributes.position,n=[];for(let t=0,i=e.count;t0){const n=t[e[0]];if(void 0!==n){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let t=0,e=n.length;tr.far)return;s.push({distance:l,distanceToRay:Math.sqrt(o),point:n,index:e,face:null,faceIndex:null,barycoord:null,object:a})}}class Ll extends Ae{constructor(t,e,n,i,r,s,a,o,l,c,h,u){super(null,s,a,o,l,c,i,r,h,u),this.isCompressedTexture=!0,this.image={width:e,height:n},this.mipmaps=t,this.flipY=!1,this.generateMipmaps=!1}}class Ul{constructor(){this.type="Curve",this.arcLengthDivisions=200}getPoint(){return console.warn("THREE.Curve: .getPoint() not implemented."),null}getPointAt(t,e){const n=this.getUtoTmapping(t);return this.getPoint(n,e)}getPoints(t=5){const e=[];for(let n=0;n<=t;n++)e.push(this.getPoint(n/t));return e}getSpacedPoints(t=5){const e=[];for(let n=0;n<=t;n++)e.push(this.getPointAt(n/t));return e}getLength(){const t=this.getLengths();return t[t.length-1]}getLengths(t=this.arcLengthDivisions){if(this.cacheArcLengths&&this.cacheArcLengths.length===t+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;const e=[];let n,i=this.getPoint(0),r=0;e.push(0);for(let s=1;s<=t;s++)n=this.getPoint(s/t),r+=n.distanceTo(i),e.push(r),i=n;return this.cacheArcLengths=e,e}updateArcLengths(){this.needsUpdate=!0,this.getLengths()}getUtoTmapping(t,e){const n=this.getLengths();let i=0;const r=n.length;let s;s=e||t*n[r-1];let a,o=0,l=r-1;for(;o<=l;)if(i=Math.floor(o+(l-o)/2),a=n[i]-s,a<0)o=i+1;else{if(!(a>0)){l=i;break}l=i-1}if(i=l,n[i]===s)return i/(r-1);const c=n[i];return(i+(s-c)/(n[i+1]-c))/(r-1)}getTangent(t,e){const n=1e-4;let i=t-n,r=t+n;i<0&&(i=0),r>1&&(r=1);const s=this.getPoint(i),a=this.getPoint(r),o=e||(s.isVector2?new re:new De);return o.copy(a).sub(s).normalize(),o}getTangentAt(t,e){const n=this.getUtoTmapping(t);return this.getTangent(n,e)}computeFrenetFrames(t,e){const n=new De,i=[],r=[],s=[],a=new De,o=new un;for(let e=0;e<=t;e++){const n=e/t;i[e]=this.getTangentAt(n,new De)}r[0]=new De,s[0]=new De;let l=Number.MAX_VALUE;const c=Math.abs(i[0].x),h=Math.abs(i[0].y),u=Math.abs(i[0].z);c<=l&&(l=c,n.set(1,0,0)),h<=l&&(l=h,n.set(0,1,0)),u<=l&&n.set(0,0,1),a.crossVectors(i[0],n).normalize(),r[0].crossVectors(i[0],a),s[0].crossVectors(i[0],r[0]);for(let e=1;e<=t;e++){if(r[e]=r[e-1].clone(),s[e]=s[e-1].clone(),a.crossVectors(i[e-1],i[e]),a.length()>Number.EPSILON){a.normalize();const t=Math.acos($t(i[e-1].dot(i[e]),-1,1));r[e].applyMatrix4(o.makeRotationAxis(a,t))}s[e].crossVectors(i[e],r[e])}if(!0===e){let e=Math.acos($t(r[0].dot(r[t]),-1,1));e/=t,i[0].dot(a.crossVectors(r[0],r[t]))>0&&(e=-e);for(let n=1;n<=t;n++)r[n].applyMatrix4(o.makeRotationAxis(i[n],e*n)),s[n].crossVectors(i[n],r[n])}return{tangents:i,normals:r,binormals:s}}clone(){return(new this.constructor).copy(this)}copy(t){return this.arcLengthDivisions=t.arcLengthDivisions,this}toJSON(){const t={metadata:{version:4.6,type:"Curve",generator:"Curve.toJSON"}};return t.arcLengthDivisions=this.arcLengthDivisions,t.type=this.type,t}fromJSON(t){return this.arcLengthDivisions=t.arcLengthDivisions,this}}class Dl extends Ul{constructor(t=0,e=0,n=1,i=1,r=0,s=2*Math.PI,a=!1,o=0){super(),this.isEllipseCurve=!0,this.type="EllipseCurve",this.aX=t,this.aY=e,this.xRadius=n,this.yRadius=i,this.aStartAngle=r,this.aEndAngle=s,this.aClockwise=a,this.aRotation=o}getPoint(t,e=new re){const n=e,i=2*Math.PI;let r=this.aEndAngle-this.aStartAngle;const s=Math.abs(r)i;)r-=i;r0?0:(Math.floor(Math.abs(l)/r)+1)*r:0===c&&l===r-1&&(l=r-2,c=1),this.closed||l>0?a=i[(l-1)%r]:(Fl.subVectors(i[0],i[1]).add(i[0]),a=Fl);const h=i[l%r],u=i[(l+1)%r];if(this.closed||l+2i.length-2?i.length-1:s+1],h=i[s>i.length-3?i.length-1:s+2];return n.set(Hl(a,o.x,l.x,c.x,h.x),Hl(a,o.y,l.y,c.y,h.y)),n}copy(t){super.copy(t),this.points=[];for(let e=0,n=t.points.length;e=n){const t=i[r]-n,s=this.curves[r],a=s.getLength(),o=0===a?0:1-t/a;return s.getPointAt(o,e)}r++}return null}getLength(){const t=this.getCurveLengths();return t[t.length-1]}updateArcLengths(){this.needsUpdate=!0,this.cacheLengths=null,this.getCurveLengths()}getCurveLengths(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;const t=[];let e=0;for(let n=0,i=this.curves.length;n1&&!e[e.length-1].equals(e[0])&&e.push(e[0]),e}copy(t){super.copy(t),this.curves=[];for(let e=0,n=t.curves.length;e0){const t=l.getPoint(0);t.equals(this.currentPoint)||this.lineTo(t.x,t.y)}this.curves.push(l);const c=l.getPoint(1);return this.currentPoint.copy(c),this}copy(t){return super.copy(t),this.currentPoint.copy(t.currentPoint),this}toJSON(){const t=super.toJSON();return t.currentPoint=this.currentPoint.toArray(),t}fromJSON(t){return super.fromJSON(t),this.currentPoint.fromArray(t.currentPoint),this}}class ec extends Ei{constructor(t=[new re(0,-.5),new re(.5,0),new re(0,.5)],e=12,n=0,i=2*Math.PI){super(),this.type="LatheGeometry",this.parameters={points:t,segments:e,phiStart:n,phiLength:i},e=Math.floor(e),i=$t(i,0,2*Math.PI);const r=[],s=[],a=[],o=[],l=[],c=1/e,h=new De,u=new re,d=new De,p=new De,m=new De;let f=0,g=0;for(let e=0;e<=t.length-1;e++)switch(e){case 0:f=t[e+1].x-t[e].x,g=t[e+1].y-t[e].y,d.x=1*g,d.y=-f,d.z=0*g,m.copy(d),d.normalize(),o.push(d.x,d.y,d.z);break;case t.length-1:o.push(m.x,m.y,m.z);break;default:f=t[e+1].x-t[e].x,g=t[e+1].y-t[e].y,d.x=1*g,d.y=-f,d.z=0*g,p.copy(d),d.x+=m.x,d.y+=m.y,d.z+=m.z,d.normalize(),o.push(d.x,d.y,d.z),m.copy(p)}for(let r=0;r<=e;r++){const d=n+r*c*i,p=Math.sin(d),m=Math.cos(d);for(let n=0;n<=t.length-1;n++){h.x=t[n].x*p,h.y=t[n].y,h.z=t[n].x*m,s.push(h.x,h.y,h.z),u.x=r/e,u.y=n/(t.length-1),a.push(u.x,u.y);const i=o[3*n+0]*p,c=o[3*n+1],d=o[3*n+0]*m;l.push(i,c,d)}}for(let n=0;n0&&(c.push(r,s,o),_+=3),e>0&&(c.push(s,a,o),_+=3)}l.addGroup(g,_,0),g+=_}(),!1===s&&(t>0&&v(!0),e>0&&v(!1)),this.setIndex(c),this.setAttribute("position",new _i(h,3)),this.setAttribute("normal",new _i(u,3)),this.setAttribute("uv",new _i(d,2))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new rc(t.radiusTop,t.radiusBottom,t.height,t.radialSegments,t.heightSegments,t.openEnded,t.thetaStart,t.thetaLength)}}class sc extends rc{constructor(t=1,e=1,n=32,i=1,r=!1,s=0,a=2*Math.PI){super(0,t,e,n,i,r,s,a),this.type="ConeGeometry",this.parameters={radius:t,height:e,radialSegments:n,heightSegments:i,openEnded:r,thetaStart:s,thetaLength:a}}static fromJSON(t){return new sc(t.radius,t.height,t.radialSegments,t.heightSegments,t.openEnded,t.thetaStart,t.thetaLength)}}class ac extends Ei{constructor(t=[],e=[],n=1,i=0){super(),this.type="PolyhedronGeometry",this.parameters={vertices:t,indices:e,radius:n,detail:i};const r=[],s=[];function a(t,e,n,i){const r=i+1,s=[];for(let i=0;i<=r;i++){s[i]=[];const a=t.clone().lerp(n,i/r),o=e.clone().lerp(n,i/r),l=r-i;for(let t=0;t<=l;t++)s[i][t]=0===t&&i===r?a:a.clone().lerp(o,t/l)}for(let t=0;t.9&&a<.1&&(e<.2&&(s[t+0]+=1),n<.2&&(s[t+2]+=1),i<.2&&(s[t+4]+=1))}}()}(),this.setAttribute("position",new _i(r,3)),this.setAttribute("normal",new _i(r.slice(),3)),this.setAttribute("uv",new _i(s,2)),0===i?this.computeVertexNormals():this.normalizeNormals()}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new ac(t.vertices,t.indices,t.radius,t.details)}}class oc extends ac{constructor(t=1,e=0){const n=(1+Math.sqrt(5))/2,i=1/n;super([-1,-1,-1,-1,-1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,1,1,1,-1,1,1,1,0,-i,-n,0,-i,n,0,i,-n,0,i,n,-i,-n,0,-i,n,0,i,-n,0,i,n,0,-n,0,-i,n,0,-i,-n,0,i,n,0,i],[3,11,7,3,7,15,3,15,13,7,19,17,7,17,6,7,6,15,17,4,8,17,8,10,17,10,6,8,0,16,8,16,2,8,2,10,0,12,1,0,1,18,0,18,16,6,10,2,6,2,13,6,13,15,2,16,18,2,18,3,2,3,13,18,1,9,18,9,11,18,11,3,4,14,12,4,12,0,4,0,8,11,9,5,11,5,19,11,19,7,19,5,14,19,14,4,19,4,17,1,12,14,1,14,5,1,5,9],t,e),this.type="DodecahedronGeometry",this.parameters={radius:t,detail:e}}static fromJSON(t){return new oc(t.radius,t.detail)}}const lc=new De,cc=new De,hc=new De,uc=new $n;class dc extends Ei{constructor(t=null,e=1){if(super(),this.type="EdgesGeometry",this.parameters={geometry:t,thresholdAngle:e},null!==t){const n=4,i=Math.pow(10,n),r=Math.cos(Zt*e),s=t.getIndex(),a=t.getAttribute("position"),o=s?s.count:a.count,l=[0,0,0],c=["a","b","c"],h=new Array(3),u={},d=[];for(let t=0;t0)for(s=e;s=e;s-=i)a=Nc(s,t[s],t[s+1],a);return a&&Cc(a,a.next)&&(Oc(a),a=a.next),a}function fc(t,e){if(!t)return t;e||(e=t);let n,i=t;do{if(n=!1,i.steiner||!Cc(i,i.next)&&0!==Rc(i.prev,i,i.next))i=i.next;else{if(Oc(i),i=e=i.prev,i===i.next)break;n=!0}}while(n||i!==e);return e}function gc(t,e,n,i,r,s,a){if(!t)return;!a&&s&&function(t,e,n,i){let r=t;do{0===r.z&&(r.z=wc(r.x,r.y,e,n,i)),r.prevZ=r.prev,r.nextZ=r.next,r=r.next}while(r!==t);r.prevZ.nextZ=null,r.prevZ=null,function(t){let e,n,i,r,s,a,o,l,c=1;do{for(n=t,t=null,s=null,a=0;n;){for(a++,i=n,o=0,e=0;e0||l>0&&i;)0!==o&&(0===l||!i||n.z<=i.z)?(r=n,n=n.nextZ,o--):(r=i,i=i.nextZ,l--),s?s.nextZ=r:t=r,r.prevZ=s,s=r;n=i}s.nextZ=null,c*=2}while(a>1)}(r)}(t,i,r,s);let o,l,c=t;for(;t.prev!==t.next;)if(o=t.prev,l=t.next,s?_c(t,i,r,s):vc(t))e.push(o.i/n|0),e.push(t.i/n|0),e.push(l.i/n|0),Oc(t),t=l.next,c=l.next;else if((t=l)===c){a?1===a?gc(t=xc(fc(t),e,n),e,n,i,r,s,2):2===a&&yc(t,e,n,i,r,s):gc(fc(t),e,n,i,r,s,1);break}}function vc(t){const e=t.prev,n=t,i=t.next;if(Rc(e,n,i)>=0)return!1;const r=e.x,s=n.x,a=i.x,o=e.y,l=n.y,c=i.y,h=rs?r>a?r:a:s>a?s:a,p=o>l?o>c?o:c:l>c?l:c;let m=i.next;for(;m!==e;){if(m.x>=h&&m.x<=d&&m.y>=u&&m.y<=p&&Ec(r,o,s,l,a,c,m.x,m.y)&&Rc(m.prev,m,m.next)>=0)return!1;m=m.next}return!0}function _c(t,e,n,i){const r=t.prev,s=t,a=t.next;if(Rc(r,s,a)>=0)return!1;const o=r.x,l=s.x,c=a.x,h=r.y,u=s.y,d=a.y,p=ol?o>c?o:c:l>c?l:c,g=h>u?h>d?h:d:u>d?u:d,v=wc(p,m,e,n,i),_=wc(f,g,e,n,i);let x=t.prevZ,y=t.nextZ;for(;x&&x.z>=v&&y&&y.z<=_;){if(x.x>=p&&x.x<=f&&x.y>=m&&x.y<=g&&x!==r&&x!==a&&Ec(o,h,l,u,c,d,x.x,x.y)&&Rc(x.prev,x,x.next)>=0)return!1;if(x=x.prevZ,y.x>=p&&y.x<=f&&y.y>=m&&y.y<=g&&y!==r&&y!==a&&Ec(o,h,l,u,c,d,y.x,y.y)&&Rc(y.prev,y,y.next)>=0)return!1;y=y.nextZ}for(;x&&x.z>=v;){if(x.x>=p&&x.x<=f&&x.y>=m&&x.y<=g&&x!==r&&x!==a&&Ec(o,h,l,u,c,d,x.x,x.y)&&Rc(x.prev,x,x.next)>=0)return!1;x=x.prevZ}for(;y&&y.z<=_;){if(y.x>=p&&y.x<=f&&y.y>=m&&y.y<=g&&y!==r&&y!==a&&Ec(o,h,l,u,c,d,y.x,y.y)&&Rc(y.prev,y,y.next)>=0)return!1;y=y.nextZ}return!0}function xc(t,e,n){let i=t;do{const r=i.prev,s=i.next.next;!Cc(r,s)&&Pc(r,i,i.next,s)&&Uc(r,s)&&Uc(s,r)&&(e.push(r.i/n|0),e.push(i.i/n|0),e.push(s.i/n|0),Oc(i),Oc(i.next),i=t=s),i=i.next}while(i!==t);return fc(i)}function yc(t,e,n,i,r,s){let a=t;do{let t=a.next.next;for(;t!==a.prev;){if(a.i!==t.i&&Ac(a,t)){let o=Dc(a,t);return a=fc(a,a.next),o=fc(o,o.next),gc(a,e,n,i,r,s,0),void gc(o,e,n,i,r,s,0)}t=t.next}a=a.next}while(a!==t)}function Mc(t,e){return t.x-e.x}function Sc(t,e){const n=function(t,e){let n,i=e,r=-1/0;const s=t.x,a=t.y;do{if(a<=i.y&&a>=i.next.y&&i.next.y!==i.y){const t=i.x+(a-i.y)*(i.next.x-i.x)/(i.next.y-i.y);if(t<=s&&t>r&&(r=t,n=i.x=i.x&&i.x>=l&&s!==i.x&&Ec(an.x||i.x===n.x&&bc(n,i)))&&(n=i,u=h)),i=i.next}while(i!==o);return n}(t,e);if(!n)return e;const i=Dc(n,t);return fc(i,i.next),fc(n,n.next)}function bc(t,e){return Rc(t.prev,t,e.prev)<0&&Rc(e.next,t,t.next)<0}function wc(t,e,n,i,r){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-n)*r|0)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-i)*r|0)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function Tc(t){let e=t,n=t;do{(e.x=(t-a)*(s-o)&&(t-a)*(i-o)>=(n-a)*(e-o)&&(n-a)*(s-o)>=(r-a)*(i-o)}function Ac(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){let n=t;do{if(n.i!==t.i&&n.next.i!==t.i&&n.i!==e.i&&n.next.i!==e.i&&Pc(n,n.next,t,e))return!0;n=n.next}while(n!==t);return!1}(t,e)&&(Uc(t,e)&&Uc(e,t)&&function(t,e){let n=t,i=!1;const r=(t.x+e.x)/2,s=(t.y+e.y)/2;do{n.y>s!=n.next.y>s&&n.next.y!==n.y&&r<(n.next.x-n.x)*(s-n.y)/(n.next.y-n.y)+n.x&&(i=!i),n=n.next}while(n!==t);return i}(t,e)&&(Rc(t.prev,t,e.prev)||Rc(t,e.prev,e))||Cc(t,e)&&Rc(t.prev,t,t.next)>0&&Rc(e.prev,e,e.next)>0)}function Rc(t,e,n){return(e.y-t.y)*(n.x-e.x)-(e.x-t.x)*(n.y-e.y)}function Cc(t,e){return t.x===e.x&&t.y===e.y}function Pc(t,e,n,i){const r=Lc(Rc(t,e,n)),s=Lc(Rc(t,e,i)),a=Lc(Rc(n,i,t)),o=Lc(Rc(n,i,e));return r!==s&&a!==o||!(0!==r||!Ic(t,n,e))||!(0!==s||!Ic(t,i,e))||!(0!==a||!Ic(n,t,i))||!(0!==o||!Ic(n,e,i))}function Ic(t,e,n){return e.x<=Math.max(t.x,n.x)&&e.x>=Math.min(t.x,n.x)&&e.y<=Math.max(t.y,n.y)&&e.y>=Math.min(t.y,n.y)}function Lc(t){return t>0?1:t<0?-1:0}function Uc(t,e){return Rc(t.prev,t,t.next)<0?Rc(t,e,t.next)>=0&&Rc(t,t.prev,e)>=0:Rc(t,e,t.prev)<0||Rc(t,t.next,e)<0}function Dc(t,e){const n=new Fc(t.i,t.x,t.y),i=new Fc(e.i,e.x,e.y),r=t.next,s=e.prev;return t.next=e,e.prev=t,n.next=r,r.prev=n,i.next=n,n.prev=i,s.next=i,i.prev=s,i}function Nc(t,e,n,i){const r=new Fc(t,e,n);return i?(r.next=i.next,r.prev=i,i.next.prev=r,i.next=r):(r.prev=r,r.next=r),r}function Oc(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function Fc(t,e,n){this.i=t,this.x=e,this.y=n,this.prev=null,this.next=null,this.z=0,this.prevZ=null,this.nextZ=null,this.steiner=!1}class Bc{static area(t){const e=t.length;let n=0;for(let i=e-1,r=0;r80*n){o=c=t[0],l=h=t[1];for(let e=n;ec&&(c=u),d>h&&(h=d);p=Math.max(c-o,h-l),p=0!==p?32767/p:0}return gc(s,a,n,o,l,p,0),a}(n,i);for(let t=0;t2&&t[e-1].equals(t[0])&&t.pop()}function kc(t,e){for(let n=0;nNumber.EPSILON){const u=Math.sqrt(h),d=Math.sqrt(l*l+c*c),p=e.x-o/u,m=e.y+a/u,f=((n.x-c/d-p)*c-(n.y+l/d-m)*l)/(a*c-o*l);i=p+a*f-t.x,r=m+o*f-t.y;const g=i*i+r*r;if(g<=2)return new re(i,r);s=Math.sqrt(g/2)}else{let t=!1;a>Number.EPSILON?l>Number.EPSILON&&(t=!0):a<-Number.EPSILON?l<-Number.EPSILON&&(t=!0):Math.sign(o)===Math.sign(c)&&(t=!0),t?(i=-o,r=a,s=Math.sqrt(h)):(i=a,r=o,s=Math.sqrt(h/2))}return new re(i/s,r/s)}const I=[];for(let t=0,e=E.length,n=e-1,i=t+1;t=0;t--){const e=t/p,n=h*Math.cos(e*Math.PI/2),i=u*Math.sin(e*Math.PI/2)+d;for(let t=0,e=E.length;t=0;){const i=n;let r=n-1;r<0&&(r=t.length-1);for(let t=0,n=o+2*p;t0)&&d.push(e,r,l),(t!==n-1||o0!=t>0&&this.version++,this._anisotropy=t}get clearcoat(){return this._clearcoat}set clearcoat(t){this._clearcoat>0!=t>0&&this.version++,this._clearcoat=t}get iridescence(){return this._iridescence}set iridescence(t){this._iridescence>0!=t>0&&this.version++,this._iridescence=t}get dispersion(){return this._dispersion}set dispersion(t){this._dispersion>0!=t>0&&this.version++,this._dispersion=t}get sheen(){return this._sheen}set sheen(t){this._sheen>0!=t>0&&this.version++,this._sheen=t}get transmission(){return this._transmission}set transmission(t){this._transmission>0!=t>0&&this.version++,this._transmission=t}copy(t){return super.copy(t),this.defines={STANDARD:"",PHYSICAL:""},this.anisotropy=t.anisotropy,this.anisotropyRotation=t.anisotropyRotation,this.anisotropyMap=t.anisotropyMap,this.clearcoat=t.clearcoat,this.clearcoatMap=t.clearcoatMap,this.clearcoatRoughness=t.clearcoatRoughness,this.clearcoatRoughnessMap=t.clearcoatRoughnessMap,this.clearcoatNormalMap=t.clearcoatNormalMap,this.clearcoatNormalScale.copy(t.clearcoatNormalScale),this.dispersion=t.dispersion,this.ior=t.ior,this.iridescence=t.iridescence,this.iridescenceMap=t.iridescenceMap,this.iridescenceIOR=t.iridescenceIOR,this.iridescenceThicknessRange=[...t.iridescenceThicknessRange],this.iridescenceThicknessMap=t.iridescenceThicknessMap,this.sheen=t.sheen,this.sheenColor.copy(t.sheenColor),this.sheenColorMap=t.sheenColorMap,this.sheenRoughness=t.sheenRoughness,this.sheenRoughnessMap=t.sheenRoughnessMap,this.transmission=t.transmission,this.transmissionMap=t.transmissionMap,this.thickness=t.thickness,this.thicknessMap=t.thicknessMap,this.attenuationDistance=t.attenuationDistance,this.attenuationColor.copy(t.attenuationColor),this.specularIntensity=t.specularIntensity,this.specularIntensityMap=t.specularIntensityMap,this.specularColor.copy(t.specularColor),this.specularColorMap=t.specularColorMap,this}}class sh extends ai{constructor(t){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new ii(16777215),this.specular=new ii(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new ii(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new re(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Mn,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.specular.copy(t.specular),this.shininess=t.shininess,this.map=t.map,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.emissive.copy(t.emissive),this.emissiveMap=t.emissiveMap,this.emissiveIntensity=t.emissiveIntensity,this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.specularMap=t.specularMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.envMapRotation.copy(t.envMapRotation),this.combine=t.combine,this.reflectivity=t.reflectivity,this.refractionRatio=t.refractionRatio,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.flatShading=t.flatShading,this.fog=t.fog,this}}class ah extends ai{constructor(t){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new ii(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new ii(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new re(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.gradientMap=t.gradientMap,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.emissive.copy(t.emissive),this.emissiveMap=t.emissiveMap,this.emissiveIntensity=t.emissiveIntensity,this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.alphaMap=t.alphaMap,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.fog=t.fog,this}}class oh extends ai{constructor(t){super(),this.isMeshNormalMaterial=!0,this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new re(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.setValues(t)}copy(t){return super.copy(t),this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.flatShading=t.flatShading,this}}class lh extends ai{constructor(t){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new ii(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new ii(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new re(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Mn,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.emissive.copy(t.emissive),this.emissiveMap=t.emissiveMap,this.emissiveIntensity=t.emissiveIntensity,this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.specularMap=t.specularMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.envMapRotation.copy(t.envMapRotation),this.combine=t.combine,this.reflectivity=t.reflectivity,this.refractionRatio=t.refractionRatio,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.flatShading=t.flatShading,this.fog=t.fog,this}}class ch extends ai{constructor(t){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new ii(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new re(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.flatShading=!1,this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.defines={MATCAP:""},this.color.copy(t.color),this.matcap=t.matcap,this.map=t.map,this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.alphaMap=t.alphaMap,this.flatShading=t.flatShading,this.fog=t.fog,this}}class hh extends ul{constructor(t){super(),this.isLineDashedMaterial=!0,this.type="LineDashedMaterial",this.scale=1,this.dashSize=3,this.gapSize=1,this.setValues(t)}copy(t){return super.copy(t),this.scale=t.scale,this.dashSize=t.dashSize,this.gapSize=t.gapSize,this}}function uh(t,e,n){return!t||!n&&t.constructor===e?t:"number"==typeof e.BYTES_PER_ELEMENT?new e(t):Array.prototype.slice.call(t)}function dh(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function ph(t){const e=t.length,n=new Array(e);for(let t=0;t!==e;++t)n[t]=t;return n.sort((function(e,n){return t[e]-t[n]})),n}function mh(t,e,n){const i=t.length,r=new t.constructor(i);for(let s=0,a=0;a!==i;++s){const i=n[s]*e;for(let n=0;n!==e;++n)r[a++]=t[i+n]}return r}function fh(t,e,n,i){let r=1,s=t[0];for(;void 0!==s&&void 0===s[i];)s=t[r++];if(void 0===s)return;let a=s[i];if(void 0!==a)if(Array.isArray(a))do{a=s[i],void 0!==a&&(e.push(s.time),n.push.apply(n,a)),s=t[r++]}while(void 0!==s);else if(void 0!==a.toArray)do{a=s[i],void 0!==a&&(e.push(s.time),a.toArray(n,n.length)),s=t[r++]}while(void 0!==s);else do{a=s[i],void 0!==a&&(e.push(s.time),n.push(a)),s=t[r++]}while(void 0!==s)}const gh={convertArray:uh,isTypedArray:dh,getKeyframeOrder:ph,sortedArray:mh,flattenJSON:fh,subclip:function(t,e,n,i,r=30){const s=t.clone();s.name=e;const a=[];for(let t=0;t=i)){l.push(e.times[t]);for(let n=0;ns.tracks[t].times[0]&&(o=s.tracks[t].times[0]);for(let t=0;t=i.times[u]){const t=u*l+o,e=t+l-o;d=i.values.slice(t,e)}else{const t=i.createInterpolant(),e=o,n=l-o;t.evaluate(s),d=t.resultBuffer.slice(e,n)}"quaternion"===r&&(new Ue).fromArray(d).normalize().conjugate().toArray(d);const p=a.times.length;for(let t=0;t=r)break t;{const a=e[1];t=r)break e}s=n,n=0}}for(;n>>1;te;)--s;if(++s,0!==r||s!==i){r>=s&&(s=Math.max(s,1),r=s-1);const t=this.getValueSize();this.times=n.slice(r,s),this.values=this.values.slice(r*t,s*t)}return this}validate(){let t=!0;const e=this.getValueSize();e-Math.floor(e)!=0&&(console.error("THREE.KeyframeTrack: Invalid value size in track.",this),t=!1);const n=this.times,i=this.values,r=n.length;0===r&&(console.error("THREE.KeyframeTrack: Track is empty.",this),t=!1);let s=null;for(let e=0;e!==r;e++){const i=n[e];if("number"==typeof i&&isNaN(i)){console.error("THREE.KeyframeTrack: Time is not a valid number.",this,e,i),t=!1;break}if(null!==s&&s>i){console.error("THREE.KeyframeTrack: Out of order keys.",this,e,i,s),t=!1;break}s=i}if(void 0!==i&&dh(i))for(let e=0,n=i.length;e!==n;++e){const n=i[e];if(isNaN(n)){console.error("THREE.KeyframeTrack: Value is not a valid number.",this,e,n),t=!1;break}}return t}optimize(){const t=this.times.slice(),e=this.values.slice(),n=this.getValueSize(),i=this.getInterpolation()===At,r=t.length-1;let s=1;for(let a=1;a0){t[s]=t[r];for(let t=r*n,i=s*n,a=0;a!==n;++a)e[i+a]=e[t+a];++s}return s!==t.length?(this.times=t.slice(0,s),this.values=e.slice(0,s*n)):(this.times=t,this.values=e),this}clone(){const t=this.times.slice(),e=this.values.slice(),n=new(0,this.constructor)(this.name,t,e);return n.createInterpolant=this.createInterpolant,n}}Mh.prototype.TimeBufferType=Float32Array,Mh.prototype.ValueBufferType=Float32Array,Mh.prototype.DefaultInterpolation=Et;class Sh extends Mh{constructor(t,e,n){super(t,e,n)}}Sh.prototype.ValueTypeName="bool",Sh.prototype.ValueBufferType=Array,Sh.prototype.DefaultInterpolation=Tt,Sh.prototype.InterpolantFactoryMethodLinear=void 0,Sh.prototype.InterpolantFactoryMethodSmooth=void 0;class bh extends Mh{}bh.prototype.ValueTypeName="color";class wh extends Mh{}wh.prototype.ValueTypeName="number";class Th extends vh{constructor(t,e,n,i){super(t,e,n,i)}interpolate_(t,e,n,i){const r=this.resultBuffer,s=this.sampleValues,a=this.valueSize,o=(n-e)/(i-e);let l=t*a;for(let t=l+a;l!==t;l+=4)Ue.slerpFlat(r,0,s,l-a,s,l,o);return r}}class Eh extends Mh{InterpolantFactoryMethodLinear(t){return new Th(this.times,this.values,this.getValueSize(),t)}}Eh.prototype.ValueTypeName="quaternion",Eh.prototype.InterpolantFactoryMethodSmooth=void 0;class Ah extends Mh{constructor(t,e,n){super(t,e,n)}}Ah.prototype.ValueTypeName="string",Ah.prototype.ValueBufferType=Array,Ah.prototype.DefaultInterpolation=Tt,Ah.prototype.InterpolantFactoryMethodLinear=void 0,Ah.prototype.InterpolantFactoryMethodSmooth=void 0;class Rh extends Mh{}Rh.prototype.ValueTypeName="vector";class Ch{constructor(t="",e=-1,n=[],i=2500){this.name=t,this.tracks=n,this.duration=e,this.blendMode=i,this.uuid=Kt(),this.duration<0&&this.resetDuration()}static parse(t){const e=[],n=t.tracks,i=1/(t.fps||1);for(let t=0,r=n.length;t!==r;++t)e.push(Ph(n[t]).scale(i));const r=new this(t.name,t.duration,e,t.blendMode);return r.uuid=t.uuid,r}static toJSON(t){const e=[],n=t.tracks,i={name:t.name,duration:t.duration,tracks:e,uuid:t.uuid,blendMode:t.blendMode};for(let t=0,i=n.length;t!==i;++t)e.push(Mh.toJSON(n[t]));return i}static CreateFromMorphTargetSequence(t,e,n,i){const r=e.length,s=[];for(let t=0;t1){const t=s[1];let e=i[t];e||(i[t]=e=[]),e.push(n)}}const s=[];for(const t in i)s.push(this.CreateFromMorphTargetSequence(t,i[t],e,n));return s}static parseAnimation(t,e){if(!t)return console.error("THREE.AnimationClip: No animation in JSONLoader data."),null;const n=function(t,e,n,i,r){if(0!==n.length){const s=[],a=[];fh(n,s,a,i),0!==s.length&&r.push(new t(e,s,a))}},i=[],r=t.name||"default",s=t.fps||30,a=t.blendMode;let o=t.length||-1;const l=t.hierarchy||[];for(let t=0;t{e&&e(r),this.manager.itemEnd(t)}),0),r;if(void 0!==Nh[t])return void Nh[t].push({onLoad:e,onProgress:n,onError:i});Nh[t]=[],Nh[t].push({onLoad:e,onProgress:n,onError:i});const s=new Request(t,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin"}),a=this.mimeType,o=this.responseType;fetch(s).then((e=>{if(200===e.status||0===e.status){if(0===e.status&&console.warn("THREE.FileLoader: HTTP Status 0 received."),"undefined"==typeof ReadableStream||void 0===e.body||void 0===e.body.getReader)return e;const n=Nh[t],i=e.body.getReader(),r=e.headers.get("X-File-Size")||e.headers.get("Content-Length"),s=r?parseInt(r):0,a=0!==s;let o=0;const l=new ReadableStream({start(t){!function e(){i.read().then((({done:i,value:r})=>{if(i)t.close();else{o+=r.byteLength;const i=new ProgressEvent("progress",{lengthComputable:a,loaded:o,total:s});for(let t=0,e=n.length;t{t.error(e)}))}()}});return new Response(l)}throw new Oh(`fetch for "${e.url}" responded with ${e.status}: ${e.statusText}`,e)})).then((t=>{switch(o){case"arraybuffer":return t.arrayBuffer();case"blob":return t.blob();case"document":return t.text().then((t=>(new DOMParser).parseFromString(t,a)));case"json":return t.json();default:if(void 0===a)return t.text();{const e=/charset="?([^;"\s]*)"?/i.exec(a),n=e&&e[1]?e[1].toLowerCase():void 0,i=new TextDecoder(n);return t.arrayBuffer().then((t=>i.decode(t)))}}})).then((e=>{Ih.add(t,e);const n=Nh[t];delete Nh[t];for(let t=0,i=n.length;t{const n=Nh[t];if(void 0===n)throw this.manager.itemError(t),e;delete Nh[t];for(let t=0,i=n.length;t{this.manager.itemEnd(t)})),this.manager.itemStart(t)}setResponseType(t){return this.responseType=t,this}setMimeType(t){return this.mimeType=t,this}}class Bh extends Dh{constructor(t){super(t)}load(t,e,n,i){void 0!==this.path&&(t=this.path+t),t=this.manager.resolveURL(t);const r=this,s=Ih.get(t);if(void 0!==s)return r.manager.itemStart(t),setTimeout((function(){e&&e(s),r.manager.itemEnd(t)}),0),s;const a=he("img");function o(){c(),Ih.add(t,this),e&&e(this),r.manager.itemEnd(t)}function l(e){c(),i&&i(e),r.manager.itemError(t),r.manager.itemEnd(t)}function c(){a.removeEventListener("load",o,!1),a.removeEventListener("error",l,!1)}return a.addEventListener("load",o,!1),a.addEventListener("error",l,!1),"data:"!==t.slice(0,5)&&void 0!==this.crossOrigin&&(a.crossOrigin=this.crossOrigin),r.manager.itemStart(t),a.src=t,a}}class zh extends Bn{constructor(t,e=1){super(),this.isLight=!0,this.type="Light",this.color=new ii(t),this.intensity=e}dispose(){}copy(t,e){return super.copy(t,e),this.color.copy(t.color),this.intensity=t.intensity,this}toJSON(t){const e=super.toJSON(t);return e.object.color=this.color.getHex(),e.object.intensity=this.intensity,void 0!==this.groundColor&&(e.object.groundColor=this.groundColor.getHex()),void 0!==this.distance&&(e.object.distance=this.distance),void 0!==this.angle&&(e.object.angle=this.angle),void 0!==this.decay&&(e.object.decay=this.decay),void 0!==this.penumbra&&(e.object.penumbra=this.penumbra),void 0!==this.shadow&&(e.object.shadow=this.shadow.toJSON()),void 0!==this.target&&(e.object.target=this.target.uuid),e}}class kh extends zh{constructor(t,e,n){super(t,n),this.isHemisphereLight=!0,this.type="HemisphereLight",this.position.copy(Bn.DEFAULT_UP),this.updateMatrix(),this.groundColor=new ii(e)}copy(t,e){return super.copy(t,e),this.groundColor.copy(t.groundColor),this}}const Vh=new un,Hh=new De,Gh=new De;class Wh{constructor(t){this.camera=t,this.intensity=1,this.bias=0,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new re(512,512),this.map=null,this.mapPass=null,this.matrix=new un,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new or,this._frameExtents=new re(1,1),this._viewportCount=1,this._viewports=[new Re(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(t){const e=this.camera,n=this.matrix;Hh.setFromMatrixPosition(t.matrixWorld),e.position.copy(Hh),Gh.setFromMatrixPosition(t.target.matrixWorld),e.lookAt(Gh),e.updateMatrixWorld(),Vh.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),this._frustum.setFromProjectionMatrix(Vh),n.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),n.multiply(Vh)}getViewport(t){return this._viewports[t]}getFrameExtents(){return this._frameExtents}dispose(){this.map&&this.map.dispose(),this.mapPass&&this.mapPass.dispose()}copy(t){return this.camera=t.camera.clone(),this.intensity=t.intensity,this.bias=t.bias,this.radius=t.radius,this.mapSize.copy(t.mapSize),this}clone(){return(new this.constructor).copy(this)}toJSON(){const t={};return 1!==this.intensity&&(t.intensity=this.intensity),0!==this.bias&&(t.bias=this.bias),0!==this.normalBias&&(t.normalBias=this.normalBias),1!==this.radius&&(t.radius=this.radius),512===this.mapSize.x&&512===this.mapSize.y||(t.mapSize=this.mapSize.toArray()),t.camera=this.camera.toJSON(!1).object,delete t.camera.matrix,t}}class Xh extends Wh{constructor(){super(new Ji(50,1,.5,500)),this.isSpotLightShadow=!0,this.focus=1}updateMatrices(t){const e=this.camera,n=2*Jt*t.angle*this.focus,i=this.mapSize.width/this.mapSize.height,r=t.distance||e.far;n===e.fov&&i===e.aspect&&r===e.far||(e.fov=n,e.aspect=i,e.far=r,e.updateProjectionMatrix()),super.updateMatrices(t)}copy(t){return super.copy(t),this.focus=t.focus,this}}class jh extends zh{constructor(t,e,n=0,i=Math.PI/3,r=0,s=2){super(t,e),this.isSpotLight=!0,this.type="SpotLight",this.position.copy(Bn.DEFAULT_UP),this.updateMatrix(),this.target=new Bn,this.distance=n,this.angle=i,this.penumbra=r,this.decay=s,this.map=null,this.shadow=new Xh}get power(){return this.intensity*Math.PI}set power(t){this.intensity=t/Math.PI}dispose(){this.shadow.dispose()}copy(t,e){return super.copy(t,e),this.distance=t.distance,this.angle=t.angle,this.penumbra=t.penumbra,this.decay=t.decay,this.target=t.target.clone(),this.shadow=t.shadow.clone(),this}}const qh=new un,Yh=new De,Zh=new De;class Jh extends Wh{constructor(){super(new Ji(90,1,.5,500)),this.isPointLightShadow=!0,this._frameExtents=new re(4,2),this._viewportCount=6,this._viewports=[new Re(2,1,1,1),new Re(0,1,1,1),new Re(3,1,1,1),new Re(1,1,1,1),new Re(3,0,1,1),new Re(1,0,1,1)],this._cubeDirections=[new De(1,0,0),new De(-1,0,0),new De(0,0,1),new De(0,0,-1),new De(0,1,0),new De(0,-1,0)],this._cubeUps=[new De(0,1,0),new De(0,1,0),new De(0,1,0),new De(0,1,0),new De(0,0,1),new De(0,0,-1)]}updateMatrices(t,e=0){const n=this.camera,i=this.matrix,r=t.distance||n.far;r!==n.far&&(n.far=r,n.updateProjectionMatrix()),Yh.setFromMatrixPosition(t.matrixWorld),n.position.copy(Yh),Zh.copy(n.position),Zh.add(this._cubeDirections[e]),n.up.copy(this._cubeUps[e]),n.lookAt(Zh),n.updateMatrixWorld(),i.makeTranslation(-Yh.x,-Yh.y,-Yh.z),qh.multiplyMatrices(n.projectionMatrix,n.matrixWorldInverse),this._frustum.setFromProjectionMatrix(qh)}}class Kh extends zh{constructor(t,e,n=0,i=2){super(t,e),this.isPointLight=!0,this.type="PointLight",this.distance=n,this.decay=i,this.shadow=new Jh}get power(){return 4*this.intensity*Math.PI}set power(t){this.intensity=t/(4*Math.PI)}dispose(){this.shadow.dispose()}copy(t,e){return super.copy(t,e),this.distance=t.distance,this.decay=t.decay,this.shadow=t.shadow.clone(),this}}class $h extends Wh{constructor(){super(new br(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}}class Qh extends zh{constructor(t,e){super(t,e),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(Bn.DEFAULT_UP),this.updateMatrix(),this.target=new Bn,this.shadow=new $h}dispose(){this.shadow.dispose()}copy(t){return super.copy(t),this.target=t.target.clone(),this.shadow=t.shadow.clone(),this}}class tu extends zh{constructor(t,e){super(t,e),this.isAmbientLight=!0,this.type="AmbientLight"}}class eu extends zh{constructor(t,e,n=10,i=10){super(t,e),this.isRectAreaLight=!0,this.type="RectAreaLight",this.width=n,this.height=i}get power(){return this.intensity*this.width*this.height*Math.PI}set power(t){this.intensity=t/(this.width*this.height*Math.PI)}copy(t){return super.copy(t),this.width=t.width,this.height=t.height,this}toJSON(t){const e=super.toJSON(t);return e.object.width=this.width,e.object.height=this.height,e}}class nu{constructor(){this.isSphericalHarmonics3=!0,this.coefficients=[];for(let t=0;t<9;t++)this.coefficients.push(new De)}set(t){for(let e=0;e<9;e++)this.coefficients[e].copy(t[e]);return this}zero(){for(let t=0;t<9;t++)this.coefficients[t].set(0,0,0);return this}getAt(t,e){const n=t.x,i=t.y,r=t.z,s=this.coefficients;return e.copy(s[0]).multiplyScalar(.282095),e.addScaledVector(s[1],.488603*i),e.addScaledVector(s[2],.488603*r),e.addScaledVector(s[3],.488603*n),e.addScaledVector(s[4],n*i*1.092548),e.addScaledVector(s[5],i*r*1.092548),e.addScaledVector(s[6],.315392*(3*r*r-1)),e.addScaledVector(s[7],n*r*1.092548),e.addScaledVector(s[8],.546274*(n*n-i*i)),e}getIrradianceAt(t,e){const n=t.x,i=t.y,r=t.z,s=this.coefficients;return e.copy(s[0]).multiplyScalar(.886227),e.addScaledVector(s[1],1.023328*i),e.addScaledVector(s[2],1.023328*r),e.addScaledVector(s[3],1.023328*n),e.addScaledVector(s[4],.858086*n*i),e.addScaledVector(s[5],.858086*i*r),e.addScaledVector(s[6],.743125*r*r-.247708),e.addScaledVector(s[7],.858086*n*r),e.addScaledVector(s[8],.429043*(n*n-i*i)),e}add(t){for(let e=0;e<9;e++)this.coefficients[e].add(t.coefficients[e]);return this}addScaledSH(t,e){for(let n=0;n<9;n++)this.coefficients[n].addScaledVector(t.coefficients[n],e);return this}scale(t){for(let e=0;e<9;e++)this.coefficients[e].multiplyScalar(t);return this}lerp(t,e){for(let n=0;n<9;n++)this.coefficients[n].lerp(t.coefficients[n],e);return this}equals(t){for(let e=0;e<9;e++)if(!this.coefficients[e].equals(t.coefficients[e]))return!1;return!0}copy(t){return this.set(t.coefficients)}clone(){return(new this.constructor).copy(this)}fromArray(t,e=0){const n=this.coefficients;for(let i=0;i<9;i++)n[i].fromArray(t,e+3*i);return this}toArray(t=[],e=0){const n=this.coefficients;for(let i=0;i<9;i++)n[i].toArray(t,e+3*i);return t}static getBasisAt(t,e){const n=t.x,i=t.y,r=t.z;e[0]=.282095,e[1]=.488603*i,e[2]=.488603*r,e[3]=.488603*n,e[4]=1.092548*n*i,e[5]=1.092548*i*r,e[6]=.315392*(3*r*r-1),e[7]=1.092548*n*r,e[8]=.546274*(n*n-i*i)}}class iu extends zh{constructor(t=new nu,e=1){super(void 0,e),this.isLightProbe=!0,this.sh=t}copy(t){return super.copy(t),this.sh.copy(t.sh),this}fromJSON(t){return this.intensity=t.intensity,this.sh.fromArray(t.sh),this}toJSON(t){const e=super.toJSON(t);return e.object.sh=this.sh.toArray(),e}}class ru extends Dh{constructor(t){super(t),this.textures={}}load(t,e,n,i){const r=this,s=new Fh(r.manager);s.setPath(r.path),s.setRequestHeader(r.requestHeader),s.setWithCredentials(r.withCredentials),s.load(t,(function(n){try{e(r.parse(JSON.parse(n)))}catch(e){i?i(e):console.error(e),r.manager.itemError(t)}}),n,i)}parse(t){const e=this.textures;function n(t){return void 0===e[t]&&console.warn("THREE.MaterialLoader: Undefined texture",t),e[t]}const i=this.createMaterialFromType(t.type);if(void 0!==t.uuid&&(i.uuid=t.uuid),void 0!==t.name&&(i.name=t.name),void 0!==t.color&&void 0!==i.color&&i.color.setHex(t.color),void 0!==t.roughness&&(i.roughness=t.roughness),void 0!==t.metalness&&(i.metalness=t.metalness),void 0!==t.sheen&&(i.sheen=t.sheen),void 0!==t.sheenColor&&(i.sheenColor=(new ii).setHex(t.sheenColor)),void 0!==t.sheenRoughness&&(i.sheenRoughness=t.sheenRoughness),void 0!==t.emissive&&void 0!==i.emissive&&i.emissive.setHex(t.emissive),void 0!==t.specular&&void 0!==i.specular&&i.specular.setHex(t.specular),void 0!==t.specularIntensity&&(i.specularIntensity=t.specularIntensity),void 0!==t.specularColor&&void 0!==i.specularColor&&i.specularColor.setHex(t.specularColor),void 0!==t.shininess&&(i.shininess=t.shininess),void 0!==t.clearcoat&&(i.clearcoat=t.clearcoat),void 0!==t.clearcoatRoughness&&(i.clearcoatRoughness=t.clearcoatRoughness),void 0!==t.dispersion&&(i.dispersion=t.dispersion),void 0!==t.iridescence&&(i.iridescence=t.iridescence),void 0!==t.iridescenceIOR&&(i.iridescenceIOR=t.iridescenceIOR),void 0!==t.iridescenceThicknessRange&&(i.iridescenceThicknessRange=t.iridescenceThicknessRange),void 0!==t.transmission&&(i.transmission=t.transmission),void 0!==t.thickness&&(i.thickness=t.thickness),void 0!==t.attenuationDistance&&(i.attenuationDistance=t.attenuationDistance),void 0!==t.attenuationColor&&void 0!==i.attenuationColor&&i.attenuationColor.setHex(t.attenuationColor),void 0!==t.anisotropy&&(i.anisotropy=t.anisotropy),void 0!==t.anisotropyRotation&&(i.anisotropyRotation=t.anisotropyRotation),void 0!==t.fog&&(i.fog=t.fog),void 0!==t.flatShading&&(i.flatShading=t.flatShading),void 0!==t.blending&&(i.blending=t.blending),void 0!==t.combine&&(i.combine=t.combine),void 0!==t.side&&(i.side=t.side),void 0!==t.shadowSide&&(i.shadowSide=t.shadowSide),void 0!==t.opacity&&(i.opacity=t.opacity),void 0!==t.transparent&&(i.transparent=t.transparent),void 0!==t.alphaTest&&(i.alphaTest=t.alphaTest),void 0!==t.alphaHash&&(i.alphaHash=t.alphaHash),void 0!==t.depthFunc&&(i.depthFunc=t.depthFunc),void 0!==t.depthTest&&(i.depthTest=t.depthTest),void 0!==t.depthWrite&&(i.depthWrite=t.depthWrite),void 0!==t.colorWrite&&(i.colorWrite=t.colorWrite),void 0!==t.blendSrc&&(i.blendSrc=t.blendSrc),void 0!==t.blendDst&&(i.blendDst=t.blendDst),void 0!==t.blendEquation&&(i.blendEquation=t.blendEquation),void 0!==t.blendSrcAlpha&&(i.blendSrcAlpha=t.blendSrcAlpha),void 0!==t.blendDstAlpha&&(i.blendDstAlpha=t.blendDstAlpha),void 0!==t.blendEquationAlpha&&(i.blendEquationAlpha=t.blendEquationAlpha),void 0!==t.blendColor&&void 0!==i.blendColor&&i.blendColor.setHex(t.blendColor),void 0!==t.blendAlpha&&(i.blendAlpha=t.blendAlpha),void 0!==t.stencilWriteMask&&(i.stencilWriteMask=t.stencilWriteMask),void 0!==t.stencilFunc&&(i.stencilFunc=t.stencilFunc),void 0!==t.stencilRef&&(i.stencilRef=t.stencilRef),void 0!==t.stencilFuncMask&&(i.stencilFuncMask=t.stencilFuncMask),void 0!==t.stencilFail&&(i.stencilFail=t.stencilFail),void 0!==t.stencilZFail&&(i.stencilZFail=t.stencilZFail),void 0!==t.stencilZPass&&(i.stencilZPass=t.stencilZPass),void 0!==t.stencilWrite&&(i.stencilWrite=t.stencilWrite),void 0!==t.wireframe&&(i.wireframe=t.wireframe),void 0!==t.wireframeLinewidth&&(i.wireframeLinewidth=t.wireframeLinewidth),void 0!==t.wireframeLinecap&&(i.wireframeLinecap=t.wireframeLinecap),void 0!==t.wireframeLinejoin&&(i.wireframeLinejoin=t.wireframeLinejoin),void 0!==t.rotation&&(i.rotation=t.rotation),void 0!==t.linewidth&&(i.linewidth=t.linewidth),void 0!==t.dashSize&&(i.dashSize=t.dashSize),void 0!==t.gapSize&&(i.gapSize=t.gapSize),void 0!==t.scale&&(i.scale=t.scale),void 0!==t.polygonOffset&&(i.polygonOffset=t.polygonOffset),void 0!==t.polygonOffsetFactor&&(i.polygonOffsetFactor=t.polygonOffsetFactor),void 0!==t.polygonOffsetUnits&&(i.polygonOffsetUnits=t.polygonOffsetUnits),void 0!==t.dithering&&(i.dithering=t.dithering),void 0!==t.alphaToCoverage&&(i.alphaToCoverage=t.alphaToCoverage),void 0!==t.premultipliedAlpha&&(i.premultipliedAlpha=t.premultipliedAlpha),void 0!==t.forceSinglePass&&(i.forceSinglePass=t.forceSinglePass),void 0!==t.visible&&(i.visible=t.visible),void 0!==t.toneMapped&&(i.toneMapped=t.toneMapped),void 0!==t.userData&&(i.userData=t.userData),void 0!==t.vertexColors&&("number"==typeof t.vertexColors?i.vertexColors=t.vertexColors>0:i.vertexColors=t.vertexColors),void 0!==t.uniforms)for(const e in t.uniforms){const r=t.uniforms[e];switch(i.uniforms[e]={},r.type){case"t":i.uniforms[e].value=n(r.value);break;case"c":i.uniforms[e].value=(new ii).setHex(r.value);break;case"v2":i.uniforms[e].value=(new re).fromArray(r.value);break;case"v3":i.uniforms[e].value=(new De).fromArray(r.value);break;case"v4":i.uniforms[e].value=(new Re).fromArray(r.value);break;case"m3":i.uniforms[e].value=(new se).fromArray(r.value);break;case"m4":i.uniforms[e].value=(new un).fromArray(r.value);break;default:i.uniforms[e].value=r.value}}if(void 0!==t.defines&&(i.defines=t.defines),void 0!==t.vertexShader&&(i.vertexShader=t.vertexShader),void 0!==t.fragmentShader&&(i.fragmentShader=t.fragmentShader),void 0!==t.glslVersion&&(i.glslVersion=t.glslVersion),void 0!==t.extensions)for(const e in t.extensions)i.extensions[e]=t.extensions[e];if(void 0!==t.lights&&(i.lights=t.lights),void 0!==t.clipping&&(i.clipping=t.clipping),void 0!==t.size&&(i.size=t.size),void 0!==t.sizeAttenuation&&(i.sizeAttenuation=t.sizeAttenuation),void 0!==t.map&&(i.map=n(t.map)),void 0!==t.matcap&&(i.matcap=n(t.matcap)),void 0!==t.alphaMap&&(i.alphaMap=n(t.alphaMap)),void 0!==t.bumpMap&&(i.bumpMap=n(t.bumpMap)),void 0!==t.bumpScale&&(i.bumpScale=t.bumpScale),void 0!==t.normalMap&&(i.normalMap=n(t.normalMap)),void 0!==t.normalMapType&&(i.normalMapType=t.normalMapType),void 0!==t.normalScale){let e=t.normalScale;!1===Array.isArray(e)&&(e=[e,e]),i.normalScale=(new re).fromArray(e)}return void 0!==t.displacementMap&&(i.displacementMap=n(t.displacementMap)),void 0!==t.displacementScale&&(i.displacementScale=t.displacementScale),void 0!==t.displacementBias&&(i.displacementBias=t.displacementBias),void 0!==t.roughnessMap&&(i.roughnessMap=n(t.roughnessMap)),void 0!==t.metalnessMap&&(i.metalnessMap=n(t.metalnessMap)),void 0!==t.emissiveMap&&(i.emissiveMap=n(t.emissiveMap)),void 0!==t.emissiveIntensity&&(i.emissiveIntensity=t.emissiveIntensity),void 0!==t.specularMap&&(i.specularMap=n(t.specularMap)),void 0!==t.specularIntensityMap&&(i.specularIntensityMap=n(t.specularIntensityMap)),void 0!==t.specularColorMap&&(i.specularColorMap=n(t.specularColorMap)),void 0!==t.envMap&&(i.envMap=n(t.envMap)),void 0!==t.envMapRotation&&i.envMapRotation.fromArray(t.envMapRotation),void 0!==t.envMapIntensity&&(i.envMapIntensity=t.envMapIntensity),void 0!==t.reflectivity&&(i.reflectivity=t.reflectivity),void 0!==t.refractionRatio&&(i.refractionRatio=t.refractionRatio),void 0!==t.lightMap&&(i.lightMap=n(t.lightMap)),void 0!==t.lightMapIntensity&&(i.lightMapIntensity=t.lightMapIntensity),void 0!==t.aoMap&&(i.aoMap=n(t.aoMap)),void 0!==t.aoMapIntensity&&(i.aoMapIntensity=t.aoMapIntensity),void 0!==t.gradientMap&&(i.gradientMap=n(t.gradientMap)),void 0!==t.clearcoatMap&&(i.clearcoatMap=n(t.clearcoatMap)),void 0!==t.clearcoatRoughnessMap&&(i.clearcoatRoughnessMap=n(t.clearcoatRoughnessMap)),void 0!==t.clearcoatNormalMap&&(i.clearcoatNormalMap=n(t.clearcoatNormalMap)),void 0!==t.clearcoatNormalScale&&(i.clearcoatNormalScale=(new re).fromArray(t.clearcoatNormalScale)),void 0!==t.iridescenceMap&&(i.iridescenceMap=n(t.iridescenceMap)),void 0!==t.iridescenceThicknessMap&&(i.iridescenceThicknessMap=n(t.iridescenceThicknessMap)),void 0!==t.transmissionMap&&(i.transmissionMap=n(t.transmissionMap)),void 0!==t.thicknessMap&&(i.thicknessMap=n(t.thicknessMap)),void 0!==t.anisotropyMap&&(i.anisotropyMap=n(t.anisotropyMap)),void 0!==t.sheenColorMap&&(i.sheenColorMap=n(t.sheenColorMap)),void 0!==t.sheenRoughnessMap&&(i.sheenRoughnessMap=n(t.sheenRoughnessMap)),i}setTextures(t){return this.textures=t,this}createMaterialFromType(t){return ru.createMaterialFromType(t)}static createMaterialFromType(t){return new{ShadowMaterial:eh,SpriteMaterial:no,RawShaderMaterial:nh,ShaderMaterial:Xi,PointsMaterial:Tl,MeshPhysicalMaterial:rh,MeshStandardMaterial:ih,MeshPhongMaterial:sh,MeshToonMaterial:ah,MeshNormalMaterial:oh,MeshLambertMaterial:lh,MeshDepthMaterial:Ia,MeshDistanceMaterial:La,MeshBasicMaterial:oi,MeshMatcapMaterial:ch,LineDashedMaterial:hh,LineBasicMaterial:ul,Material:ai}[t]}}class su{static decodeText(t){if(console.warn("THREE.LoaderUtils: decodeText() has been deprecated with r165 and will be removed with r175. Use TextDecoder instead."),"undefined"!=typeof TextDecoder)return(new TextDecoder).decode(t);let e="";for(let n=0,i=t.length;n0){this.source.connect(this.filters[0]);for(let t=1,e=this.filters.length;t0){this.source.disconnect(this.filters[0]);for(let t=1,e=this.filters.length;t0&&this._mixBufferRegionAdditive(n,i,this._addIndex*e,1,e);for(let t=e,r=e+e;t!==r;++t)if(n[t]!==n[t+e]){a.setValue(n,i);break}}saveOriginalState(){const t=this.binding,e=this.buffer,n=this.valueSize,i=n*this._origIndex;t.getValue(e,i);for(let t=n,r=i;t!==r;++t)e[t]=e[i+t%n];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0}restoreOriginalState(){const t=3*this.valueSize;this.binding.setValue(this.buffer,t)}_setAdditiveIdentityNumeric(){const t=this._addIndex*this.valueSize,e=t+this.valueSize;for(let n=t;n=.5)for(let i=0;i!==r;++i)t[e+i]=t[n+i]}_slerp(t,e,n,i){Ue.slerpFlat(t,e,t,e,t,n,i)}_slerpAdditive(t,e,n,i,r){const s=this._workIndex*r;Ue.multiplyQuaternionsFlat(t,s,t,e,t,n),Ue.slerpFlat(t,e,t,e,t,s,i)}_lerp(t,e,n,i,r){const s=1-i;for(let a=0;a!==r;++a){const r=e+a;t[r]=t[r]*s+t[n+a]*i}}_lerpAdditive(t,e,n,i,r){for(let s=0;s!==r;++s){const r=e+s;t[r]=t[r]+t[n+s]*i}}}const Ru="\\[\\]\\.:\\/",Cu=new RegExp("["+Ru+"]","g"),Pu="[^"+Ru+"]",Iu="[^"+Ru.replace("\\.","")+"]",Lu=new RegExp("^"+/((?:WC+[\/:])*)/.source.replace("WC",Pu)+/(WCOD+)?/.source.replace("WCOD",Iu)+/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",Pu)+/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",Pu)+"$"),Uu=["material","materials","bones","map"];class Du{constructor(t,e,n){this.path=e,this.parsedPath=n||Du.parseTrackName(e),this.node=Du.findNode(t,this.parsedPath.nodeName),this.rootNode=t,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(t,e,n){return t&&t.isAnimationObjectGroup?new Du.Composite(t,e,n):new Du(t,e,n)}static sanitizeNodeName(t){return t.replace(/\s/g,"_").replace(Cu,"")}static parseTrackName(t){const e=Lu.exec(t);if(null===e)throw new Error("PropertyBinding: Cannot parse trackName: "+t);const n={nodeName:e[2],objectName:e[3],objectIndex:e[4],propertyName:e[5],propertyIndex:e[6]},i=n.nodeName&&n.nodeName.lastIndexOf(".");if(void 0!==i&&-1!==i){const t=n.nodeName.substring(i+1);-1!==Uu.indexOf(t)&&(n.nodeName=n.nodeName.substring(0,i),n.objectName=t)}if(null===n.propertyName||0===n.propertyName.length)throw new Error("PropertyBinding: can not parse propertyName from trackName: "+t);return n}static findNode(t,e){if(void 0===e||""===e||"."===e||-1===e||e===t.name||e===t.uuid)return t;if(t.skeleton){const n=t.skeleton.getBoneByName(e);if(void 0!==n)return n}if(t.children){const n=function(t){for(let i=0;i0){const t=this._interpolants,e=this._propertyBindings;if(this.blendMode===It)for(let n=0,i=t.length;n!==i;++n)t[n].evaluate(s),e[n].accumulateAdditive(a);else for(let n=0,r=t.length;n!==r;++n)t[n].evaluate(s),e[n].accumulate(i,a)}}_updateWeight(t){let e=0;if(this.enabled){e=this.weight;const n=this._weightInterpolant;if(null!==n){const i=n.evaluate(t)[0];e*=i,t>n.parameterPositions[1]&&(this.stopFading(),0===i&&(this.enabled=!1))}}return this._effectiveWeight=e,e}_updateTimeScale(t){let e=0;if(!this.paused){e=this.timeScale;const n=this._timeScaleInterpolant;null!==n&&(e*=n.evaluate(t)[0],t>n.parameterPositions[1]&&(this.stopWarping(),0===e?this.paused=!0:this.timeScale=e))}return this._effectiveTimeScale=e,e}_updateTime(t){const e=this._clip.duration,n=this.loop;let i=this.time+t,r=this._loopCount;const s=2202===n;if(0===t)return-1===r?i:s&&1==(1&r)?e-i:i;if(2200===n){-1===r&&(this._loopCount=0,this._setEndings(!0,!0,!1));t:{if(i>=e)i=e;else{if(!(i<0)){this.time=i;break t}i=0}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this.time=i,this._mixer.dispatchEvent({type:"finished",action:this,direction:t<0?-1:1})}}else{if(-1===r&&(t>=0?(r=0,this._setEndings(!0,0===this.repetitions,s)):this._setEndings(0===this.repetitions,!0,s)),i>=e||i<0){const n=Math.floor(i/e);i-=e*n,r+=Math.abs(n);const a=this.repetitions-r;if(a<=0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,i=t>0?e:0,this.time=i,this._mixer.dispatchEvent({type:"finished",action:this,direction:t>0?1:-1});else{if(1===a){const e=t<0;this._setEndings(e,!e,s)}else this._setEndings(!1,!1,s);this._loopCount=r,this.time=i,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:n})}}else this.time=i;if(s&&1==(1&r))return e-i}return i}_setEndings(t,e,n){const i=this._interpolantSettings;n?(i.endingStart=Ct,i.endingEnd=Ct):(i.endingStart=t?this.zeroSlopeAtStart?Ct:Rt:Pt,i.endingEnd=e?this.zeroSlopeAtEnd?Ct:Rt:Pt)}_scheduleFading(t,e,n){const i=this._mixer,r=i.time;let s=this._weightInterpolant;null===s&&(s=i._lendControlInterpolant(),this._weightInterpolant=s);const a=s.parameterPositions,o=s.sampleValues;return a[0]=r,o[0]=e,a[1]=r+t,o[1]=n,this}}const Ou=new Float32Array(1);class Fu{constructor(t){this.value=t}clone(){return new Fu(void 0===this.value.clone?this.value:this.value.clone())}}let Bu=0;const zu=new un;function ku(t,e){return t.distance-e.distance}function Vu(t,e,n,i){let r=!0;if(t.layers.test(e.layers)&&!1===t.raycast(e,n)&&(r=!1),!0===r&&!0===i){const i=t.children;for(let t=0,r=i.length;t=0;--e)t[e].stop();return this}update(t){t*=this.timeScale;const e=this._actions,n=this._nActiveActions,i=this.time+=t,r=Math.sign(t),s=this._accuIndex^=1;for(let a=0;a!==n;++a)e[a]._update(i,t,r,s);const a=this._bindings,o=this._nActiveBindings;for(let t=0;t!==o;++t)a[t].apply(s);return this}setTime(t){this.time=0;for(let t=0;t=r){const s=r++,c=t[s];e[c.uuid]=l,t[l]=c,e[o]=s,t[s]=a;for(let t=0,e=i;t!==e;++t){const e=n[t],i=e[s],r=e[l];e[l]=i,e[s]=r}}}this.nCachedObjects_=r}uncache(){const t=this._objects,e=this._indicesByUUID,n=this._bindings,i=n.length;let r=this.nCachedObjects_,s=t.length;for(let a=0,o=arguments.length;a!==o;++a){const o=arguments[a].uuid,l=e[o];if(void 0!==l)if(delete e[o],l0&&(e[a.uuid]=l),t[l]=a,t.pop();for(let t=0,e=i;t!==e;++t){const e=n[t];e[l]=e[r],e.pop()}}}this.nCachedObjects_=r}subscribe_(t,e){const n=this._bindingsIndicesByPath;let i=n[t];const r=this._bindings;if(void 0!==i)return r[i];const s=this._paths,a=this._parsedPaths,o=this._objects,l=o.length,c=this.nCachedObjects_,h=new Array(l);i=r.length,n[t]=i,s.push(t),a.push(e),r.push(h);for(let n=c,i=o.length;n!==i;++n){const i=o[n];h[n]=new Du(i,t,e)}return h}unsubscribe_(t){const e=this._bindingsIndicesByPath,n=e[t];if(void 0!==n){const i=this._paths,r=this._parsedPaths,s=this._bindings,a=s.length-1,o=s[a];e[t[a]]=n,s[n]=o,s.pop(),r[n]=r[a],r.pop(),i[n]=i[a],i.pop()}}},e.AnimationUtils=gh,e.ArcCurve=Nl,e.ArrayCamera=ka,e.ArrowHelper=class extends Bn{constructor(t=new De(0,0,1),e=new De(0,0,0),n=1,i=16776960,r=.2*n,s=.2*r){super(),this.type="ArrowHelper",void 0===ld&&(ld=new Ei,ld.setAttribute("position",new _i([0,0,0,0,1,0],3)),cd=new rc(0,.5,1,5,1),cd.translate(0,-.5,0)),this.position.copy(e),this.line=new xl(ld,new ul({color:i,toneMapped:!1})),this.line.matrixAutoUpdate=!1,this.add(this.line),this.cone=new Bi(cd,new oi({color:i,toneMapped:!1})),this.cone.matrixAutoUpdate=!1,this.add(this.cone),this.setDirection(t),this.setLength(n,r,s)}setDirection(t){if(t.y>.99999)this.quaternion.set(0,0,0,1);else if(t.y<-.99999)this.quaternion.set(1,0,0,0);else{od.set(t.z,0,-t.x).normalize();const e=Math.acos(t.y);this.quaternion.setFromAxisAngle(od,e)}}setLength(t,e=.2*t,n=.2*e){this.line.scale.set(1,Math.max(1e-4,t-e),1),this.line.updateMatrix(),this.cone.scale.set(n,e,n),this.cone.position.y=t,this.cone.updateMatrix()}setColor(t){this.line.material.color.set(t),this.cone.material.color.set(t)}copy(t){return super.copy(t,!1),this.line.copy(t.line),this.cone.copy(t.cone),this}dispose(){this.line.geometry.dispose(),this.line.material.dispose(),this.cone.geometry.dispose(),this.cone.material.dispose()}},e.AttachedBindMode=a,e.Audio=Su,e.AudioAnalyser=class{constructor(t,e=2048){this.analyser=t.context.createAnalyser(),this.analyser.fftSize=e,this.data=new Uint8Array(this.analyser.frequencyBinCount),t.getOutput().connect(this.analyser)}getFrequencyData(){return this.analyser.getByteFrequencyData(this.data),this.data}getAverageFrequency(){let t=0;const e=this.getFrequencyData();for(let n=0;n=this.min.x&&t.x<=this.max.x&&t.y>=this.min.y&&t.y<=this.max.y}containsBox(t){return this.min.x<=t.min.x&&t.max.x<=this.max.x&&this.min.y<=t.min.y&&t.max.y<=this.max.y}getParameter(t,e){return e.set((t.x-this.min.x)/(this.max.x-this.min.x),(t.y-this.min.y)/(this.max.y-this.min.y))}intersectsBox(t){return t.max.x>=this.min.x&&t.min.x<=this.max.x&&t.max.y>=this.min.y&&t.min.y<=this.max.y}clampPoint(t,e){return e.copy(t).clamp(this.min,this.max)}distanceToPoint(t){return this.clampPoint(t,Gu).distanceTo(t)}intersect(t){return this.min.max(t.min),this.max.min(t.max),this.isEmpty()&&this.makeEmpty(),this}union(t){return this.min.min(t.min),this.max.max(t.max),this}translate(t){return this.min.add(t),this.max.add(t),this}equals(t){return t.min.equals(this.min)&&t.max.equals(this.max)}},e.Box3=Fe,e.Box3Helper=class extends bl{constructor(t,e=16776960){const n=new Uint16Array([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,4,1,5,2,6,3,7]),i=new Ei;i.setIndex(new fi(n,1)),i.setAttribute("position",new _i([1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1],3)),super(i,new ul({color:e,toneMapped:!1})),this.box=t,this.type="Box3Helper",this.geometry.computeBoundingSphere()}updateMatrixWorld(t){const e=this.box;e.isEmpty()||(e.getCenter(this.position),e.getSize(this.scale),this.scale.multiplyScalar(.5),super.updateMatrixWorld(t))}dispose(){this.geometry.dispose(),this.material.dispose()}},e.BoxGeometry=ki,e.BoxHelper=class extends bl{constructor(t,e=16776960){const n=new Uint16Array([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,4,1,5,2,6,3,7]),i=new Float32Array(24),r=new Ei;r.setIndex(new fi(n,1)),r.setAttribute("position",new fi(i,3)),super(r,new ul({color:e,toneMapped:!1})),this.object=t,this.type="BoxHelper",this.matrixAutoUpdate=!1,this.update()}update(t){if(void 0!==t&&console.warn("THREE.BoxHelper: .update() has no longer arguments."),void 0!==this.object&&ad.setFromObject(this.object),ad.isEmpty())return;const e=ad.min,n=ad.max,i=this.geometry.attributes.position,r=i.array;r[0]=n.x,r[1]=n.y,r[2]=n.z,r[3]=e.x,r[4]=n.y,r[5]=n.z,r[6]=e.x,r[7]=e.y,r[8]=n.z,r[9]=n.x,r[10]=e.y,r[11]=n.z,r[12]=n.x,r[13]=n.y,r[14]=e.z,r[15]=e.x,r[16]=n.y,r[17]=e.z,r[18]=e.x,r[19]=e.y,r[20]=e.z,r[21]=n.x,r[22]=e.y,r[23]=e.z,i.needsUpdate=!0,this.geometry.computeBoundingSphere()}setFromObject(t){return this.object=t,this.update(),this}copy(t,e){return super.copy(t,e),this.object=t.object,this}dispose(){this.geometry.dispose(),this.material.dispose()}},e.BufferAttribute=fi,e.BufferGeometry=Ei,e.BufferGeometryLoader=ou,e.ByteType=w,e.Cache=Ih,e.Camera=ji,e.CameraHelper=class extends bl{constructor(t){const e=new Ei,n=new ul({color:16777215,vertexColors:!0,toneMapped:!1}),i=[],r=[],s={};function a(t,e){o(t),o(e)}function o(t){i.push(0,0,0),r.push(0,0,0),void 0===s[t]&&(s[t]=[]),s[t].push(i.length/3-1)}a("n1","n2"),a("n2","n4"),a("n4","n3"),a("n3","n1"),a("f1","f2"),a("f2","f4"),a("f4","f3"),a("f3","f1"),a("n1","f1"),a("n2","f2"),a("n3","f3"),a("n4","f4"),a("p","n1"),a("p","n2"),a("p","n3"),a("p","n4"),a("u1","u2"),a("u2","u3"),a("u3","u1"),a("c","t"),a("p","c"),a("cn1","cn2"),a("cn3","cn4"),a("cf1","cf2"),a("cf3","cf4"),e.setAttribute("position",new _i(i,3)),e.setAttribute("color",new _i(r,3)),super(e,n),this.type="CameraHelper",this.camera=t,this.camera.updateProjectionMatrix&&this.camera.updateProjectionMatrix(),this.matrix=t.matrixWorld,this.matrixAutoUpdate=!1,this.pointMap=s,this.update();const l=new ii(16755200),c=new ii(16711680),h=new ii(43775),u=new ii(16777215),d=new ii(3355443);this.setColors(l,c,h,u,d)}setColors(t,e,n,i,r){const s=this.geometry.getAttribute("color");s.setXYZ(0,t.r,t.g,t.b),s.setXYZ(1,t.r,t.g,t.b),s.setXYZ(2,t.r,t.g,t.b),s.setXYZ(3,t.r,t.g,t.b),s.setXYZ(4,t.r,t.g,t.b),s.setXYZ(5,t.r,t.g,t.b),s.setXYZ(6,t.r,t.g,t.b),s.setXYZ(7,t.r,t.g,t.b),s.setXYZ(8,t.r,t.g,t.b),s.setXYZ(9,t.r,t.g,t.b),s.setXYZ(10,t.r,t.g,t.b),s.setXYZ(11,t.r,t.g,t.b),s.setXYZ(12,t.r,t.g,t.b),s.setXYZ(13,t.r,t.g,t.b),s.setXYZ(14,t.r,t.g,t.b),s.setXYZ(15,t.r,t.g,t.b),s.setXYZ(16,t.r,t.g,t.b),s.setXYZ(17,t.r,t.g,t.b),s.setXYZ(18,t.r,t.g,t.b),s.setXYZ(19,t.r,t.g,t.b),s.setXYZ(20,t.r,t.g,t.b),s.setXYZ(21,t.r,t.g,t.b),s.setXYZ(22,t.r,t.g,t.b),s.setXYZ(23,t.r,t.g,t.b),s.setXYZ(24,e.r,e.g,e.b),s.setXYZ(25,e.r,e.g,e.b),s.setXYZ(26,e.r,e.g,e.b),s.setXYZ(27,e.r,e.g,e.b),s.setXYZ(28,e.r,e.g,e.b),s.setXYZ(29,e.r,e.g,e.b),s.setXYZ(30,e.r,e.g,e.b),s.setXYZ(31,e.r,e.g,e.b),s.setXYZ(32,n.r,n.g,n.b),s.setXYZ(33,n.r,n.g,n.b),s.setXYZ(34,n.r,n.g,n.b),s.setXYZ(35,n.r,n.g,n.b),s.setXYZ(36,n.r,n.g,n.b),s.setXYZ(37,n.r,n.g,n.b),s.setXYZ(38,i.r,i.g,i.b),s.setXYZ(39,i.r,i.g,i.b),s.setXYZ(40,r.r,r.g,r.b),s.setXYZ(41,r.r,r.g,r.b),s.setXYZ(42,r.r,r.g,r.b),s.setXYZ(43,r.r,r.g,r.b),s.setXYZ(44,r.r,r.g,r.b),s.setXYZ(45,r.r,r.g,r.b),s.setXYZ(46,r.r,r.g,r.b),s.setXYZ(47,r.r,r.g,r.b),s.setXYZ(48,r.r,r.g,r.b),s.setXYZ(49,r.r,r.g,r.b),s.needsUpdate=!0}update(){const t=this.geometry,e=this.pointMap;rd.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse),sd("c",e,t,rd,0,0,-1),sd("t",e,t,rd,0,0,1),sd("n1",e,t,rd,-1,-1,-1),sd("n2",e,t,rd,1,-1,-1),sd("n3",e,t,rd,-1,1,-1),sd("n4",e,t,rd,1,1,-1),sd("f1",e,t,rd,-1,-1,1),sd("f2",e,t,rd,1,-1,1),sd("f3",e,t,rd,-1,1,1),sd("f4",e,t,rd,1,1,1),sd("u1",e,t,rd,.7,1.1,-1),sd("u2",e,t,rd,-.7,1.1,-1),sd("u3",e,t,rd,0,2,-1),sd("cf1",e,t,rd,-1,0,1),sd("cf2",e,t,rd,1,0,1),sd("cf3",e,t,rd,0,-1,1),sd("cf4",e,t,rd,0,1,1),sd("cn1",e,t,rd,-1,0,-1),sd("cn2",e,t,rd,1,0,-1),sd("cn3",e,t,rd,0,-1,-1),sd("cn4",e,t,rd,0,1,-1),t.getAttribute("position").needsUpdate=!0}dispose(){this.geometry.dispose(),this.material.dispose()}},e.CanvasTexture=class extends Ae{constructor(t,e,n,i,r,s,a,o,l){super(t,e,n,i,r,s,a,o,l),this.isCanvasTexture=!0,this.needsUpdate=!0}},e.CapsuleGeometry=nc,e.CatmullRomCurve3=Vl,e.CineonToneMapping=3,e.CircleGeometry=ic,e.ClampToEdgeWrapping=f,e.Clock=gu,e.Color=ii,e.ColorKeyframeTrack=bh,e.ColorManagement=_e,e.CompressedArrayTexture=class extends Ll{constructor(t,e,n,i,r,s){super(t,e,n,r,s),this.isCompressedArrayTexture=!0,this.image.depth=i,this.wrapR=f,this.layerUpdates=new Set}addLayerUpdate(t){this.layerUpdates.add(t)}clearLayerUpdates(){this.layerUpdates.clear()}},e.CompressedCubeTexture=class extends Ll{constructor(t,e,n){super(void 0,t[0].width,t[0].height,e,n,c),this.isCompressedCubeTexture=!0,this.isCubeTexture=!0,this.image=t}},e.CompressedTexture=Ll,e.CompressedTextureLoader=class extends Dh{constructor(t){super(t)}load(t,e,n,i){const r=this,s=[],a=new Ll,o=new Fh(this.manager);o.setPath(this.path),o.setResponseType("arraybuffer"),o.setRequestHeader(this.requestHeader),o.setWithCredentials(r.withCredentials);let l=0;function c(c){o.load(t[c],(function(t){const n=r.parse(t,!0);s[c]={width:n.width,height:n.height,format:n.format,mipmaps:n.mipmaps},l+=1,6===l&&(1===n.mipmapCount&&(a.minFilter=y),a.image=s,a.format=n.format,a.needsUpdate=!0,e&&e(a))}),n,i)}if(Array.isArray(t))for(let e=0,n=t.length;e{e&&e(n),r.manager.itemEnd(t)})).catch((t=>{i&&i(t)})):(setTimeout((function(){e&&e(s),r.manager.itemEnd(t)}),0),s);const a={};a.credentials="anonymous"===this.crossOrigin?"same-origin":"include",a.headers=this.requestHeader;const o=fetch(t,a).then((function(t){return t.blob()})).then((function(t){return createImageBitmap(t,Object.assign(r.options,{colorSpaceConversion:"none"}))})).then((function(n){return Ih.add(t,n),e&&e(n),r.manager.itemEnd(t),n})).catch((function(e){i&&i(e),Ih.remove(t),r.manager.itemError(t),r.manager.itemEnd(t)}));Ih.add(t,o),r.manager.itemStart(t)}},e.ImageLoader=Bh,e.ImageUtils=Se,e.IncrementStencilOp=7682,e.IncrementWrapStencilOp=34055,e.InstancedBufferAttribute=Fo,e.InstancedBufferGeometry=au,e.InstancedInterleavedBuffer=class extends Qa{constructor(t,e,n=1){super(t,e),this.isInstancedInterleavedBuffer=!0,this.meshPerAttribute=n}copy(t){return super.copy(t),this.meshPerAttribute=t.meshPerAttribute,this}clone(t){const e=super.clone(t);return e.meshPerAttribute=this.meshPerAttribute,e}toJSON(t){const e=super.toJSON(t);return e.isInstancedInterleavedBuffer=!0,e.meshPerAttribute=this.meshPerAttribute,e}},e.InstancedMesh=Xo,e.Int16BufferAttribute=class extends fi{constructor(t,e,n){super(new Int16Array(t),e,n)}},e.Int32BufferAttribute=class extends fi{constructor(t,e,n){super(new Int32Array(t),e,n)}},e.Int8BufferAttribute=class extends fi{constructor(t,e,n){super(new Int8Array(t),e,n)}},e.IntType=A,e.InterleavedBuffer=Qa,e.InterleavedBufferAttribute=eo,e.Interpolant=vh,e.InterpolateDiscrete=Tt,e.InterpolateLinear=Et,e.InterpolateSmooth=At,e.InvertStencilOp=5386,e.KeepStencilOp=Vt,e.KeyframeTrack=Mh,e.LOD=Mo,e.LatheGeometry=ec,e.Layers=Sn,e.LessCompare=513,e.LessDepth=2,e.LessEqualCompare=515,e.LessEqualDepth=3,e.LessEqualStencilFunc=515,e.LessStencilFunc=513,e.Light=zh,e.LightProbe=iu,e.Line=xl,e.Line3=class{constructor(t=new De,e=new De){this.start=t,this.end=e}set(t,e){return this.start.copy(t),this.end.copy(e),this}copy(t){return this.start.copy(t.start),this.end.copy(t.end),this}getCenter(t){return t.addVectors(this.start,this.end).multiplyScalar(.5)}delta(t){return t.subVectors(this.end,this.start)}distanceSq(){return this.start.distanceToSquared(this.end)}distance(){return this.start.distanceTo(this.end)}at(t,e){return this.delta(e).multiplyScalar(t).add(this.start)}closestPointToPointParameter(t,e){Wu.subVectors(t,this.start),Xu.subVectors(this.end,this.start);const n=Xu.dot(Xu);let i=Xu.dot(Wu)/n;return e&&(i=$t(i,0,1)),i}closestPointToPoint(t,e,n){const i=this.closestPointToPointParameter(t,e);return this.delta(n).multiplyScalar(i).add(this.start)}applyMatrix4(t){return this.start.applyMatrix4(t),this.end.applyMatrix4(t),this}equals(t){return t.start.equals(this.start)&&t.end.equals(this.end)}clone(){return(new this.constructor).copy(this)}},e.LineBasicMaterial=ul,e.LineCurve=ql,e.LineCurve3=Yl,e.LineDashedMaterial=hh,e.LineLoop=wl,e.LineSegments=bl,e.LinearDisplayP3ColorSpace=Ot,e.LinearFilter=y,e.LinearInterpolant=xh,e.LinearMipMapLinearFilter=1008,e.LinearMipMapNearestFilter=1007,e.LinearMipmapLinearFilter=S,e.LinearMipmapNearestFilter=M,e.LinearSRGBColorSpace=Dt,e.LinearToneMapping=1,e.LinearTransfer=Ft,e.Loader=Dh,e.LoaderUtils=su,e.LoadingManager=Lh,e.LoopOnce=2200,e.LoopPingPong=2202,e.LoopRepeat=2201,e.LuminanceAlphaFormat=z,e.LuminanceFormat=B,e.MOUSE={LEFT:0,MIDDLE:1,RIGHT:2,ROTATE:0,DOLLY:1,PAN:2},e.Material=ai,e.MaterialLoader=ru,e.MathUtils=ie,e.Matrix2=Hu,e.Matrix3=se,e.Matrix4=un,e.MaxEquation=104,e.Mesh=Bi,e.MeshBasicMaterial=oi,e.MeshDepthMaterial=Ia,e.MeshDistanceMaterial=La,e.MeshLambertMaterial=lh,e.MeshMatcapMaterial=ch,e.MeshNormalMaterial=oh,e.MeshPhongMaterial=sh,e.MeshPhysicalMaterial=rh,e.MeshStandardMaterial=ih,e.MeshToonMaterial=ah,e.MinEquation=103,e.MirroredRepeatWrapping=g,e.MixOperation=1,e.MultiplyBlending=4,e.MultiplyOperation=0,e.NearestFilter=v,e.NearestMipMapLinearFilter=1005,e.NearestMipMapNearestFilter=1004,e.NearestMipmapLinearFilter=x,e.NearestMipmapNearestFilter=_,e.NeutralToneMapping=7,e.NeverCompare=512,e.NeverDepth=0,e.NeverStencilFunc=512,e.NoBlending=0,e.NoColorSpace=Lt,e.NoToneMapping=0,e.NormalAnimationBlendMode=2500,e.NormalBlending=1,e.NotEqualCompare=517,e.NotEqualDepth=7,e.NotEqualStencilFunc=517,e.NumberKeyframeTrack=wh,e.Object3D=Bn,e.ObjectLoader=class extends Dh{constructor(t){super(t)}load(t,e,n,i){const r=this,s=""===this.path?su.extractUrlBase(t):this.path;this.resourcePath=this.resourcePath||s;const a=new Fh(this.manager);a.setPath(this.path),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials),a.load(t,(function(n){let s=null;try{s=JSON.parse(n)}catch(e){return void 0!==i&&i(e),void console.error("THREE:ObjectLoader: Can't parse "+t+".",e.message)}const a=s.metadata;if(void 0===a||void 0===a.type||"geometry"===a.type.toLowerCase())return void 0!==i&&i(new Error("THREE.ObjectLoader: Can't load "+t)),void console.error("THREE.ObjectLoader: Can't load "+t);r.parse(s,e)}),n,i)}async loadAsync(t,e){const n=""===this.path?su.extractUrlBase(t):this.path;this.resourcePath=this.resourcePath||n;const i=new Fh(this.manager);i.setPath(this.path),i.setRequestHeader(this.requestHeader),i.setWithCredentials(this.withCredentials);const r=await i.loadAsync(t,e),s=JSON.parse(r),a=s.metadata;if(void 0===a||void 0===a.type||"geometry"===a.type.toLowerCase())throw new Error("THREE.ObjectLoader: Can't load "+t);return await this.parseAsync(s)}parse(t,e){const n=this.parseAnimations(t.animations),i=this.parseShapes(t.shapes),r=this.parseGeometries(t.geometries,i),s=this.parseImages(t.images,(function(){void 0!==e&&e(l)})),a=this.parseTextures(t.textures,s),o=this.parseMaterials(t.materials,a),l=this.parseObject(t.object,r,o,a,n),c=this.parseSkeletons(t.skeletons,l);if(this.bindSkeletons(l,c),this.bindLightTargets(l),void 0!==e){let t=!1;for(const e in s)if(s[e].data instanceof HTMLImageElement){t=!0;break}!1===t&&e(l)}return l}async parseAsync(t){const e=this.parseAnimations(t.animations),n=this.parseShapes(t.shapes),i=this.parseGeometries(t.geometries,n),r=await this.parseImagesAsync(t.images),s=this.parseTextures(t.textures,r),a=this.parseMaterials(t.materials,s),o=this.parseObject(t.object,i,a,s,e),l=this.parseSkeletons(t.skeletons,o);return this.bindSkeletons(o,l),this.bindLightTargets(o),o}parseShapes(t){const e={};if(void 0!==t)for(let n=0,i=t.length;n0){const n=new Lh(e);r=new Bh(n),r.setCrossOrigin(this.crossOrigin);for(let e=0,n=t.length;e0){i=new Bh(this.manager),i.setCrossOrigin(this.crossOrigin);for(let e=0,i=t.length;e{const e=new Fe;e.min.fromArray(t.boxMin),e.max.fromArray(t.boxMax);const n=new en;return n.radius=t.sphereRadius,n.center.fromArray(t.sphereCenter),{boxInitialized:t.boxInitialized,box:e,sphereInitialized:t.sphereInitialized,sphere:n}})),s._maxInstanceCount=t.maxInstanceCount,s._maxVertexCount=t.maxVertexCount,s._maxIndexCount=t.maxIndexCount,s._geometryInitialized=t.geometryInitialized,s._geometryCount=t.geometryCount,s._matricesTexture=h(t.matricesTexture.uuid),void 0!==t.colorsTexture&&(s._colorsTexture=h(t.colorsTexture.uuid));break;case"LOD":s=new Mo;break;case"Line":s=new xl(l(t.geometry),c(t.material));break;case"LineLoop":s=new wl(l(t.geometry),c(t.material));break;case"LineSegments":s=new bl(l(t.geometry),c(t.material));break;case"PointCloud":case"Points":s=new Pl(l(t.geometry),c(t.material));break;case"Sprite":s=new vo(c(t.material));break;case"Group":s=new Va;break;case"Bone":s=new Lo;break;default:s=new Bn}if(s.uuid=t.uuid,void 0!==t.name&&(s.name=t.name),void 0!==t.matrix?(s.matrix.fromArray(t.matrix),void 0!==t.matrixAutoUpdate&&(s.matrixAutoUpdate=t.matrixAutoUpdate),s.matrixAutoUpdate&&s.matrix.decompose(s.position,s.quaternion,s.scale)):(void 0!==t.position&&s.position.fromArray(t.position),void 0!==t.rotation&&s.rotation.fromArray(t.rotation),void 0!==t.quaternion&&s.quaternion.fromArray(t.quaternion),void 0!==t.scale&&s.scale.fromArray(t.scale)),void 0!==t.up&&s.up.fromArray(t.up),void 0!==t.castShadow&&(s.castShadow=t.castShadow),void 0!==t.receiveShadow&&(s.receiveShadow=t.receiveShadow),t.shadow&&(void 0!==t.shadow.intensity&&(s.shadow.intensity=t.shadow.intensity),void 0!==t.shadow.bias&&(s.shadow.bias=t.shadow.bias),void 0!==t.shadow.normalBias&&(s.shadow.normalBias=t.shadow.normalBias),void 0!==t.shadow.radius&&(s.shadow.radius=t.shadow.radius),void 0!==t.shadow.mapSize&&s.shadow.mapSize.fromArray(t.shadow.mapSize),void 0!==t.shadow.camera&&(s.shadow.camera=this.parseObject(t.shadow.camera))),void 0!==t.visible&&(s.visible=t.visible),void 0!==t.frustumCulled&&(s.frustumCulled=t.frustumCulled),void 0!==t.renderOrder&&(s.renderOrder=t.renderOrder),void 0!==t.userData&&(s.userData=t.userData),void 0!==t.layers&&(s.layers.mask=t.layers),void 0!==t.children){const a=t.children;for(let t=0;t1)for(let n=0;nNumber.EPSILON){if(l<0&&(n=e[s],o=-o,a=e[r],l=-l),t.ya.y)continue;if(t.y===n.y){if(t.x===n.x)return!0}else{const e=l*(t.x-n.x)-o*(t.y-n.y);if(0===e)return!0;if(e<0)continue;i=!i}}else{if(t.y!==n.y)continue;if(a.x<=t.x&&t.x<=n.x||n.x<=t.x&&t.x<=a.x)return!0}}return i}const n=Bc.isClockWise,i=this.subPaths;if(0===i.length)return[];let r,s,a;const o=[];if(1===i.length)return s=i[0],a=new pc,a.curves=s.curves,o.push(a),o;let l=!n(i[0].getPoints());l=t?!l:l;const c=[],h=[];let u,d,p=[],m=0;h[m]=void 0,p[m]=[];for(let e=0,a=i.length;e1){let t=!1,n=0;for(let t=0,e=h.length;t0&&!1===t&&(p=c)}for(let t=0,e=h.length;t=t.HAVE_CURRENT_DATA&&(this.needsUpdate=!0)}},e.WebGL3DRenderTarget=class extends Pe{constructor(t=1,e=1,n=1,i={}){super(t,e,i),this.isWebGL3DRenderTarget=!0,this.depth=n,this.texture=new Le(null,t,e,n),this.texture.isRenderTargetTexture=!0}},e.WebGLArrayRenderTarget=class extends Pe{constructor(t=1,e=1,n=1,i={}){super(t,e,i),this.isWebGLArrayRenderTarget=!0,this.depth=n,this.texture=new Ie(null,t,e,n),this.texture.isRenderTargetTexture=!0}},e.WebGLCoordinateSystem=Wt,e.WebGLCubeRenderTarget=tr,e.WebGLMultipleRenderTargets=class extends Pe{constructor(t=1,e=1,n=1,i={}){console.warn('THREE.WebGLMultipleRenderTargets has been deprecated and will be removed in r172. Use THREE.WebGLRenderTarget and set the "count" parameter to enable MRT.'),super(t,e,{...i,count:n}),this.isWebGLMultipleRenderTargets=!0}get texture(){return this.textures}},e.WebGLRenderTarget=Pe,e.WebGLRenderer=class{constructor(t={}){const{canvas:e=ue(),context:i=null,depth:r=!0,stencil:s=!1,alpha:a=!1,antialias:o=!1,premultipliedAlpha:l=!0,preserveDrawingBuffer:c=!1,powerPreference:h="default",failIfMajorPerformanceCaveat:u=!1}=t;let d;if(this.isWebGLRenderer=!0,null!==i){if("undefined"!=typeof WebGLRenderingContext&&i instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");d=i.getContextAttributes().alpha}else d=a;const p=new Uint32Array(4),m=new Int32Array(4);let f=null,g=null;const v=[],_=[];this.domElement=e,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this._outputColorSpace=Ut,this.toneMapping=0,this.toneMappingExposure=1;const x=this;let y=!1,M=0,w=0,T=null,A=-1,C=null;const D=new Re,N=new Re;let O=null;const F=new ii(0);let B=0,z=e.width,k=e.height,V=1,H=null,W=null;const q=new Re(0,0,z,k),Y=new Re(0,0,z,k);let Z=!1;const J=new or;let K=!1,$=!1;const Q=new un,tt=new un,et=new De,nt=new Re,it={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let rt=!1;function st(){return null===T?V:1}let at,ot,lt,ct,ht,ut,dt,pt,mt,ft,gt,vt,_t,xt,yt,Mt,St,bt,wt,Tt,Et,At,Rt,Ct,Pt=i;function It(t,n){return e.getContext(t,n)}try{const t={alpha:!0,depth:r,stencil:s,antialias:o,premultipliedAlpha:l,preserveDrawingBuffer:c,powerPreference:h,failIfMajorPerformanceCaveat:u};if("setAttribute"in e&&e.setAttribute("data-engine",`three.js r${n}`),e.addEventListener("webglcontextlost",Ot,!1),e.addEventListener("webglcontextrestored",Ft,!1),e.addEventListener("webglcontextcreationerror",Bt,!1),null===Pt){const e="webgl2";if(Pt=It(e,t),null===Pt)throw It(e)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}}catch(t){throw console.error("THREE.WebGLRenderer: "+t.message),t}function Lt(){at=new kr(Pt),at.init(),At=new za(Pt,at),ot=new yr(Pt,at,t,At),lt=new Na(Pt),ot.reverseDepthBuffer&<.buffers.depth.setReversed(!0),ct=new Gr(Pt),ht=new ya,ut=new Ba(Pt,at,lt,ht,ot,At,ct),dt=new Sr(x),pt=new zr(x),mt=new cr(Pt),Rt=new _r(Pt,mt),ft=new Vr(Pt,mt,ct,Rt),gt=new Xr(Pt,ft,mt,ct),wt=new Wr(Pt,ot,ut),Mt=new Mr(ht),vt=new xa(x,dt,pt,at,ot,Rt,Mt),_t=new Ya(x,ht),xt=new wa,yt=new Pa(at),bt=new vr(x,dt,pt,lt,gt,d,l),St=new Ua(x,gt,ot),Ct=new Za(Pt,ct,ot,lt),Tt=new xr(Pt,at,ct),Et=new Hr(Pt,at,ct),ct.programs=vt.programs,x.capabilities=ot,x.extensions=at,x.properties=ht,x.renderLists=xt,x.shadowMap=St,x.state=lt,x.info=ct}Lt();const Nt=new Xa(x,Pt);function Ot(t){t.preventDefault(),console.log("THREE.WebGLRenderer: Context Lost."),y=!0}function Ft(){console.log("THREE.WebGLRenderer: Context Restored."),y=!1;const t=ct.autoReset,e=St.enabled,n=St.autoUpdate,i=St.needsUpdate,r=St.type;Lt(),ct.autoReset=t,St.enabled=e,St.autoUpdate=n,St.needsUpdate=i,St.type=r}function Bt(t){console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ",t.statusMessage)}function zt(t){const e=t.target;e.removeEventListener("dispose",zt),function(t){(function(t){const e=ht.get(t).programs;void 0!==e&&(e.forEach((function(t){vt.releaseProgram(t)})),t.isShaderMaterial&&vt.releaseShaderCache(t))})(t),ht.remove(t)}(e)}function kt(t,e,n){!0===t.transparent&&2===t.side&&!1===t.forceSinglePass?(t.side=1,t.needsUpdate=!0,Jt(t,e,n),t.side=0,t.needsUpdate=!0,Jt(t,e,n),t.side=2):Jt(t,e,n)}this.xr=Nt,this.getContext=function(){return Pt},this.getContextAttributes=function(){return Pt.getContextAttributes()},this.forceContextLoss=function(){const t=at.get("WEBGL_lose_context");t&&t.loseContext()},this.forceContextRestore=function(){const t=at.get("WEBGL_lose_context");t&&t.restoreContext()},this.getPixelRatio=function(){return V},this.setPixelRatio=function(t){void 0!==t&&(V=t,this.setSize(z,k,!1))},this.getSize=function(t){return t.set(z,k)},this.setSize=function(t,n,i=!0){Nt.isPresenting?console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting."):(z=t,k=n,e.width=Math.floor(t*V),e.height=Math.floor(n*V),!0===i&&(e.style.width=t+"px",e.style.height=n+"px"),this.setViewport(0,0,t,n))},this.getDrawingBufferSize=function(t){return t.set(z*V,k*V).floor()},this.setDrawingBufferSize=function(t,n,i){z=t,k=n,V=i,e.width=Math.floor(t*i),e.height=Math.floor(n*i),this.setViewport(0,0,t,n)},this.getCurrentViewport=function(t){return t.copy(D)},this.getViewport=function(t){return t.copy(q)},this.setViewport=function(t,e,n,i){t.isVector4?q.set(t.x,t.y,t.z,t.w):q.set(t,e,n,i),lt.viewport(D.copy(q).multiplyScalar(V).round())},this.getScissor=function(t){return t.copy(Y)},this.setScissor=function(t,e,n,i){t.isVector4?Y.set(t.x,t.y,t.z,t.w):Y.set(t,e,n,i),lt.scissor(N.copy(Y).multiplyScalar(V).round())},this.getScissorTest=function(){return Z},this.setScissorTest=function(t){lt.setScissorTest(Z=t)},this.setOpaqueSort=function(t){H=t},this.setTransparentSort=function(t){W=t},this.getClearColor=function(t){return t.copy(bt.getClearColor())},this.setClearColor=function(){bt.setClearColor.apply(bt,arguments)},this.getClearAlpha=function(){return bt.getClearAlpha()},this.setClearAlpha=function(){bt.setClearAlpha.apply(bt,arguments)},this.clear=function(t=!0,e=!0,n=!0){let i=0;if(t){let t=!1;if(null!==T){const e=T.texture.format;t=e===j||e===X||e===G}if(t){const t=T.texture.type,e=t===b||t===R||t===E||t===U||t===I||t===L,n=bt.getClearColor(),i=bt.getClearAlpha(),r=n.r,s=n.g,a=n.b;e?(p[0]=r,p[1]=s,p[2]=a,p[3]=i,Pt.clearBufferuiv(Pt.COLOR,0,p)):(m[0]=r,m[1]=s,m[2]=a,m[3]=i,Pt.clearBufferiv(Pt.COLOR,0,m))}else i|=Pt.COLOR_BUFFER_BIT}e&&(i|=Pt.DEPTH_BUFFER_BIT,Pt.clearDepth(this.capabilities.reverseDepthBuffer?0:1)),n&&(i|=Pt.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),Pt.clear(i)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.dispose=function(){e.removeEventListener("webglcontextlost",Ot,!1),e.removeEventListener("webglcontextrestored",Ft,!1),e.removeEventListener("webglcontextcreationerror",Bt,!1),xt.dispose(),yt.dispose(),ht.dispose(),dt.dispose(),pt.dispose(),gt.dispose(),Rt.dispose(),Ct.dispose(),vt.dispose(),Nt.dispose(),Nt.removeEventListener("sessionstart",Ht),Nt.removeEventListener("sessionend",Gt),Wt.stop()},this.renderBufferDirect=function(t,e,n,i,r,s){null===e&&(e=it);const a=r.isMesh&&r.matrixWorld.determinant()<0,o=function(t,e,n,i,r){!0!==e.isScene&&(e=it),ut.resetTextureUnits();const s=e.fog,a=i.isMeshStandardMaterial?e.environment:null,o=null===T?x.outputColorSpace:!0===T.isXRRenderTarget?T.texture.colorSpace:Dt,l=(i.isMeshStandardMaterial?pt:dt).get(i.envMap||a),c=!0===i.vertexColors&&!!n.attributes.color&&4===n.attributes.color.itemSize,h=!!n.attributes.tangent&&(!!i.normalMap||i.anisotropy>0),u=!!n.morphAttributes.position,d=!!n.morphAttributes.normal,p=!!n.morphAttributes.color;let m=0;i.toneMapped&&(null!==T&&!0!==T.isXRRenderTarget||(m=x.toneMapping));const f=n.morphAttributes.position||n.morphAttributes.normal||n.morphAttributes.color,v=void 0!==f?f.length:0,_=ht.get(i),y=g.state.lights;if(!0===K&&(!0===$||t!==C)){const e=t===C&&i.id===A;Mt.setState(i,t,e)}let M=!1;i.version===_.__version?_.needsLights&&_.lightsStateVersion!==y.state.version||_.outputColorSpace!==o||r.isBatchedMesh&&!1===_.batching?M=!0:r.isBatchedMesh||!0!==_.batching?r.isBatchedMesh&&!0===_.batchingColor&&null===r.colorTexture||r.isBatchedMesh&&!1===_.batchingColor&&null!==r.colorTexture||r.isInstancedMesh&&!1===_.instancing?M=!0:r.isInstancedMesh||!0!==_.instancing?r.isSkinnedMesh&&!1===_.skinning?M=!0:r.isSkinnedMesh||!0!==_.skinning?r.isInstancedMesh&&!0===_.instancingColor&&null===r.instanceColor||r.isInstancedMesh&&!1===_.instancingColor&&null!==r.instanceColor||r.isInstancedMesh&&!0===_.instancingMorph&&null===r.morphTexture||r.isInstancedMesh&&!1===_.instancingMorph&&null!==r.morphTexture||_.envMap!==l||!0===i.fog&&_.fog!==s?M=!0:void 0===_.numClippingPlanes||_.numClippingPlanes===Mt.numPlanes&&_.numIntersection===Mt.numIntersection?(_.vertexAlphas!==c||_.vertexTangents!==h||_.morphTargets!==u||_.morphNormals!==d||_.morphColors!==p||_.toneMapping!==m||_.morphTargetsCount!==v)&&(M=!0):M=!0:M=!0:M=!0:M=!0:(M=!0,_.__version=i.version);let S=_.currentProgram;!0===M&&(S=Jt(i,e,r));let b=!1,w=!1,E=!1;const R=S.getUniforms(),P=_.uniforms;if(lt.useProgram(S.program)&&(b=!0,w=!0,E=!0),i.id!==A&&(A=i.id,w=!0),b||C!==t){ot.reverseDepthBuffer?(Q.copy(t.projectionMatrix),function(t){const e=t.elements;e[2]=.5*e[2]+.5*e[3],e[6]=.5*e[6]+.5*e[7],e[10]=.5*e[10]+.5*e[11],e[14]=.5*e[14]+.5*e[15]}(Q),function(t){const e=t.elements;-1===e[11]?(e[10]=-e[10]-1,e[14]=-e[14]):(e[10]=-e[10],e[14]=1-e[14])}(Q),R.setValue(Pt,"projectionMatrix",Q)):R.setValue(Pt,"projectionMatrix",t.projectionMatrix),R.setValue(Pt,"viewMatrix",t.matrixWorldInverse);const e=R.map.cameraPosition;void 0!==e&&e.setValue(Pt,et.setFromMatrixPosition(t.matrixWorld)),ot.logarithmicDepthBuffer&&R.setValue(Pt,"logDepthBufFC",2/(Math.log(t.far+1)/Math.LN2)),(i.isMeshPhongMaterial||i.isMeshToonMaterial||i.isMeshLambertMaterial||i.isMeshBasicMaterial||i.isMeshStandardMaterial||i.isShaderMaterial)&&R.setValue(Pt,"isOrthographic",!0===t.isOrthographicCamera),C!==t&&(C=t,w=!0,E=!0)}if(r.isSkinnedMesh){R.setOptional(Pt,r,"bindMatrix"),R.setOptional(Pt,r,"bindMatrixInverse");const t=r.skeleton;t&&(null===t.boneTexture&&t.computeBoneTexture(),R.setValue(Pt,"boneTexture",t.boneTexture,ut))}r.isBatchedMesh&&(R.setOptional(Pt,r,"batchingTexture"),R.setValue(Pt,"batchingTexture",r._matricesTexture,ut),R.setOptional(Pt,r,"batchingIdTexture"),R.setValue(Pt,"batchingIdTexture",r._indirectTexture,ut),R.setOptional(Pt,r,"batchingColorTexture"),null!==r._colorsTexture&&R.setValue(Pt,"batchingColorTexture",r._colorsTexture,ut));const I=n.morphAttributes;var L,U;if(void 0===I.position&&void 0===I.normal&&void 0===I.color||wt.update(r,n,S),(w||_.receiveShadow!==r.receiveShadow)&&(_.receiveShadow=r.receiveShadow,R.setValue(Pt,"receiveShadow",r.receiveShadow)),i.isMeshGouraudMaterial&&null!==i.envMap&&(P.envMap.value=l,P.flipEnvMap.value=l.isCubeTexture&&!1===l.isRenderTargetTexture?-1:1),i.isMeshStandardMaterial&&null===i.envMap&&null!==e.environment&&(P.envMapIntensity.value=e.environmentIntensity),w&&(R.setValue(Pt,"toneMappingExposure",x.toneMappingExposure),_.needsLights&&(U=E,(L=P).ambientLightColor.needsUpdate=U,L.lightProbe.needsUpdate=U,L.directionalLights.needsUpdate=U,L.directionalLightShadows.needsUpdate=U,L.pointLights.needsUpdate=U,L.pointLightShadows.needsUpdate=U,L.spotLights.needsUpdate=U,L.spotLightShadows.needsUpdate=U,L.rectAreaLights.needsUpdate=U,L.hemisphereLights.needsUpdate=U),s&&!0===i.fog&&_t.refreshFogUniforms(P,s),_t.refreshMaterialUniforms(P,i,V,k,g.state.transmissionRenderTarget[t.id]),Ks.upload(Pt,Kt(_),P,ut)),i.isShaderMaterial&&!0===i.uniformsNeedUpdate&&(Ks.upload(Pt,Kt(_),P,ut),i.uniformsNeedUpdate=!1),i.isSpriteMaterial&&R.setValue(Pt,"center",r.center),R.setValue(Pt,"modelViewMatrix",r.modelViewMatrix),R.setValue(Pt,"normalMatrix",r.normalMatrix),R.setValue(Pt,"modelMatrix",r.matrixWorld),i.isShaderMaterial||i.isRawShaderMaterial){const t=i.uniformsGroups;for(let e=0,n=t.length;e{function n(){i.forEach((function(t){ht.get(t).currentProgram.isReady()&&i.delete(t)})),0!==i.size?setTimeout(n,10):e(t)}null!==at.get("KHR_parallel_shader_compile")?n():setTimeout(n,10)}))};let Vt=null;function Ht(){Wt.stop()}function Gt(){Wt.start()}const Wt=new lr;function Xt(t,e,n,i){if(!1===t.visible)return;if(t.layers.test(e.layers))if(t.isGroup)n=t.renderOrder;else if(t.isLOD)!0===t.autoUpdate&&t.update(e);else if(t.isLight)g.pushLight(t),t.castShadow&&g.pushShadow(t);else if(t.isSprite){if(!t.frustumCulled||J.intersectsSprite(t)){i&&nt.setFromMatrixPosition(t.matrixWorld).applyMatrix4(tt);const e=gt.update(t),r=t.material;r.visible&&f.push(t,e,r,n,nt.z,null)}}else if((t.isMesh||t.isLine||t.isPoints)&&(!t.frustumCulled||J.intersectsObject(t))){const e=gt.update(t),r=t.material;if(i&&(void 0!==t.boundingSphere?(null===t.boundingSphere&&t.computeBoundingSphere(),nt.copy(t.boundingSphere.center)):(null===e.boundingSphere&&e.computeBoundingSphere(),nt.copy(e.boundingSphere.center)),nt.applyMatrix4(t.matrixWorld).applyMatrix4(tt)),Array.isArray(r)){const i=e.groups;for(let s=0,a=i.length;s0&&Yt(r,e,n),s.length>0&&Yt(s,e,n),a.length>0&&Yt(a,e,n),lt.buffers.depth.setTest(!0),lt.buffers.depth.setMask(!0),lt.buffers.color.setMask(!0),lt.setPolygonOffset(!1)}function qt(t,e,n,i){if(null!==(!0===n.isScene?n.overrideMaterial:null))return;void 0===g.state.transmissionRenderTarget[i.id]&&(g.state.transmissionRenderTarget[i.id]=new Pe(1,1,{generateMipmaps:!0,type:at.has("EXT_color_buffer_half_float")||at.has("EXT_color_buffer_float")?P:b,minFilter:S,samples:4,stencilBuffer:s,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:_e.workingColorSpace}));const r=g.state.transmissionRenderTarget[i.id],a=i.viewport||D;r.setSize(a.z,a.w);const o=x.getRenderTarget();x.setRenderTarget(r),x.getClearColor(F),B=x.getClearAlpha(),B<1&&x.setClearColor(16777215,.5),x.clear(),rt&&bt.render(n);const l=x.toneMapping;x.toneMapping=0;const c=i.viewport;if(void 0!==i.viewport&&(i.viewport=void 0),g.setupLightsView(i),!0===K&&Mt.setGlobalState(x.clippingPlanes,i),Yt(t,n,i),ut.updateMultisampleRenderTarget(r),ut.updateRenderTargetMipmap(r),!1===at.has("WEBGL_multisampled_render_to_texture")){let t=!1;for(let r=0,s=e.length;r0)for(let e=0,s=n.length;e0&&qt(i,r,t,e),rt&&bt.render(t),jt(f,t,e);null!==T&&(ut.updateMultisampleRenderTarget(T),ut.updateRenderTargetMipmap(T)),!0===t.isScene&&t.onAfterRender(x,t,e),Rt.resetDefaultState(),A=-1,C=null,_.pop(),_.length>0?(g=_[_.length-1],!0===K&&Mt.setGlobalState(x.clippingPlanes,g.state.camera)):g=null,v.pop(),f=v.length>0?v[v.length-1]:null},this.getActiveCubeFace=function(){return M},this.getActiveMipmapLevel=function(){return w},this.getRenderTarget=function(){return T},this.setRenderTargetTextures=function(t,e,n){ht.get(t.texture).__webglTexture=e,ht.get(t.depthTexture).__webglTexture=n;const i=ht.get(t);i.__hasExternalTextures=!0,i.__autoAllocateDepthBuffer=void 0===n,i.__autoAllocateDepthBuffer||!0===at.has("WEBGL_multisampled_render_to_texture")&&(console.warn("THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided"),i.__useRenderToTexture=!1)},this.setRenderTargetFramebuffer=function(t,e){const n=ht.get(t);n.__webglFramebuffer=e,n.__useDefaultFramebuffer=void 0===e},this.setRenderTarget=function(t,e=0,n=0){T=t,M=e,w=n;let i=!0,r=null,s=!1,a=!1;if(t){const o=ht.get(t);if(void 0!==o.__useDefaultFramebuffer)lt.bindFramebuffer(Pt.FRAMEBUFFER,null),i=!1;else if(void 0===o.__webglFramebuffer)ut.setupRenderTarget(t);else if(o.__hasExternalTextures)ut.rebindTextures(t,ht.get(t.texture).__webglTexture,ht.get(t.depthTexture).__webglTexture);else if(t.depthBuffer){const e=t.depthTexture;if(o.__boundDepthTexture!==e){if(null!==e&&ht.has(e)&&(t.width!==e.image.width||t.height!==e.image.height))throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.");ut.setupDepthRenderbuffer(t)}}const l=t.texture;(l.isData3DTexture||l.isDataArrayTexture||l.isCompressedArrayTexture)&&(a=!0);const c=ht.get(t).__webglFramebuffer;t.isWebGLCubeRenderTarget?(r=Array.isArray(c[e])?c[e][n]:c[e],s=!0):r=t.samples>0&&!1===ut.useMultisampledRTT(t)?ht.get(t).__webglMultisampledFramebuffer:Array.isArray(c)?c[n]:c,D.copy(t.viewport),N.copy(t.scissor),O=t.scissorTest}else D.copy(q).multiplyScalar(V).floor(),N.copy(Y).multiplyScalar(V).floor(),O=Z;if(lt.bindFramebuffer(Pt.FRAMEBUFFER,r)&&i&<.drawBuffers(t,r),lt.viewport(D),lt.scissor(N),lt.setScissorTest(O),s){const i=ht.get(t.texture);Pt.framebufferTexture2D(Pt.FRAMEBUFFER,Pt.COLOR_ATTACHMENT0,Pt.TEXTURE_CUBE_MAP_POSITIVE_X+e,i.__webglTexture,n)}else if(a){const i=ht.get(t.texture),r=e||0;Pt.framebufferTextureLayer(Pt.FRAMEBUFFER,Pt.COLOR_ATTACHMENT0,i.__webglTexture,n||0,r)}A=-1},this.readRenderTargetPixels=function(t,e,n,i,r,s,a){if(!t||!t.isWebGLRenderTarget)return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let o=ht.get(t).__webglFramebuffer;if(t.isWebGLCubeRenderTarget&&void 0!==a&&(o=o[a]),o){lt.bindFramebuffer(Pt.FRAMEBUFFER,o);try{const a=t.texture,o=a.format,l=a.type;if(!ot.textureFormatReadable(o))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");if(!ot.textureTypeReadable(l))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");e>=0&&e<=t.width-i&&n>=0&&n<=t.height-r&&Pt.readPixels(e,n,i,r,At.convert(o),At.convert(l),s)}finally{const t=null!==T?ht.get(T).__webglFramebuffer:null;lt.bindFramebuffer(Pt.FRAMEBUFFER,t)}}},this.readRenderTargetPixelsAsync=async function(t,e,n,i,r,s,a){if(!t||!t.isWebGLRenderTarget)throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let o=ht.get(t).__webglFramebuffer;if(t.isWebGLCubeRenderTarget&&void 0!==a&&(o=o[a]),o){const a=t.texture,l=a.format,c=a.type;if(!ot.textureFormatReadable(l))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!ot.textureTypeReadable(c))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");if(e>=0&&e<=t.width-i&&n>=0&&n<=t.height-r){lt.bindFramebuffer(Pt.FRAMEBUFFER,o);const t=Pt.createBuffer();Pt.bindBuffer(Pt.PIXEL_PACK_BUFFER,t),Pt.bufferData(Pt.PIXEL_PACK_BUFFER,s.byteLength,Pt.STREAM_READ),Pt.readPixels(e,n,i,r,At.convert(l),At.convert(c),0);const a=null!==T?ht.get(T).__webglFramebuffer:null;lt.bindFramebuffer(Pt.FRAMEBUFFER,a);const h=Pt.fenceSync(Pt.SYNC_GPU_COMMANDS_COMPLETE,0);return Pt.flush(),await function(t,e,n){return new Promise((function(n,i){setTimeout((function r(){switch(t.clientWaitSync(e,t.SYNC_FLUSH_COMMANDS_BIT,0)){case t.WAIT_FAILED:i();break;case t.TIMEOUT_EXPIRED:setTimeout(r,4);break;default:n()}}),4)}))}(Pt,h),Pt.bindBuffer(Pt.PIXEL_PACK_BUFFER,t),Pt.getBufferSubData(Pt.PIXEL_PACK_BUFFER,0,s),Pt.deleteBuffer(t),Pt.deleteSync(h),s}throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")}},this.copyFramebufferToTexture=function(t,e=null,n=0){!0!==t.isTexture&&(pe("WebGLRenderer: copyFramebufferToTexture function signature has changed."),e=arguments[0]||null,t=arguments[1]);const i=Math.pow(2,-n),r=Math.floor(t.image.width*i),s=Math.floor(t.image.height*i),a=null!==e?e.x:0,o=null!==e?e.y:0;ut.setTexture2D(t,0),Pt.copyTexSubImage2D(Pt.TEXTURE_2D,n,0,0,a,o,r,s),lt.unbindTexture()},this.copyTextureToTexture=function(t,e,n=null,i=null,r=0){let s,a,o,l,c,h;!0!==t.isTexture&&(pe("WebGLRenderer: copyTextureToTexture function signature has changed."),i=arguments[0]||null,t=arguments[1],e=arguments[2],r=arguments[3]||0,n=null),null!==n?(s=n.max.x-n.min.x,a=n.max.y-n.min.y,o=n.min.x,l=n.min.y):(s=t.image.width,a=t.image.height,o=0,l=0),null!==i?(c=i.x,h=i.y):(c=0,h=0);const u=At.convert(e.format),d=At.convert(e.type);ut.setTexture2D(e,0),Pt.pixelStorei(Pt.UNPACK_FLIP_Y_WEBGL,e.flipY),Pt.pixelStorei(Pt.UNPACK_PREMULTIPLY_ALPHA_WEBGL,e.premultiplyAlpha),Pt.pixelStorei(Pt.UNPACK_ALIGNMENT,e.unpackAlignment);const p=Pt.getParameter(Pt.UNPACK_ROW_LENGTH),m=Pt.getParameter(Pt.UNPACK_IMAGE_HEIGHT),f=Pt.getParameter(Pt.UNPACK_SKIP_PIXELS),g=Pt.getParameter(Pt.UNPACK_SKIP_ROWS),v=Pt.getParameter(Pt.UNPACK_SKIP_IMAGES),_=t.isCompressedTexture?t.mipmaps[r]:t.image;Pt.pixelStorei(Pt.UNPACK_ROW_LENGTH,_.width),Pt.pixelStorei(Pt.UNPACK_IMAGE_HEIGHT,_.height),Pt.pixelStorei(Pt.UNPACK_SKIP_PIXELS,o),Pt.pixelStorei(Pt.UNPACK_SKIP_ROWS,l),t.isDataTexture?Pt.texSubImage2D(Pt.TEXTURE_2D,r,c,h,s,a,u,d,_.data):t.isCompressedTexture?Pt.compressedTexSubImage2D(Pt.TEXTURE_2D,r,c,h,_.width,_.height,u,_.data):Pt.texSubImage2D(Pt.TEXTURE_2D,r,c,h,s,a,u,d,_),Pt.pixelStorei(Pt.UNPACK_ROW_LENGTH,p),Pt.pixelStorei(Pt.UNPACK_IMAGE_HEIGHT,m),Pt.pixelStorei(Pt.UNPACK_SKIP_PIXELS,f),Pt.pixelStorei(Pt.UNPACK_SKIP_ROWS,g),Pt.pixelStorei(Pt.UNPACK_SKIP_IMAGES,v),0===r&&e.generateMipmaps&&Pt.generateMipmap(Pt.TEXTURE_2D),lt.unbindTexture()},this.copyTextureToTexture3D=function(t,e,n=null,i=null,r=0){let s,a,o,l,c,h,u,d,p;!0!==t.isTexture&&(pe("WebGLRenderer: copyTextureToTexture3D function signature has changed."),n=arguments[0]||null,i=arguments[1]||null,t=arguments[2],e=arguments[3],r=arguments[4]||0);const m=t.isCompressedTexture?t.mipmaps[r]:t.image;null!==n?(s=n.max.x-n.min.x,a=n.max.y-n.min.y,o=n.max.z-n.min.z,l=n.min.x,c=n.min.y,h=n.min.z):(s=m.width,a=m.height,o=m.depth,l=0,c=0,h=0),null!==i?(u=i.x,d=i.y,p=i.z):(u=0,d=0,p=0);const f=At.convert(e.format),g=At.convert(e.type);let v;if(e.isData3DTexture)ut.setTexture3D(e,0),v=Pt.TEXTURE_3D;else{if(!e.isDataArrayTexture&&!e.isCompressedArrayTexture)return void console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.");ut.setTexture2DArray(e,0),v=Pt.TEXTURE_2D_ARRAY}Pt.pixelStorei(Pt.UNPACK_FLIP_Y_WEBGL,e.flipY),Pt.pixelStorei(Pt.UNPACK_PREMULTIPLY_ALPHA_WEBGL,e.premultiplyAlpha),Pt.pixelStorei(Pt.UNPACK_ALIGNMENT,e.unpackAlignment);const _=Pt.getParameter(Pt.UNPACK_ROW_LENGTH),x=Pt.getParameter(Pt.UNPACK_IMAGE_HEIGHT),y=Pt.getParameter(Pt.UNPACK_SKIP_PIXELS),M=Pt.getParameter(Pt.UNPACK_SKIP_ROWS),S=Pt.getParameter(Pt.UNPACK_SKIP_IMAGES);Pt.pixelStorei(Pt.UNPACK_ROW_LENGTH,m.width),Pt.pixelStorei(Pt.UNPACK_IMAGE_HEIGHT,m.height),Pt.pixelStorei(Pt.UNPACK_SKIP_PIXELS,l),Pt.pixelStorei(Pt.UNPACK_SKIP_ROWS,c),Pt.pixelStorei(Pt.UNPACK_SKIP_IMAGES,h),t.isDataTexture||t.isData3DTexture?Pt.texSubImage3D(v,r,u,d,p,s,a,o,f,g,m.data):e.isCompressedArrayTexture?Pt.compressedTexSubImage3D(v,r,u,d,p,s,a,o,f,m.data):Pt.texSubImage3D(v,r,u,d,p,s,a,o,f,g,m),Pt.pixelStorei(Pt.UNPACK_ROW_LENGTH,_),Pt.pixelStorei(Pt.UNPACK_IMAGE_HEIGHT,x),Pt.pixelStorei(Pt.UNPACK_SKIP_PIXELS,y),Pt.pixelStorei(Pt.UNPACK_SKIP_ROWS,M),Pt.pixelStorei(Pt.UNPACK_SKIP_IMAGES,S),0===r&&e.generateMipmaps&&Pt.generateMipmap(v),lt.unbindTexture()},this.initRenderTarget=function(t){void 0===ht.get(t).__webglFramebuffer&&ut.setupRenderTarget(t)},this.initTexture=function(t){t.isCubeTexture?ut.setTextureCube(t,0):t.isData3DTexture?ut.setTexture3D(t,0):t.isDataArrayTexture||t.isCompressedArrayTexture?ut.setTexture2DArray(t,0):ut.setTexture2D(t,0),lt.unbindTexture()},this.resetState=function(){M=0,w=0,T=null,lt.reset(),Rt.reset()},"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return Wt}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(t){this._outputColorSpace=t;const e=this.getContext();e.drawingBufferColorSpace=t===Nt?"display-p3":"srgb",e.unpackColorSpace=_e.workingColorSpace===Ot?"display-p3":"srgb"}},e.WebGLUtils=za,e.WebGPUCoordinateSystem=Xt,e.WireframeGeometry=$c,e.WrapAroundEnding=Pt,e.ZeroCurvatureEnding=Rt,e.ZeroFactor=200,e.ZeroSlopeEnding=Ct,e.ZeroStencilOp=0,e.createCanvasElement=ue}},s={};function a(t){var e=s[t];if(void 0!==e)return e.exports;var n=s[t]={id:t,exports:{}};return r[t](n,n.exports,a),n.exports}a.m=r,e=[],a.O=(t,n,i,r)=>{if(!n){var s=1/0;for(h=0;h=r)&&Object.keys(a.O).every((t=>a.O[t](n[l])))?n.splice(l--,1):(o=!1,r0&&e[h-1][2]>r;h--)e[h]=e[h-1];e[h]=[n,i,r]},a.F={},a.E=t=>{Object.keys(a.F).map((e=>{a.F[e](t)}))},a.n=t=>{var e=t&&t.__esModule?()=>t.default:()=>t;return a.d(e,{a:e}),e},a.d=(t,e)=>{for(var n in e)a.o(e,n)&&!a.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:e[n]})},a.f={},a.e=t=>Promise.all(Object.keys(a.f).reduce(((e,n)=>(a.f[n](t,e),e)),[])),a.u=t=>(840===t?"pdfjs-dist-webpack":t)+".chunk.js",a.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),n={},i="FileViewer:",a.l=(t,e,r,s)=>{if(n[t])n[t].push(e);else{var o,l;if(void 0!==r)for(var c=document.getElementsByTagName("script"),h=0;h{o.onerror=o.onload=null,clearTimeout(p);var r=n[t];if(delete n[t],o.parentNode&&o.parentNode.removeChild(o),r&&r.forEach((t=>t(i))),e)return e(i)},p=setTimeout(d.bind(null,void 0,{type:"timeout",target:o}),12e4);o.onerror=d.bind(null,o.onerror),o.onload=d.bind(null,o.onload),l&&document.head.appendChild(o)}},a.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},a.p="/static/react-file-viewer/",(()=>{a.b=document.baseURI||self.location.href;var t={179:0};a.f.j=(e,n)=>{var i=a.o(t,e)?t[e]:void 0;if(0!==i)if(i)n.push(i[2]);else{var r=new Promise(((n,r)=>i=t[e]=[n,r]));n.push(i[2]=r);var s=a.p+a.u(e),o=new Error;a.l(s,(n=>{if(a.o(t,e)&&(0!==(i=t[e])&&(t[e]=void 0),i)){var r=n&&("load"===n.type?"missing":n.type),s=n&&n.target&&n.target.src;o.message="Loading chunk "+e+" failed.\n("+r+": "+s+")",o.name="ChunkLoadError",o.type=r,o.request=s,i[1](o)}}),"chunk-"+e,e)}},a.F.j=e=>{if(!a.o(t,e)||void 0===t[e]){t[e]=null;var n=document.createElement("link");a.nc&&n.setAttribute("nonce",a.nc),n.rel="prefetch",n.as="script",n.href=a.p+a.u(e),document.head.appendChild(n)}},a.O.j=e=>0===t[e];var e=(e,n)=>{var i,r,[s,o,l]=n,c=0;if(s.some((e=>0!==t[e]))){for(i in o)a.o(o,i)&&(a.m[i]=o[i]);if(l)var h=l(a)}for(e&&e(n);c{a.E(840)}),5);var o=a(352);return a.O(o)})())); \ No newline at end of file diff --git a/dist/pdfjs-dist-webpack.chunk.js b/dist/pdfjs-dist-webpack.chunk.js new file mode 100644 index 0000000..d1824ec --- /dev/null +++ b/dist/pdfjs-dist-webpack.chunk.js @@ -0,0 +1,2 @@ +/*! For license information please see pdfjs-dist-webpack.chunk.js.LICENSE.txt */ +"use strict";(self.webpackChunkFileViewer=self.webpackChunkFileViewer||[]).push([[840],{560:(t,e,i)=>{i.r(e),i.d(e,{AbortException:()=>cs,AnnotationEditorLayer:()=>us,AnnotationEditorParamsType:()=>ps,AnnotationEditorType:()=>gs,AnnotationEditorUIManager:()=>ms,AnnotationLayer:()=>fs,AnnotationMode:()=>bs,CMapCompressionType:()=>vs,ColorPicker:()=>As,DOMSVGFactory:()=>ys,DrawLayer:()=>ws,FeatureTest:()=>_s,GlobalWorkerOptions:()=>xs,ImageKind:()=>Cs,InvalidPDFException:()=>Es,MissingPDFException:()=>Ss,OPS:()=>Ts,OutputScale:()=>Ms,PDFDataRangeTransport:()=>ks,PDFDateString:()=>Is,PDFWorker:()=>Ps,PasswordResponses:()=>Rs,PermissionFlag:()=>Ds,PixelsPerInch:()=>Ls,RenderingCancelledException:()=>Fs,TextLayer:()=>Ns,UnexpectedResponseException:()=>Os,Util:()=>Bs,VerbosityLevel:()=>zs,XfaLayer:()=>Hs,build:()=>js,createValidAbsoluteUrl:()=>Us,fetchData:()=>$s,getDocument:()=>Ws,getFilenameFromUrl:()=>Gs,getPdfFilenameFromUrl:()=>Vs,getXfaPageViewport:()=>qs,isDataScheme:()=>Xs,isPdfFile:()=>Ks,noContextMenu:()=>Ys,normalizeUnicode:()=>Qs,setLayerDimensions:()=>Js,shadow:()=>Zs,version:()=>tn});var s={d:(t,e)=>{for(var i in e)s.o(e,i)&&!s.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e)};e=globalThis.pdfjsLib={},s.d(e,{AbortException:()=>D,AnnotationEditorLayer:()=>hs,AnnotationEditorParamsType:()=>d,AnnotationEditorType:()=>h,AnnotationEditorUIManager:()=>Tt,AnnotationLayer:()=>Qi,AnnotationMode:()=>l,CMapCompressionType:()=>g,ColorPicker:()=>as,DOMSVGFactory:()=>tt,DrawLayer:()=>ds,FeatureTest:()=>O,GlobalWorkerOptions:()=>fe,ImageKind:()=>u,InvalidPDFException:()=>k,MissingPDFException:()=>I,OPS:()=>m,OutputScale:()=>vt,PDFDataRangeTransport:()=>ai,PDFDateString:()=>ut,PDFWorker:()=>hi,PasswordResponses:()=>f,PermissionFlag:()=>c,PixelsPerInch:()=>Y,RenderingCancelledException:()=>it,TextLayer:()=>Ye,UnexpectedResponseException:()=>P,Util:()=>z,VerbosityLevel:()=>p,XfaLayer:()=>yi,build:()=>fi,createValidAbsoluteUrl:()=>C,fetchData:()=>Q,getDocument:()=>ii,getFilenameFromUrl:()=>at,getPdfFilenameFromUrl:()=>rt,getXfaPageViewport:()=>pt,isDataScheme:()=>st,isPdfFile:()=>nt,noContextMenu:()=>ht,normalizeUnicode:()=>U,setLayerDimensions:()=>bt,shadow:()=>E,version:()=>mi});const n=!("object"!=typeof process||process+""!="[object process]"||process.versions.nw||process.versions.electron&&process.type&&"browser"!==process.type),a=[1,0,0,1,0,0],r=[.001,0,0,.001,0,0],o=1.35,l={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},h={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15},d={RESIZE:1,CREATE:2,FREETEXT_SIZE:11,FREETEXT_COLOR:12,FREETEXT_OPACITY:13,INK_COLOR:21,INK_THICKNESS:22,INK_OPACITY:23,HIGHLIGHT_COLOR:31,HIGHLIGHT_DEFAULT_COLOR:32,HIGHLIGHT_THICKNESS:33,HIGHLIGHT_FREE:34,HIGHLIGHT_SHOW_ALL:35},c={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},u={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},p={ERRORS:0,WARNINGS:1,INFOS:5},g={NONE:0,BINARY:1},m={dependency:1,setLineWidth:2,setLineCap:3,setLineJoin:4,setMiterLimit:5,setDash:6,setRenderingIntent:7,setFlatness:8,setGState:9,save:10,restore:11,transform:12,moveTo:13,lineTo:14,curveTo:15,curveTo2:16,curveTo3:17,closePath:18,rectangle:19,stroke:20,closeStroke:21,fill:22,eoFill:23,fillStroke:24,eoFillStroke:25,closeFillStroke:26,closeEOFillStroke:27,endPath:28,clip:29,eoClip:30,beginText:31,endText:32,setCharSpacing:33,setWordSpacing:34,setHScale:35,setLeading:36,setFont:37,setTextRenderingMode:38,setTextRise:39,moveText:40,setLeadingMoveText:41,setTextMatrix:42,nextLine:43,showText:44,showSpacedText:45,nextLineShowText:46,nextLineSetSpacingShowText:47,setCharWidth:48,setCharWidthAndBounds:49,setStrokeColorSpace:50,setFillColorSpace:51,setStrokeColor:52,setStrokeColorN:53,setFillColor:54,setFillColorN:55,setStrokeGray:56,setFillGray:57,setStrokeRGBColor:58,setFillRGBColor:59,setStrokeCMYKColor:60,setFillCMYKColor:61,shadingFill:62,beginInlineImage:63,beginImageData:64,endInlineImage:65,paintXObject:66,markPoint:67,markPointProps:68,beginMarkedContent:69,beginMarkedContentProps:70,endMarkedContent:71,beginCompat:72,endCompat:73,paintFormXObjectBegin:74,paintFormXObjectEnd:75,beginGroup:76,endGroup:77,beginAnnotation:80,endAnnotation:81,paintImageMaskXObject:83,paintImageMaskXObjectGroup:84,paintImageXObject:85,paintInlineImageXObject:86,paintInlineImageXObjectGroup:87,paintImageXObjectRepeat:88,paintImageMaskXObjectRepeat:89,paintSolidColorImageMask:90,constructPath:91,setStrokeTransparent:92,setFillTransparent:93},f={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let b=p.WARNINGS;function v(t){Number.isInteger(t)&&(b=t)}function A(){return b}function y(t){b>=p.INFOS&&console.log(`Info: ${t}`)}function w(t){b>=p.WARNINGS&&console.log(`Warning: ${t}`)}function _(t){throw new Error(t)}function x(t,e){t||_(e)}function C(t,e=null,i=null){if(!t)return null;try{if(i&&"string"==typeof t&&(i.addDefaultProtocol&&t.startsWith("www.")&&t.match(/\./g)?.length>=2&&(t=`http://${t}`),i.tryConvertEncoding))try{t=decodeURIComponent(escape(t))}catch{}const s=e?new URL(t,e):new URL(t);if(function(t){switch(t?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}(s))return s}catch{}return null}function E(t,e,i,s=!1){return Object.defineProperty(t,e,{value:i,enumerable:!s,configurable:!0,writable:!1}),i}const S=function(){function t(t,e){this.message=t,this.name=e}return t.prototype=new Error,t.constructor=t,t}();class T extends S{constructor(t,e){super(t,"PasswordException"),this.code=e}}class M extends S{constructor(t,e){super(t,"UnknownErrorException"),this.details=e}}class k extends S{constructor(t){super(t,"InvalidPDFException")}}class I extends S{constructor(t){super(t,"MissingPDFException")}}class P extends S{constructor(t,e){super(t,"UnexpectedResponseException"),this.status=e}}class R extends S{constructor(t){super(t,"FormatError")}}class D extends S{constructor(t){super(t,"AbortException")}}function L(t){"object"==typeof t&&void 0!==t?.length||_("Invalid argument for bytesToString");const e=t.length,i=8192;if(et.toString(16).padStart(2,"0")));class z{static makeHexColor(t,e,i){return`#${B[t]}${B[e]}${B[i]}`}static scaleMinMax(t,e){let i;t[0]?(t[0]<0&&(i=e[0],e[0]=e[2],e[2]=i),e[0]*=t[0],e[2]*=t[0],t[3]<0&&(i=e[1],e[1]=e[3],e[3]=i),e[1]*=t[3],e[3]*=t[3]):(i=e[0],e[0]=e[1],e[1]=i,i=e[2],e[2]=e[3],e[3]=i,t[1]<0&&(i=e[1],e[1]=e[3],e[3]=i),e[1]*=t[1],e[3]*=t[1],t[2]<0&&(i=e[0],e[0]=e[2],e[2]=i),e[0]*=t[2],e[2]*=t[2]),e[0]+=t[4],e[1]+=t[5],e[2]+=t[4],e[3]+=t[5]}static transform(t,e){return[t[0]*e[0]+t[2]*e[1],t[1]*e[0]+t[3]*e[1],t[0]*e[2]+t[2]*e[3],t[1]*e[2]+t[3]*e[3],t[0]*e[4]+t[2]*e[5]+t[4],t[1]*e[4]+t[3]*e[5]+t[5]]}static applyTransform(t,e){return[t[0]*e[0]+t[1]*e[2]+e[4],t[0]*e[1]+t[1]*e[3]+e[5]]}static applyInverseTransform(t,e){const i=e[0]*e[3]-e[1]*e[2];return[(t[0]*e[3]-t[1]*e[2]+e[2]*e[5]-e[4]*e[3])/i,(-t[0]*e[1]+t[1]*e[0]+e[4]*e[1]-e[5]*e[0])/i]}static getAxialAlignedBoundingBox(t,e){const i=this.applyTransform(t,e),s=this.applyTransform(t.slice(2,4),e),n=this.applyTransform([t[0],t[3]],e),a=this.applyTransform([t[2],t[1]],e);return[Math.min(i[0],s[0],n[0],a[0]),Math.min(i[1],s[1],n[1],a[1]),Math.max(i[0],s[0],n[0],a[0]),Math.max(i[1],s[1],n[1],a[1])]}static inverseTransform(t){const e=t[0]*t[3]-t[1]*t[2];return[t[3]/e,-t[1]/e,-t[2]/e,t[0]/e,(t[2]*t[5]-t[4]*t[3])/e,(t[4]*t[1]-t[5]*t[0])/e]}static singularValueDecompose2dScale(t){const e=[t[0],t[2],t[1],t[3]],i=t[0]*e[0]+t[1]*e[2],s=t[0]*e[1]+t[1]*e[3],n=t[2]*e[0]+t[3]*e[2],a=t[2]*e[1]+t[3]*e[3],r=(i+a)/2,o=Math.sqrt((i+a)**2-4*(i*a-n*s))/2,l=r+o||1,h=r-o||1;return[Math.sqrt(l),Math.sqrt(h)]}static normalizeRect(t){const e=t.slice(0);return t[0]>t[2]&&(e[0]=t[2],e[2]=t[0]),t[1]>t[3]&&(e[1]=t[3],e[3]=t[1]),e}static intersect(t,e){const i=Math.max(Math.min(t[0],t[2]),Math.min(e[0],e[2])),s=Math.min(Math.max(t[0],t[2]),Math.max(e[0],e[2]));if(i>s)return null;const n=Math.max(Math.min(t[1],t[3]),Math.min(e[1],e[3])),a=Math.min(Math.max(t[1],t[3]),Math.max(e[1],e[3]));return n>a?null:[i,n,s,a]}static#t(t,e,i,s,n,a,r,o,l,h){if(l<=0||l>=1)return;const d=1-l,c=l*l,u=c*l,p=d*(d*(d*t+3*l*e)+3*c*i)+u*s,g=d*(d*(d*n+3*l*a)+3*c*r)+u*o;h[0]=Math.min(h[0],p),h[1]=Math.min(h[1],g),h[2]=Math.max(h[2],p),h[3]=Math.max(h[3],g)}static#e(t,e,i,s,n,a,r,o,l,h,d,c){if(Math.abs(l)<1e-12)return void(Math.abs(h)>=1e-12&&this.#t(t,e,i,s,n,a,r,o,-d/h,c));const u=h**2-4*d*l;if(u<0)return;const p=Math.sqrt(u),g=2*l;this.#t(t,e,i,s,n,a,r,o,(-h+p)/g,c),this.#t(t,e,i,s,n,a,r,o,(-h-p)/g,c)}static bezierBoundingBox(t,e,i,s,n,a,r,o,l){return l?(l[0]=Math.min(l[0],t,r),l[1]=Math.min(l[1],e,o),l[2]=Math.max(l[2],t,r),l[3]=Math.max(l[3],e,o)):l=[Math.min(t,r),Math.min(e,o),Math.max(t,r),Math.max(e,o)],this.#e(t,i,n,r,e,s,a,o,3*(3*(i-n)-t+r),6*(t-2*i+n),3*(i-t),l),this.#e(t,i,n,r,e,s,a,o,3*(3*(s-a)-e+o),6*(e-2*s+a),3*(s-e),l),l}}let H=null,j=null;function U(t){return H||(H=/([\u00a0\u00b5\u037e\u0eb3\u2000-\u200a\u202f\u2126\ufb00-\ufb04\ufb06\ufb20-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufba1\ufba4-\ufba9\ufbae-\ufbb1\ufbd3-\ufbdc\ufbde-\ufbe7\ufbea-\ufbf8\ufbfc-\ufbfd\ufc00-\ufc5d\ufc64-\ufcf1\ufcf5-\ufd3d\ufd88\ufdf4\ufdfa-\ufdfb\ufe71\ufe77\ufe79\ufe7b\ufe7d]+)|(\ufb05+)/gu,j=new Map([["ſt","ſt"]])),t.replaceAll(H,((t,e,i)=>e?e.normalize("NFKC"):j.get(i)))}const $="pdfjs_internal_id_";class W{addFilter(t){return"none"}addHCMFilter(t,e){return"none"}addAlphaFilter(t){return"none"}addLuminosityFilter(t){return"none"}addHighlightHCMFilter(t,e,i,s,n){return"none"}destroy(t=!1){}}class G{#i=!1;constructor({enableHWA:t=!1}){this.#i=t}create(t,e){if(t<=0||e<=0)throw new Error("Invalid canvas size");const i=this._createCanvas(t,e);return{canvas:i,context:i.getContext("2d",{willReadFrequently:!this.#i})}}reset(t,e,i){if(!t.canvas)throw new Error("Canvas is not specified");if(e<=0||i<=0)throw new Error("Invalid canvas size");t.canvas.width=e,t.canvas.height=i}destroy(t){if(!t.canvas)throw new Error("Canvas is not specified");t.canvas.width=0,t.canvas.height=0,t.canvas=null,t.context=null}_createCanvas(t,e){_("Abstract method `_createCanvas` called.")}}class V{constructor({baseUrl:t=null,isCompressed:e=!0}){this.baseUrl=t,this.isCompressed=e}async fetch({name:t}){if(!this.baseUrl)throw new Error("Ensure that the `cMapUrl` and `cMapPacked` API parameters are provided.");if(!t)throw new Error("CMap name must be specified.");const e=this.baseUrl+t+(this.isCompressed?".bcmap":""),i=this.isCompressed?g.BINARY:g.NONE;return this._fetchData(e,i).catch((t=>{throw new Error(`Unable to load ${this.isCompressed?"binary ":""}CMap at: ${e}`)}))}_fetchData(t,e){_("Abstract method `_fetchData` called.")}}class q{constructor({baseUrl:t=null}){this.baseUrl=t}async fetch({filename:t}){if(!this.baseUrl)throw new Error("Ensure that the `standardFontDataUrl` API parameter is provided.");if(!t)throw new Error("Font filename must be specified.");const e=`${this.baseUrl}${t}`;return this._fetchData(e).catch((t=>{throw new Error(`Unable to load font data at: ${e}`)}))}_fetchData(t){_("Abstract method `_fetchData` called.")}}class X{create(t,e,i=!1){if(t<=0||e<=0)throw new Error("Invalid SVG dimensions");const s=this._createSVG("svg:svg");return s.setAttribute("version","1.1"),i||(s.setAttribute("width",`${t}px`),s.setAttribute("height",`${e}px`)),s.setAttribute("preserveAspectRatio","none"),s.setAttribute("viewBox",`0 0 ${t} ${e}`),s}createElement(t){if("string"!=typeof t)throw new Error("Invalid SVG element type");return this._createSVG(t)}_createSVG(t){_("Abstract method `_createSVG` called.")}}const K="http://www.w3.org/2000/svg";class Y{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF}async function Q(t,e="text"){if(lt(t,document.baseURI)){const i=await fetch(t);if(!i.ok)throw new Error(i.statusText);switch(e){case"arraybuffer":return i.arrayBuffer();case"blob":return i.blob();case"json":return i.json()}return i.text()}return new Promise(((i,s)=>{const n=new XMLHttpRequest;n.open("GET",t,!0),n.responseType=e,n.onreadystatechange=()=>{if(n.readyState===XMLHttpRequest.DONE)if(200!==n.status&&0!==n.status)s(new Error(n.statusText));else{switch(e){case"arraybuffer":case"blob":case"json":return void i(n.response)}i(n.responseText)}},n.send(null)}))}class J extends V{_fetchData(t,e){return Q(t,this.isCompressed?"arraybuffer":"text").then((t=>({cMapData:t instanceof ArrayBuffer?new Uint8Array(t):F(t),compressionType:e})))}}class Z extends q{_fetchData(t){return Q(t,"arraybuffer").then((t=>new Uint8Array(t)))}}class tt extends X{_createSVG(t){return document.createElementNS(K,t)}}class et{constructor({viewBox:t,scale:e,rotation:i,offsetX:s=0,offsetY:n=0,dontFlip:a=!1}){this.viewBox=t,this.scale=e,this.rotation=i,this.offsetX=s,this.offsetY=n;const r=(t[2]+t[0])/2,o=(t[3]+t[1])/2;let l,h,d,c,u,p,g,m;switch((i%=360)<0&&(i+=360),i){case 180:l=-1,h=0,d=0,c=1;break;case 90:l=0,h=1,d=1,c=0;break;case 270:l=0,h=-1,d=-1,c=0;break;case 0:l=1,h=0,d=0,c=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}a&&(d=-d,c=-c),0===l?(u=Math.abs(o-t[1])*e+s,p=Math.abs(r-t[0])*e+n,g=(t[3]-t[1])*e,m=(t[2]-t[0])*e):(u=Math.abs(r-t[0])*e+s,p=Math.abs(o-t[1])*e+n,g=(t[2]-t[0])*e,m=(t[3]-t[1])*e),this.transform=[l*e,h*e,d*e,c*e,u-l*e*r-d*e*o,p-h*e*r-c*e*o],this.width=g,this.height=m}get rawDims(){const{viewBox:t}=this;return E(this,"rawDims",{pageWidth:t[2]-t[0],pageHeight:t[3]-t[1],pageX:t[0],pageY:t[1]})}clone({scale:t=this.scale,rotation:e=this.rotation,offsetX:i=this.offsetX,offsetY:s=this.offsetY,dontFlip:n=!1}={}){return new et({viewBox:this.viewBox.slice(),scale:t,rotation:e,offsetX:i,offsetY:s,dontFlip:n})}convertToViewportPoint(t,e){return z.applyTransform([t,e],this.transform)}convertToViewportRectangle(t){const e=z.applyTransform([t[0],t[1]],this.transform),i=z.applyTransform([t[2],t[3]],this.transform);return[e[0],e[1],i[0],i[1]]}convertToPdfPoint(t,e){return z.applyInverseTransform([t,e],this.transform)}}class it extends S{constructor(t,e=0){super(t,"RenderingCancelledException"),this.extraDelay=e}}function st(t){const e=t.length;let i=0;for(;i=1&&s<=12?s-1:0;let n=parseInt(e[3],10);n=n>=1&&n<=31?n:1;let a=parseInt(e[4],10);a=a>=0&&a<=23?a:0;let r=parseInt(e[5],10);r=r>=0&&r<=59?r:0;let o=parseInt(e[6],10);o=o>=0&&o<=59?o:0;const l=e[7]||"Z";let h=parseInt(e[8],10);h=h>=0&&h<=23?h:0;let d=parseInt(e[9],10)||0;return d=d>=0&&d<=59?d:0,"-"===l?(a+=h,r+=d):"+"===l&&(a-=h,r-=d),new Date(Date.UTC(i,s,n,a,r,o))}}function pt(t,{scale:e=1,rotation:i=0}){const{width:s,height:n}=t.attributes.style,a=[0,0,parseInt(s),parseInt(n)];return new et({viewBox:a,scale:e,rotation:i})}function gt(t){if(t.startsWith("#")){const e=parseInt(t.slice(1),16);return[(16711680&e)>>16,(65280&e)>>8,255&e]}return t.startsWith("rgb(")?t.slice(4,-1).split(",").map((t=>parseInt(t))):t.startsWith("rgba(")?t.slice(5,-1).split(",").map((t=>parseInt(t))).slice(0,3):(w(`Not a valid color format: "${t}"`),[0,0,0])}function mt(t){const{a:e,b:i,c:s,d:n,e:a,f:r}=t.getTransform();return[e,i,s,n,a,r]}function ft(t){const{a:e,b:i,c:s,d:n,e:a,f:r}=t.getTransform().invertSelf();return[e,i,s,n,a,r]}function bt(t,e,i=!1,s=!0){if(e instanceof et){const{pageWidth:s,pageHeight:n}=e.rawDims,{style:a}=t,r=O.isCSSRoundSupported,o=`var(--scale-factor) * ${s}px`,l=`var(--scale-factor) * ${n}px`,h=r?`round(down, ${o}, var(--scale-round-x, 1px))`:`calc(${o})`,d=r?`round(down, ${l}, var(--scale-round-y, 1px))`:`calc(${l})`;i&&e.rotation%180!=0?(a.width=d,a.height=h):(a.width=h,a.height=d)}s&&t.setAttribute("data-main-rotation",e.rotation)}class vt{constructor(){const t=window.devicePixelRatio||1;this.sx=t,this.sy=t}get scaled(){return 1!==this.sx||1!==this.sy}get symmetric(){return this.sx===this.sy}}class At{#s=null;#n=null;#a;#r=null;#o=null;static#l=null;constructor(t){this.#a=t,At.#l||=Object.freeze({freetext:"pdfjs-editor-remove-freetext-button",highlight:"pdfjs-editor-remove-highlight-button",ink:"pdfjs-editor-remove-ink-button",stamp:"pdfjs-editor-remove-stamp-button"})}render(){const t=this.#s=document.createElement("div");t.classList.add("editToolbar","hidden"),t.setAttribute("role","toolbar");const e=this.#a._uiManager._signal;t.addEventListener("contextmenu",ht,{signal:e}),t.addEventListener("pointerdown",At.#h,{signal:e});const i=this.#r=document.createElement("div");i.className="buttons",t.append(i);const s=this.#a.toolbarPosition;if(s){const{style:e}=t,i="ltr"===this.#a._uiManager.direction?1-s[0]:s[0];e.insetInlineEnd=100*i+"%",e.top=`calc(${100*s[1]}% + var(--editor-toolbar-vert-offset))`}return this.#d(),t}get div(){return this.#s}static#h(t){t.stopPropagation()}#c(t){this.#a._focusEventsAllowed=!1,t.preventDefault(),t.stopPropagation()}#u(t){this.#a._focusEventsAllowed=!0,t.preventDefault(),t.stopPropagation()}#p(t){const e=this.#a._uiManager._signal;t.addEventListener("focusin",this.#c.bind(this),{capture:!0,signal:e}),t.addEventListener("focusout",this.#u.bind(this),{capture:!0,signal:e}),t.addEventListener("contextmenu",ht,{signal:e})}hide(){this.#s.classList.add("hidden"),this.#n?.hideDropdown()}show(){this.#s.classList.remove("hidden"),this.#o?.shown()}#d(){const{editorType:t,_uiManager:e}=this.#a,i=document.createElement("button");i.className="delete",i.tabIndex=0,i.setAttribute("data-l10n-id",At.#l[t]),this.#p(i),i.addEventListener("click",(t=>{e.delete()}),{signal:e._signal}),this.#r.append(i)}get#g(){const t=document.createElement("div");return t.className="divider",t}async addAltText(t){const e=await t.render();this.#p(e),this.#r.prepend(e,this.#g),this.#o=t}addColorPicker(t){this.#n=t;const e=t.renderButton();this.#p(e),this.#r.prepend(e,this.#g)}remove(){this.#s.remove(),this.#n?.destroy(),this.#n=null}}class yt{#r=null;#s=null;#m;constructor(t){this.#m=t}#f(){const t=this.#s=document.createElement("div");t.className="editToolbar",t.setAttribute("role","toolbar"),t.addEventListener("contextmenu",ht,{signal:this.#m._signal});const e=this.#r=document.createElement("div");return e.className="buttons",t.append(e),this.#b(),t}#v(t,e){let i=0,s=0;for(const n of t){const t=n.y+n.height;if(ti?(s=a,i=t):e?a>s&&(s=a):a{this.#m.highlightSelection("floating_button")}),{signal:i}),this.#r.append(t)}}function wt(t,e,i){for(const s of i)e.addEventListener(s,t[s].bind(t))}class _t{#A=0;get id(){return"pdfjs_internal_editor_"+this.#A++}}class xt{#y=function(){if("undefined"!=typeof crypto&&"function"==typeof crypto?.randomUUID)return crypto.randomUUID();const t=new Uint8Array(32);if("undefined"!=typeof crypto&&"function"==typeof crypto?.getRandomValues)crypto.getRandomValues(t);else for(let e=0;e<32;e++)t[e]=Math.floor(255*Math.random());return L(t)}();#A=0;#w=null;static get _isSVGFittingCanvas(){const t=new OffscreenCanvas(1,3).getContext("2d",{willReadFrequently:!0}),e=new Image;return e.src='data:image/svg+xml;charset=UTF-8,',E(this,"_isSVGFittingCanvas",e.decode().then((()=>(t.drawImage(e,0,0,1,1,0,0,1,3),0===new Uint32Array(t.getImageData(0,0,1,1).data.buffer)[0]))))}async#_(t,e){this.#w||=new Map;let i=this.#w.get(t);if(null===i)return null;if(i?.bitmap)return i.refCounter+=1,i;try{let t;if(i||={bitmap:null,id:`image_${this.#y}_${this.#A++}`,refCounter:0,isSvg:!1},"string"==typeof e?(i.url=e,t=await Q(e,"blob")):e instanceof File?t=i.file=e:e instanceof Blob&&(t=e),"image/svg+xml"===t.type){const e=xt._isSVGFittingCanvas,s=new FileReader,n=new Image,a=new Promise(((t,a)=>{n.onload=()=>{i.bitmap=n,i.isSvg=!0,t()},s.onload=async()=>{const t=i.svgUrl=s.result;n.src=await e?`${t}#svgView(preserveAspectRatio(none))`:t},n.onerror=s.onerror=a}));s.readAsDataURL(t),await a}else i.bitmap=await createImageBitmap(t);i.refCounter=1}catch(t){console.error(t),i=null}return this.#w.set(t,i),i&&this.#w.set(i.id,i),i}async getFromFile(t){const{lastModified:e,name:i,size:s,type:n}=t;return this.#_(`${e}_${i}_${s}_${n}`,t)}async getFromUrl(t){return this.#_(t,t)}async getFromBlob(t,e){const i=await e;return this.#_(t,i)}async getFromId(t){this.#w||=new Map;const e=this.#w.get(t);if(!e)return null;if(e.bitmap)return e.refCounter+=1,e;if(e.file)return this.getFromFile(e.file);if(e.blobPromise){const{blobPromise:t}=e;return delete e.blobPromise,this.getFromBlob(e.id,t)}return this.getFromUrl(e.url)}getFromCanvas(t,e){this.#w||=new Map;let i=this.#w.get(t);if(i?.bitmap)return i.refCounter+=1,i;const s=new OffscreenCanvas(e.width,e.height);return s.getContext("2d").drawImage(e,0,0),i={bitmap:s.transferToImageBitmap(),id:`image_${this.#y}_${this.#A++}`,refCounter:1,isSvg:!1},this.#w.set(t,i),this.#w.set(i.id,i),i}getSvgUrl(t){const e=this.#w.get(t);return e?.isSvg?e.svgUrl:null}deleteId(t){this.#w||=new Map;const e=this.#w.get(t);if(!e)return;if(e.refCounter-=1,0!==e.refCounter)return;const{bitmap:i}=e;if(!e.url&&!e.file){const t=new OffscreenCanvas(i.width,i.height);t.getContext("bitmaprenderer").transferFromImageBitmap(i),e.blobPromise=t.convertToBlob()}i.close?.(),e.bitmap=null}isValidId(t){return t.startsWith(`image_${this.#y}_`)}}class Ct{#x=[];#C=!1;#E;#S=-1;constructor(t=128){this.#E=t}add({cmd:t,undo:e,post:i,mustExec:s,type:n=NaN,overwriteIfSameType:a=!1,keepUndo:r=!1}){if(s&&t(),this.#C)return;const o={cmd:t,undo:e,post:i,type:n};if(-1===this.#S)return this.#x.length>0&&(this.#x.length=0),this.#S=0,void this.#x.push(o);if(a&&this.#x[this.#S].type===n)return r&&(o.undo=this.#x[this.#S].undo),void(this.#x[this.#S]=o);const l=this.#S+1;l===this.#E?this.#x.splice(0,1):(this.#S=l,lt===e[i])))return St._colorsMapping.get(t);return e}getHexCode(t){const e=this._colors.get(t);return e?z.makeHexColor(...e):t}}class Tt{#M=new AbortController;#k=null;#I=new Map;#P=new Map;#R=null;#D=null;#L=null;#F=new Ct;#N=null;#O=0;#B=new Set;#z=null;#H=null;#j=new Set;#U=!1;#$=!1;#W=!1;#G=null;#V=null;#q=null;#X=null;#K=!1;#Y=null;#Q=new _t;#J=!1;#Z=!1;#tt=null;#et=null;#it=null;#st=null;#nt=h.NONE;#at=new Set;#rt=null;#ot=null;#lt=null;#ht={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1};#dt=[0,0];#ct=null;#ut=null;#pt=null;#gt=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){const t=Tt.prototype,e=t=>t.#ut.contains(document.activeElement)&&"BUTTON"!==document.activeElement.tagName&&t.hasSomethingToControl(),i=(t,{target:e})=>{if(e instanceof HTMLInputElement){const{type:t}=e;return"text"!==t&&"number"!==t}return!0},s=this.TRANSLATE_SMALL,n=this.TRANSLATE_BIG;return E(this,"_keyboardManager",new Et([[["ctrl+a","mac+meta+a"],t.selectAll,{checker:i}],[["ctrl+z","mac+meta+z"],t.undo,{checker:i}],[["ctrl+y","ctrl+shift+z","mac+meta+shift+z","ctrl+shift+Z","mac+meta+shift+Z"],t.redo,{checker:i}],[["Backspace","alt+Backspace","ctrl+Backspace","shift+Backspace","mac+Backspace","mac+alt+Backspace","mac+ctrl+Backspace","Delete","ctrl+Delete","shift+Delete","mac+Delete"],t.delete,{checker:i}],[["Enter","mac+Enter"],t.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#ut.contains(e)&&!t.isEnterHandled}],[[" ","mac+ "],t.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#ut.contains(document.activeElement)}],[["Escape","mac+Escape"],t.unselectAll],[["ArrowLeft","mac+ArrowLeft"],t.translateSelectedEditors,{args:[-s,0],checker:e}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t.translateSelectedEditors,{args:[-n,0],checker:e}],[["ArrowRight","mac+ArrowRight"],t.translateSelectedEditors,{args:[s,0],checker:e}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t.translateSelectedEditors,{args:[n,0],checker:e}],[["ArrowUp","mac+ArrowUp"],t.translateSelectedEditors,{args:[0,-s],checker:e}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t.translateSelectedEditors,{args:[0,-n],checker:e}],[["ArrowDown","mac+ArrowDown"],t.translateSelectedEditors,{args:[0,s],checker:e}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t.translateSelectedEditors,{args:[0,n],checker:e}]]))}constructor(t,e,i,s,n,a,r,o,l,h,d){const c=this._signal=this.#M.signal;this.#ut=t,this.#pt=e,this.#R=i,this._eventBus=s,s._on("editingaction",this.onEditingAction.bind(this),{signal:c}),s._on("pagechanging",this.onPageChanging.bind(this),{signal:c}),s._on("scalechanging",this.onScaleChanging.bind(this),{signal:c}),s._on("rotationchanging",this.onRotationChanging.bind(this),{signal:c}),s._on("setpreference",this.onSetPreference.bind(this),{signal:c}),s._on("switchannotationeditorparams",(t=>this.updateParams(t.type,t.value)),{signal:c}),this.#mt(),this.#ft(),this.#bt(),this.#D=n.annotationStorage,this.#G=n.filterFactory,this.#ot=a,this.#X=r||null,this.#U=o,this.#$=l,this.#W=h,this.#st=d||null,this.viewParameters={realScale:Y.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1}destroy(){this.#gt?.resolve(),this.#gt=null,this.#M?.abort(),this.#M=null,this._signal=null;for(const t of this.#P.values())t.destroy();this.#P.clear(),this.#I.clear(),this.#j.clear(),this.#k=null,this.#at.clear(),this.#F.destroy(),this.#R?.destroy(),this.#Y?.hide(),this.#Y=null,this.#V&&(clearTimeout(this.#V),this.#V=null),this.#ct&&(clearTimeout(this.#ct),this.#ct=null)}combinedSignal(t){return AbortSignal.any([this._signal,t.signal])}get mlManager(){return this.#st}get useNewAltTextFlow(){return this.#$}get useNewAltTextWhenAddingImage(){return this.#W}get hcmFilter(){return E(this,"hcmFilter",this.#ot?this.#G.addHCMFilter(this.#ot.foreground,this.#ot.background):"none")}get direction(){return E(this,"direction",getComputedStyle(this.#ut).direction)}get highlightColors(){return E(this,"highlightColors",this.#X?new Map(this.#X.split(",").map((t=>t.split("=").map((t=>t.trim()))))):null)}get highlightColorNames(){return E(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,(t=>t.reverse()))):null)}setMainHighlightColorPicker(t){this.#it=t}editAltText(t,e=!1){this.#R?.editAltText(this,t,e)}switchToMode(t,e){this._eventBus.on("annotationeditormodechanged",e,{once:!0,signal:this._signal}),this._eventBus.dispatch("showannotationeditorui",{source:this,mode:t})}setPreference(t,e){this._eventBus.dispatch("setpreference",{source:this,name:t,value:e})}onSetPreference({name:t,value:e}){"enableNewAltTextWhenAddingImage"===t&&(this.#W=e)}onPageChanging({pageNumber:t}){this.#O=t-1}focusMainContainer(){this.#ut.focus()}findParent(t,e){for(const i of this.#P.values()){const{x:s,y:n,width:a,height:r}=i.div.getBoundingClientRect();if(t>=s&&t<=s+a&&e>=n&&e<=n+r)return i}return null}disableUserSelect(t=!1){this.#pt.classList.toggle("noUserSelect",t)}addShouldRescale(t){this.#j.add(t)}removeShouldRescale(t){this.#j.delete(t)}onScaleChanging({scale:t}){this.commitOrRemove(),this.viewParameters.realScale=t*Y.PDF_TO_CSS_UNITS;for(const t of this.#j)t.onScaleChanging()}onRotationChanging({pagesRotation:t}){this.commitOrRemove(),this.viewParameters.rotation=t}#vt({anchorNode:t}){return t.nodeType===Node.TEXT_NODE?t.parentElement:t}#At(t){const{currentLayer:e}=this;if(e.hasTextLayer(t))return e;for(const e of this.#P.values())if(e.hasTextLayer(t))return e;return null}highlightSelection(t=""){const e=document.getSelection();if(!e||e.isCollapsed)return;const{anchorNode:i,anchorOffset:s,focusNode:n,focusOffset:a}=e,r=e.toString(),o=this.#vt(e).closest(".textLayer"),l=this.getSelectionBoxes(o);if(!l)return;e.empty();const d=this.#At(o),c=this.#nt===h.NONE,u=()=>{d?.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:t,boxes:l,anchorNode:i,anchorOffset:s,focusNode:n,focusOffset:a,text:r}),c&&this.showAllEditors("highlight",!0,!0)};c?this.switchToMode(h.HIGHLIGHT,u):u()}#yt(){const t=document.getSelection();if(!t||t.isCollapsed)return;const e=this.#vt(t).closest(".textLayer"),i=this.getSelectionBoxes(e);i&&(this.#Y||=new yt(this),this.#Y.show(e,i,"ltr"===this.direction))}addToAnnotationStorage(t){t.isEmpty()||!this.#D||this.#D.has(t.id)||this.#D.setValue(t.id,t)}#wt(){const t=document.getSelection();if(!t||t.isCollapsed)return void(this.#rt&&(this.#Y?.hide(),this.#rt=null,this.#_t({hasSelectedText:!1})));const{anchorNode:e}=t;if(e===this.#rt)return;const i=this.#vt(t).closest(".textLayer");if(i){if(this.#Y?.hide(),this.#rt=e,this.#_t({hasSelectedText:!0}),(this.#nt===h.HIGHLIGHT||this.#nt===h.NONE)&&(this.#nt===h.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0),this.#K=this.isShiftKeyDown,!this.isShiftKeyDown)){const t=this.#nt===h.HIGHLIGHT?this.#At(i):null;t?.toggleDrawing();const e=new AbortController,s=this.combinedSignal(e),n=i=>{"pointerup"===i.type&&0!==i.button||(e.abort(),t?.toggleDrawing(!0),"pointerup"===i.type&&this.#xt("main_toolbar"))};window.addEventListener("pointerup",n,{signal:s}),window.addEventListener("blur",n,{signal:s})}}else this.#rt&&(this.#Y?.hide(),this.#rt=null,this.#_t({hasSelectedText:!1}))}#xt(t=""){this.#nt===h.HIGHLIGHT?this.highlightSelection(t):this.#U&&this.#yt()}#mt(){document.addEventListener("selectionchange",this.#wt.bind(this),{signal:this._signal})}#Ct(){if(this.#q)return;this.#q=new AbortController;const t=this.combinedSignal(this.#q);window.addEventListener("focus",this.focus.bind(this),{signal:t}),window.addEventListener("blur",this.blur.bind(this),{signal:t})}#Et(){this.#q?.abort(),this.#q=null}blur(){if(this.isShiftKeyDown=!1,this.#K&&(this.#K=!1,this.#xt("main_toolbar")),!this.hasSelection)return;const{activeElement:t}=document;for(const e of this.#at)if(e.div.contains(t)){this.#et=[e,t],e._focusEventsAllowed=!1;break}}focus(){if(!this.#et)return;const[t,e]=this.#et;this.#et=null,e.addEventListener("focusin",(()=>{t._focusEventsAllowed=!0}),{once:!0,signal:this._signal}),e.focus()}#bt(){if(this.#tt)return;this.#tt=new AbortController;const t=this.combinedSignal(this.#tt);window.addEventListener("keydown",this.keydown.bind(this),{signal:t}),window.addEventListener("keyup",this.keyup.bind(this),{signal:t})}#St(){this.#tt?.abort(),this.#tt=null}#Tt(){if(this.#N)return;this.#N=new AbortController;const t=this.combinedSignal(this.#N);document.addEventListener("copy",this.copy.bind(this),{signal:t}),document.addEventListener("cut",this.cut.bind(this),{signal:t}),document.addEventListener("paste",this.paste.bind(this),{signal:t})}#Mt(){this.#N?.abort(),this.#N=null}#ft(){const t=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:t}),document.addEventListener("drop",this.drop.bind(this),{signal:t})}addEditListeners(){this.#bt(),this.#Tt()}removeEditListeners(){this.#St(),this.#Mt()}dragOver(t){for(const{type:e}of t.dataTransfer.items)for(const i of this.#H)if(i.isHandlingMimeForPasting(e))return t.dataTransfer.dropEffect="copy",void t.preventDefault()}drop(t){for(const e of t.dataTransfer.items)for(const i of this.#H)if(i.isHandlingMimeForPasting(e.type))return i.paste(e,this.currentLayer),void t.preventDefault()}copy(t){if(t.preventDefault(),this.#k?.commitOrRemove(),!this.hasSelection)return;const e=[];for(const t of this.#at){const i=t.serialize(!0);i&&e.push(i)}0!==e.length&&t.clipboardData.setData("application/pdfjs",JSON.stringify(e))}cut(t){this.copy(t),this.delete()}async paste(t){t.preventDefault();const{clipboardData:e}=t;for(const t of e.items)for(const e of this.#H)if(e.isHandlingMimeForPasting(t.type))return void e.paste(t,this.currentLayer);let i=e.getData("application/pdfjs");if(!i)return;try{i=JSON.parse(i)}catch(t){return void w(`paste: "${t.message}".`)}if(!Array.isArray(i))return;this.unselectAll();const s=this.currentLayer;try{const t=[];for(const e of i){const i=await s.deserialize(e);if(!i)return;t.push(i)}const e=()=>{for(const e of t)this.#kt(e);this.#It(t)},n=()=>{for(const e of t)e.remove()};this.addCommands({cmd:e,undo:n,mustExec:!0})}catch(t){w(`paste: "${t.message}".`)}}keydown(t){this.isShiftKeyDown||"Shift"!==t.key||(this.isShiftKeyDown=!0),this.#nt===h.NONE||this.isEditorHandlingKeyboard||Tt._keyboardManager.exec(this,t)}keyup(t){this.isShiftKeyDown&&"Shift"===t.key&&(this.isShiftKeyDown=!1,this.#K&&(this.#K=!1,this.#xt("main_toolbar")))}onEditingAction({name:t}){switch(t){case"undo":case"redo":case"delete":case"selectAll":this[t]();break;case"highlightSelection":this.highlightSelection("context_menu")}}#_t(t){Object.entries(t).some((([t,e])=>this.#ht[t]!==e))&&(this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(this.#ht,t)}),this.#nt===h.HIGHLIGHT&&!1===t.hasSelectedEditor&&this.#Pt([[d.HIGHLIGHT_FREE,!0]]))}#Pt(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})}setEditingState(t){t?(this.#Ct(),this.#Tt(),this.#_t({isEditing:this.#nt!==h.NONE,isEmpty:this.#Rt(),hasSomethingToUndo:this.#F.hasSomethingToUndo(),hasSomethingToRedo:this.#F.hasSomethingToRedo(),hasSelectedEditor:!1})):(this.#Et(),this.#Mt(),this.#_t({isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(t){if(!this.#H){this.#H=t;for(const t of this.#H)this.#Pt(t.defaultPropertiesToUpdate)}}getId(){return this.#Q.id}get currentLayer(){return this.#P.get(this.#O)}getLayer(t){return this.#P.get(t)}get currentPageIndex(){return this.#O}addLayer(t){this.#P.set(t.pageIndex,t),this.#J?t.enable():t.disable()}removeLayer(t){this.#P.delete(t.pageIndex)}async updateMode(t,e=null,i=!1){if(this.#nt!==t&&(!this.#gt||(await this.#gt.promise,this.#gt))){if(this.#gt=Promise.withResolvers(),this.#nt=t,t===h.NONE)return this.setEditingState(!1),this.#Dt(),void this.#gt.resolve();this.setEditingState(!0),await this.#Lt(),this.unselectAll();for(const e of this.#P.values())e.updateMode(t);if(!e)return i&&this.addNewEditorFromKeyboard(),void this.#gt.resolve();for(const t of this.#I.values())t.annotationElementId===e?(this.setSelected(t),t.enterInEditMode()):t.unselect();this.#gt.resolve()}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t!==this.#nt&&this._eventBus.dispatch("switchannotationeditormode",{source:this,mode:t})}updateParams(t,e){if(this.#H){switch(t){case d.CREATE:return void this.currentLayer.addNewEditor();case d.HIGHLIGHT_DEFAULT_COLOR:this.#it?.updateColor(e);break;case d.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}}),(this.#lt||=new Map).set(t,e),this.showAllEditors("highlight",e)}for(const i of this.#at)i.updateParams(t,e);for(const i of this.#H)i.updateDefaultParams(t,e)}}showAllEditors(t,e,i=!1){for(const i of this.#I.values())i.editorType===t&&i.show(e);(this.#lt?.get(d.HIGHLIGHT_SHOW_ALL)??!0)!==e&&this.#Pt([[d.HIGHLIGHT_SHOW_ALL,e]])}enableWaiting(t=!1){if(this.#Z!==t){this.#Z=t;for(const e of this.#P.values())t?e.disableClick():e.enableClick(),e.div.classList.toggle("waiting",t)}}async#Lt(){if(!this.#J){this.#J=!0;const t=[];for(const e of this.#P.values())t.push(e.enable());await Promise.all(t);for(const t of this.#I.values())t.enable()}}#Dt(){if(this.unselectAll(),this.#J){this.#J=!1;for(const t of this.#P.values())t.disable();for(const t of this.#I.values())t.disable()}}getEditors(t){const e=[];for(const i of this.#I.values())i.pageIndex===t&&e.push(i);return e}getEditor(t){return this.#I.get(t)}addEditor(t){this.#I.set(t.id,t)}removeEditor(t){t.div.contains(document.activeElement)&&(this.#V&&clearTimeout(this.#V),this.#V=setTimeout((()=>{this.focusMainContainer(),this.#V=null}),0)),this.#I.delete(t.id),this.unselect(t),t.annotationElementId&&this.#B.has(t.annotationElementId)||this.#D?.remove(t.id)}addDeletedAnnotationElement(t){this.#B.add(t.annotationElementId),this.addChangedExistingAnnotation(t),t.deleted=!0}isDeletedAnnotationElement(t){return this.#B.has(t)}removeDeletedAnnotationElement(t){this.#B.delete(t.annotationElementId),this.removeChangedExistingAnnotation(t),t.deleted=!1}#kt(t){const e=this.#P.get(t.pageIndex);e?e.addOrRebuild(t):(this.addEditor(t),this.addToAnnotationStorage(t))}setActiveEditor(t){this.#k!==t&&(this.#k=t,t&&this.#Pt(t.propertiesToUpdate))}get#Ft(){let t=null;for(t of this.#at);return t}updateUI(t){this.#Ft===t&&this.#Pt(t.propertiesToUpdate)}toggleSelected(t){if(this.#at.has(t))return this.#at.delete(t),t.unselect(),void this.#_t({hasSelectedEditor:this.hasSelection});this.#at.add(t),t.select(),this.#Pt(t.propertiesToUpdate),this.#_t({hasSelectedEditor:!0})}setSelected(t){for(const e of this.#at)e!==t&&e.unselect();this.#at.clear(),this.#at.add(t),t.select(),this.#Pt(t.propertiesToUpdate),this.#_t({hasSelectedEditor:!0})}isSelected(t){return this.#at.has(t)}get firstSelectedEditor(){return this.#at.values().next().value}unselect(t){t.unselect(),this.#at.delete(t),this.#_t({hasSelectedEditor:this.hasSelection})}get hasSelection(){return 0!==this.#at.size}get isEnterHandled(){return 1===this.#at.size&&this.firstSelectedEditor.isEnterHandled}undo(){this.#F.undo(),this.#_t({hasSomethingToUndo:this.#F.hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:this.#Rt()})}redo(){this.#F.redo(),this.#_t({hasSomethingToUndo:!0,hasSomethingToRedo:this.#F.hasSomethingToRedo(),isEmpty:this.#Rt()})}addCommands(t){this.#F.add(t),this.#_t({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#Rt()})}#Rt(){if(0===this.#I.size)return!0;if(1===this.#I.size)for(const t of this.#I.values())return t.isEmpty();return!1}delete(){if(this.commitOrRemove(),!this.hasSelection)return;const t=[...this.#at];this.addCommands({cmd:()=>{for(const e of t)e.remove()},undo:()=>{for(const e of t)this.#kt(e)},mustExec:!0})}commitOrRemove(){this.#k?.commitOrRemove()}hasSomethingToControl(){return this.#k||this.hasSelection}#It(t){for(const t of this.#at)t.unselect();this.#at.clear();for(const e of t)e.isEmpty()||(this.#at.add(e),e.select());this.#_t({hasSelectedEditor:this.hasSelection})}selectAll(){for(const t of this.#at)t.commit();this.#It(this.#I.values())}unselectAll(){if((!this.#k||(this.#k.commitOrRemove(),this.#nt===h.NONE))&&this.hasSelection){for(const t of this.#at)t.unselect();this.#at.clear(),this.#_t({hasSelectedEditor:!1})}}translateSelectedEditors(t,e,i=!1){if(i||this.commitOrRemove(),!this.hasSelection)return;this.#dt[0]+=t,this.#dt[1]+=e;const[s,n]=this.#dt,a=[...this.#at];this.#ct&&clearTimeout(this.#ct),this.#ct=setTimeout((()=>{this.#ct=null,this.#dt[0]=this.#dt[1]=0,this.addCommands({cmd:()=>{for(const t of a)this.#I.has(t.id)&&t.translateInPage(s,n)},undo:()=>{for(const t of a)this.#I.has(t.id)&&t.translateInPage(-s,-n)},mustExec:!1})}),1e3);for(const i of a)i.translateInPage(t,e)}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0),this.#z=new Map;for(const t of this.#at)this.#z.set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!this.#z)return!1;this.disableUserSelect(!1);const t=this.#z;this.#z=null;let e=!1;for(const[{x:i,y:s,pageIndex:n},a]of t)a.newX=i,a.newY=s,a.newPageIndex=n,e||=i!==a.savedX||s!==a.savedY||n!==a.savedPageIndex;if(!e)return!1;const i=(t,e,i,s)=>{if(this.#I.has(t.id)){const n=this.#P.get(s);n?t._setParentAndPosition(n,e,i):(t.pageIndex=s,t.x=e,t.y=i)}};return this.addCommands({cmd:()=>{for(const[e,{newX:s,newY:n,newPageIndex:a}]of t)i(e,s,n,a)},undo:()=>{for(const[e,{savedX:s,savedY:n,savedPageIndex:a}]of t)i(e,s,n,a)},mustExec:!0}),!0}dragSelectedEditors(t,e){if(this.#z)for(const i of this.#z.keys())i.drag(t,e)}rebuild(t){if(null===t.parent){const e=this.getLayer(t.pageIndex);e?(e.changeParent(t),e.addOrRebuild(t)):(this.addEditor(t),this.addToAnnotationStorage(t),t.rebuild())}else t.parent.addOrRebuild(t)}get isEditorHandlingKeyboard(){return this.getActive()?.shouldGetKeyboardEvents()||1===this.#at.size&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(t){return this.#k===t}getActive(){return this.#k}getMode(){return this.#nt}get imageManager(){return E(this,"imageManager",new xt)}getSelectionBoxes(t){if(!t)return null;const e=document.getSelection();for(let i=0,s=e.rangeCount;i({x:(e-s)/a,y:1-(t+r-i)/n,width:o/a,height:r/n});break;case"180":r=(t,e,r,o)=>({x:1-(t+r-i)/n,y:1-(e+o-s)/a,width:r/n,height:o/a});break;case"270":r=(t,e,r,o)=>({x:1-(e+o-s)/a,y:(t-i)/n,width:o/a,height:r/n});break;default:r=(t,e,r,o)=>({x:(t-i)/n,y:(e-s)/a,width:r/n,height:o/a})}const o=[];for(let t=0,i=e.rangeCount;tt.stopPropagation()),{signal:i});const s=t=>{t.preventDefault(),this.#a._uiManager.editAltText(this.#a),this.#Wt&&this.#a._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:this.#Vt}})};return t.addEventListener("click",s,{capture:!0,signal:i}),t.addEventListener("keydown",(e=>{e.target===t&&"Enter"===e.key&&(this.#Ht=!0,s(e))}),{signal:i}),await this.#qt(),t}get#Vt(){return(this.#o?"added":null===this.#o&&this.guessedText&&"review")||"missing"}finish(){this.#Ot&&(this.#Ot.focus({focusVisible:this.#Ht}),this.#Ht=!1)}isEmpty(){return this.#Wt?null===this.#o:!this.#o&&!this.#Nt}hasData(){return this.#Wt?null!==this.#o||!!this.#Ut:this.isEmpty()}get guessedText(){return this.#Ut}async setGuessedText(t){null===this.#o&&(this.#Ut=t,this.#$t=await Mt._l10nPromise.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer")({generatedAltText:t}),this.#qt())}toggleAltTextBadge(t=!1){if(!this.#Wt||this.#o)return this.#jt?.remove(),void(this.#jt=null);if(!this.#jt){const t=this.#jt=document.createElement("div");t.className="noAltTextBadge",this.#a.div.append(t)}this.#jt.classList.toggle("hidden",!t)}serialize(t){let e=this.#o;return t||this.#Ut!==e||(e=this.#$t),{altText:e,decorative:this.#Nt,guessedText:this.#Ut,textWithDisclaimer:this.#$t}}get data(){return{altText:this.#o,decorative:this.#Nt}}set data({altText:t,decorative:e,guessedText:i,textWithDisclaimer:s,cancel:n=!1}){i&&(this.#Ut=i,this.#$t=s),this.#o===t&&this.#Nt===e||(n||(this.#o=t,this.#Nt=e),this.#qt())}toggle(t=!1){this.#Ot&&(!t&&this.#zt&&(clearTimeout(this.#zt),this.#zt=null),this.#Ot.disabled=!t)}shown(){this.#a._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:this.#Vt}})}destroy(){this.#Ot?.remove(),this.#Ot=null,this.#Bt=null,this.#jt?.remove(),this.#jt=null}async#qt(){const t=this.#Ot;if(!t)return;if(this.#Wt){if(t.classList.toggle("done",!!this.#o),Mt._l10nPromise.get(Mt.#Gt[this.#Vt]).then((e=>{t.setAttribute("aria-label",e);for(const i of t.childNodes)if(i.nodeType===Node.TEXT_NODE){i.textContent=e;break}})),!this.#o)return void this.#Bt?.remove()}else{if(!this.#o&&!this.#Nt)return t.classList.remove("done"),void this.#Bt?.remove();t.classList.add("done"),Mt._l10nPromise.get("pdfjs-editor-alt-text-edit-button-label").then((e=>{t.setAttribute("aria-label",e)}))}let e=this.#Bt;if(!e){this.#Bt=e=document.createElement("span"),e.className="tooltip",e.setAttribute("role","tooltip"),e.id=`alt-text-tooltip-${this.#a.id}`;const i=100,s=this.#a._uiManager._signal;s.addEventListener("abort",(()=>{clearTimeout(this.#zt),this.#zt=null}),{once:!0}),t.addEventListener("mouseenter",(()=>{this.#zt=setTimeout((()=>{this.#zt=null,this.#Bt.classList.add("show"),this.#a._reportTelemetry({action:"alt_text_tooltip"})}),i)}),{signal:s}),t.addEventListener("mouseleave",(()=>{this.#zt&&(clearTimeout(this.#zt),this.#zt=null),this.#Bt?.classList.remove("show")}),{signal:s})}e.innerText=this.#Nt?await Mt._l10nPromise.get("pdfjs-editor-alt-text-decorative-tooltip"):this.#o,e.parentNode||t.append(e),this.#a.getImageForAltText()?.setAttribute("aria-describedby",e.id)}}class kt{#Xt=null;#Kt=null;#o=null;#Yt=!1;#Qt=!1;#Jt=null;#Zt=null;#te=null;#ee="";#ie=!1;#se=null;#ne=!1;#ae=!1;#re=!1;#oe=null;#le=0;#he=0;#de=null;_editToolbar=null;_initialOptions=Object.create(null);_initialData=null;_isVisible=!0;_uiManager=null;_focusEventsAllowed=!0;static _l10nPromise=null;static _l10nResizer=null;#ce=!1;#ue=kt._zIndex++;static _borderLineWidth=-1;static _colorManager=new St;static _zIndex=1;static _telemetryTimeout=1e3;static get _resizerKeyboardManager(){const t=kt.prototype._resizeWithKeyboard,e=Tt.TRANSLATE_SMALL,i=Tt.TRANSLATE_BIG;return E(this,"_resizerKeyboardManager",new Et([[["ArrowLeft","mac+ArrowLeft"],t,{args:[-e,0]}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t,{args:[-i,0]}],[["ArrowRight","mac+ArrowRight"],t,{args:[e,0]}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t,{args:[i,0]}],[["ArrowUp","mac+ArrowUp"],t,{args:[0,-e]}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t,{args:[0,-i]}],[["ArrowDown","mac+ArrowDown"],t,{args:[0,e]}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t,{args:[0,i]}],[["Escape","mac+Escape"],kt.prototype._stopResizingWithKeyboard]]))}constructor(t){this.parent=t.parent,this.id=t.id,this.width=this.height=null,this.pageIndex=t.parent.pageIndex,this.name=t.name,this.div=null,this._uiManager=t.uiManager,this.annotationElementId=null,this._willKeepAspectRatio=!1,this._initialOptions.isCentered=t.isCentered,this._structTreeParentId=null;const{rotation:e,rawDims:{pageWidth:i,pageHeight:s,pageX:n,pageY:a}}=this.parent.viewport;this.rotation=e,this.pageRotation=(360+e-this._uiManager.viewParameters.rotation)%360,this.pageDimensions=[i,s],this.pageTranslation=[n,a];const[r,o]=this.parentDimensions;this.x=t.x/r,this.y=t.y/o,this.isAttachedToDOM=!1,this.deleted=!1}get editorType(){return Object.getPrototypeOf(this).constructor._type}static get _defaultLineColor(){return E(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){const e=new It({id:t.parent.getNextId(),parent:t.parent,uiManager:t._uiManager});e.annotationElementId=t.annotationElementId,e.deleted=!0,e._uiManager.addToAnnotationStorage(e)}static initialize(t,e,i){if(kt._l10nResizer||=Object.freeze({topLeft:"pdfjs-editor-resizer-top-left",topMiddle:"pdfjs-editor-resizer-top-middle",topRight:"pdfjs-editor-resizer-top-right",middleRight:"pdfjs-editor-resizer-middle-right",bottomRight:"pdfjs-editor-resizer-bottom-right",bottomMiddle:"pdfjs-editor-resizer-bottom-middle",bottomLeft:"pdfjs-editor-resizer-bottom-left",middleLeft:"pdfjs-editor-resizer-middle-left"}),kt._l10nPromise||=new Map([...["pdfjs-editor-alt-text-button-label","pdfjs-editor-alt-text-edit-button-label","pdfjs-editor-alt-text-decorative-tooltip","pdfjs-editor-new-alt-text-added-button-label","pdfjs-editor-new-alt-text-missing-button-label","pdfjs-editor-new-alt-text-to-review-button-label"].map((e=>[e,t.get(e)])),...["pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer"].map((e=>[e,t.get.bind(t,e)]))]),i?.strings)for(const e of i.strings)kt._l10nPromise.set(e,t.get(e));if(-1!==kt._borderLineWidth)return;const s=getComputedStyle(document.documentElement);kt._borderLineWidth=parseFloat(s.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,e){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return!1}static paste(t,e){_("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return this.#ce}set _isDraggable(t){this.#ce=t,this.div?.classList.toggle("draggable",t)}get isEnterHandled(){return!0}center(){const[t,e]=this.pageDimensions;switch(this.parentRotation){case 90:this.x-=this.height*e/(2*t),this.y+=this.width*t/(2*e);break;case 180:this.x+=this.width/2,this.y+=this.height/2;break;case 270:this.x+=this.height*e/(2*t),this.y-=this.width*t/(2*e);break;default:this.x-=this.width/2,this.y-=this.height/2}this.fixAndSetPosition()}addCommands(t){this._uiManager.addCommands(t)}get currentLayer(){return this._uiManager.currentLayer}setInBackground(){this.div.style.zIndex=0}setInForeground(){this.div.style.zIndex=this.#ue}setParent(t){null!==t?(this.pageIndex=t.pageIndex,this.pageDimensions=t.pageDimensions):this.#pe(),this.parent=t}focusin(t){this._focusEventsAllowed&&(this.#ie?this.#ie=!1:this.parent.setSelected(this))}focusout(t){this._focusEventsAllowed&&this.isAttachedToDOM&&(t.relatedTarget?.closest(`#${this.id}`)||(t.preventDefault(),this.parent?.isMultipleSelection||this.commitOrRemove()))}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.addToAnnotationStorage()}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(t,e,i,s){const[n,a]=this.parentDimensions;[i,s]=this.screenToPageTranslation(i,s),this.x=(t+i)/n,this.y=(e+s)/a,this.fixAndSetPosition()}#ge([t,e],i,s){[i,s]=this.screenToPageTranslation(i,s),this.x+=i/t,this.y+=s/e,this.fixAndSetPosition()}translate(t,e){this.#ge(this.parentDimensions,t,e)}translateInPage(t,e){this.#se||=[this.x,this.y],this.#ge(this.pageDimensions,t,e),this.div.scrollIntoView({block:"nearest"})}drag(t,e){this.#se||=[this.x,this.y];const[i,s]=this.parentDimensions;if(this.x+=t/i,this.y+=e/s,this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){const{x:t,y:e}=this.div.getBoundingClientRect();this.parent.findNewParent(this,t,e)&&(this.x-=Math.floor(this.x),this.y-=Math.floor(this.y))}let{x:n,y:a}=this;const[r,o]=this.getBaseTranslation();n+=r,a+=o,this.div.style.left=`${(100*n).toFixed(2)}%`,this.div.style.top=`${(100*a).toFixed(2)}%`,this.div.scrollIntoView({block:"nearest"})}get _hasBeenMoved(){return!!this.#se&&(this.#se[0]!==this.x||this.#se[1]!==this.y)}getBaseTranslation(){const[t,e]=this.parentDimensions,{_borderLineWidth:i}=kt,s=i/t,n=i/e;switch(this.rotation){case 90:return[-s,n];case 180:return[s,n];case 270:return[s,-n];default:return[-s,-n]}}get _mustFixPosition(){return!0}fixAndSetPosition(t=this.rotation){const[e,i]=this.pageDimensions;let{x:s,y:n,width:a,height:r}=this;if(a*=e,r*=i,s*=e,n*=i,this._mustFixPosition)switch(t){case 0:s=Math.max(0,Math.min(e-a,s)),n=Math.max(0,Math.min(i-r,n));break;case 90:s=Math.max(0,Math.min(e-r,s)),n=Math.min(i,Math.max(a,n));break;case 180:s=Math.min(e,Math.max(a,s)),n=Math.min(i,Math.max(r,n));break;case 270:s=Math.min(e,Math.max(r,s)),n=Math.max(0,Math.min(i-a,n))}this.x=s/=e,this.y=n/=i;const[o,l]=this.getBaseTranslation();s+=o,n+=l;const{style:h}=this.div;h.left=`${(100*s).toFixed(2)}%`,h.top=`${(100*n).toFixed(2)}%`,this.moveInDOM()}static#me(t,e,i){switch(i){case 90:return[e,-t];case 180:return[-t,-e];case 270:return[-e,t];default:return[t,e]}}screenToPageTranslation(t,e){return kt.#me(t,e,this.parentRotation)}pageTranslationToScreen(t,e){return kt.#me(t,e,360-this.parentRotation)}#fe(t){switch(t){case 90:{const[t,e]=this.pageDimensions;return[0,-t/e,e/t,0]}case 180:return[-1,0,0,-1];case 270:{const[t,e]=this.pageDimensions;return[0,t/e,-e/t,0]}default:return[1,0,0,1]}}get parentScale(){return this._uiManager.viewParameters.realScale}get parentRotation(){return(this._uiManager.viewParameters.rotation+this.pageRotation)%360}get parentDimensions(){const{parentScale:t,pageDimensions:[e,i]}=this;return[e*t,i*t]}setDims(t,e){const[i,s]=this.parentDimensions;this.div.style.width=`${(100*t/i).toFixed(2)}%`,this.#Qt||(this.div.style.height=`${(100*e/s).toFixed(2)}%`)}fixDims(){const{style:t}=this.div,{height:e,width:i}=t,s=i.endsWith("%"),n=!this.#Qt&&e.endsWith("%");if(s&&n)return;const[a,r]=this.parentDimensions;s||(t.width=`${(100*parseFloat(i)/a).toFixed(2)}%`),this.#Qt||n||(t.height=`${(100*parseFloat(e)/r).toFixed(2)}%`)}getInitialTranslation(){return[0,0]}#be(){if(this.#Jt)return;this.#Jt=document.createElement("div"),this.#Jt.classList.add("resizers");const t=this._willKeepAspectRatio?["topLeft","topRight","bottomRight","bottomLeft"]:["topLeft","topMiddle","topRight","middleRight","bottomRight","bottomMiddle","bottomLeft","middleLeft"],e=this._uiManager._signal;for(const i of t){const t=document.createElement("div");this.#Jt.append(t),t.classList.add("resizer",i),t.setAttribute("data-resizer-name",i),t.addEventListener("pointerdown",this.#ve.bind(this,i),{signal:e}),t.addEventListener("contextmenu",ht,{signal:e}),t.tabIndex=-1}this.div.prepend(this.#Jt)}#ve(t,e){e.preventDefault();const{isMac:i}=O.platform;if(0!==e.button||e.ctrlKey&&i)return;this.#o?.toggle(!1);const s=this._isDraggable;this._isDraggable=!1;const n=new AbortController,a=this._uiManager.combinedSignal(n);this.parent.togglePointerEvents(!1),window.addEventListener("pointermove",this.#Ae.bind(this,t),{passive:!0,capture:!0,signal:a}),window.addEventListener("contextmenu",ht,{signal:a});const r=this.x,o=this.y,l=this.width,h=this.height,d=this.parent.div.style.cursor,c=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(e.target).cursor;const u=()=>{n.abort(),this.parent.togglePointerEvents(!0),this.#o?.toggle(!0),this._isDraggable=s,this.parent.div.style.cursor=d,this.div.style.cursor=c,this.#ye(r,o,l,h)};window.addEventListener("pointerup",u,{signal:a}),window.addEventListener("blur",u,{signal:a})}#ye(t,e,i,s){const n=this.x,a=this.y,r=this.width,o=this.height;n===t&&a===e&&r===i&&o===s||this.addCommands({cmd:()=>{this.width=r,this.height=o,this.x=n,this.y=a;const[t,e]=this.parentDimensions;this.setDims(t*r,e*o),this.fixAndSetPosition()},undo:()=>{this.width=i,this.height=s,this.x=t,this.y=e;const[n,a]=this.parentDimensions;this.setDims(n*i,a*s),this.fixAndSetPosition()},mustExec:!0})}#Ae(t,e){const[i,s]=this.parentDimensions,n=this.x,a=this.y,r=this.width,o=this.height,l=kt.MIN_SIZE/i,h=kt.MIN_SIZE/s,d=t=>Math.round(1e4*t)/1e4,c=this.#fe(this.rotation),u=(t,e)=>[c[0]*t+c[2]*e,c[1]*t+c[3]*e],p=this.#fe(360-this.rotation);let g,m,f=!1,b=!1;switch(t){case"topLeft":f=!0,g=(t,e)=>[0,0],m=(t,e)=>[t,e];break;case"topMiddle":g=(t,e)=>[t/2,0],m=(t,e)=>[t/2,e];break;case"topRight":f=!0,g=(t,e)=>[t,0],m=(t,e)=>[0,e];break;case"middleRight":b=!0,g=(t,e)=>[t,e/2],m=(t,e)=>[0,e/2];break;case"bottomRight":f=!0,g=(t,e)=>[t,e],m=(t,e)=>[0,0];break;case"bottomMiddle":g=(t,e)=>[t/2,e],m=(t,e)=>[t/2,0];break;case"bottomLeft":f=!0,g=(t,e)=>[0,e],m=(t,e)=>[t,0];break;case"middleLeft":b=!0,g=(t,e)=>[0,e/2],m=(t,e)=>[t,e/2]}const v=g(r,o),A=m(r,o);let y=u(...A);const w=d(n+y[0]),_=d(a+y[1]);let x=1,C=1,[E,S]=this.screenToPageTranslation(e.movementX,e.movementY);var T,M;if([E,S]=(T=E/i,M=S/s,[p[0]*T+p[2]*M,p[1]*T+p[3]*M]),f){const t=Math.hypot(r,o);x=C=Math.max(Math.min(Math.hypot(A[0]-v[0]-E,A[1]-v[1]-S)/t,1/r,1/o),l/r,h/o)}else b?x=Math.max(l,Math.min(1,Math.abs(A[0]-v[0]-E)))/r:C=Math.max(h,Math.min(1,Math.abs(A[1]-v[1]-S)))/o;const k=d(r*x),I=d(o*C);y=u(...m(k,I));const P=w-y[0],R=_-y[1];this.width=k,this.height=I,this.x=P,this.y=R,this.setDims(i*k,s*I),this.fixAndSetPosition()}altTextFinish(){this.#o?.finish()}async addEditToolbar(){return this._editToolbar||this.#ae||(this._editToolbar=new At(this),this.div.append(this._editToolbar.render()),this.#o&&await this._editToolbar.addAltText(this.#o)),this._editToolbar}removeEditToolbar(){this._editToolbar&&(this._editToolbar.remove(),this._editToolbar=null,this.#o?.destroy())}addContainer(t){const e=this._editToolbar?.div;e?e.before(t):this.div.append(t)}getClientDimensions(){return this.div.getBoundingClientRect()}async addAltTextButton(){this.#o||(Mt.initialize(kt._l10nPromise),this.#o=new Mt(this),this.#Xt&&(this.#o.data=this.#Xt,this.#Xt=null),await this.addEditToolbar())}get altTextData(){return this.#o?.data}set altTextData(t){this.#o&&(this.#o.data=t)}get guessedAltText(){return this.#o?.guessedText}async setGuessedAltText(t){await(this.#o?.setGuessedText(t))}serializeAltText(t){return this.#o?.serialize(t)}hasAltText(){return!!this.#o&&!this.#o.isEmpty()}hasAltTextData(){return this.#o?.hasData()??!1}render(){this.div=document.createElement("div"),this.div.setAttribute("data-editor-rotation",(360-this.rotation)%360),this.div.className=this.name,this.div.setAttribute("id",this.id),this.div.tabIndex=this.#Yt?-1:0,this._isVisible||this.div.classList.add("hidden"),this.setInForeground(),this.#we();const[t,e]=this.parentDimensions;this.parentRotation%180!=0&&(this.div.style.maxWidth=`${(100*e/t).toFixed(2)}%`,this.div.style.maxHeight=`${(100*t/e).toFixed(2)}%`);const[i,s]=this.getInitialTranslation();return this.translate(i,s),wt(this,this.div,["pointerdown"]),this.div}pointerdown(t){const{isMac:e}=O.platform;0!==t.button||t.ctrlKey&&e?t.preventDefault():(this.#ie=!0,this._isDraggable?this.#_e(t):this.#xe(t))}#xe(t){const{isMac:e}=O.platform;t.ctrlKey&&!e||t.shiftKey||t.metaKey&&e?this.parent.toggleSelected(this):this.parent.setSelected(this)}#_e(t){const e=this._uiManager.isSelected(this);this._uiManager.setUpDragSession();const i=new AbortController,s=this._uiManager.combinedSignal(i);if(e){this.div.classList.add("moving"),this.#le=t.clientX,this.#he=t.clientY;const e=t=>{const{clientX:e,clientY:i}=t,[s,n]=this.screenToPageTranslation(e-this.#le,i-this.#he);this.#le=e,this.#he=i,this._uiManager.dragSelectedEditors(s,n)};window.addEventListener("pointermove",e,{passive:!0,capture:!0,signal:s})}const n=()=>{i.abort(),e&&this.div.classList.remove("moving"),this.#ie=!1,this._uiManager.endDragSession()||this.#xe(t)};window.addEventListener("pointerup",n,{signal:s}),window.addEventListener("blur",n,{signal:s})}moveInDOM(){this.#oe&&clearTimeout(this.#oe),this.#oe=setTimeout((()=>{this.#oe=null,this.parent?.moveEditorInDOM(this)}),0)}_setParentAndPosition(t,e,i){t.changeParent(this),this.x=e,this.y=i,this.fixAndSetPosition()}getRect(t,e,i=this.rotation){const s=this.parentScale,[n,a]=this.pageDimensions,[r,o]=this.pageTranslation,l=t/s,h=e/s,d=this.x*n,c=this.y*a,u=this.width*n,p=this.height*a;switch(i){case 0:return[d+l+r,a-c-h-p+o,d+l+u+r,a-c-h+o];case 90:return[d+h+r,a-c+l+o,d+h+p+r,a-c+l+u+o];case 180:return[d-l-u+r,a-c+h+o,d-l+r,a-c+h+p+o];case 270:return[d-h-p+r,a-c-l-u+o,d-h+r,a-c-l+o];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(t,e){const[i,s,n,a]=t,r=n-i,o=a-s;switch(this.rotation){case 0:return[i,e-a,r,o];case 90:return[i,e-s,o,r];case 180:return[n,e-s,r,o];case 270:return[n,e-a,o,r];default:throw new Error("Invalid rotation")}}onceAdded(){}isEmpty(){return!1}enableEditMode(){this.#ae=!0}disableEditMode(){this.#ae=!1}isInEditMode(){return this.#ae}shouldGetKeyboardEvents(){return this.#re}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}#we(){if(this.#te||!this.div)return;this.#te=new AbortController;const t=this._uiManager.combinedSignal(this.#te);this.div.addEventListener("focusin",this.focusin.bind(this),{signal:t}),this.div.addEventListener("focusout",this.focusout.bind(this),{signal:t})}rebuild(){this.#we()}rotate(t){}serializeDeleted(){return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex,popupRef:this._initialData?.popupRef||""}}serialize(t=!1,e=null){_("An editor must be serializable")}static async deserialize(t,e,i){const s=new this.prototype.constructor({parent:e,id:e.getNextId(),uiManager:i});s.rotation=t.rotation,s.#Xt=t.accessibilityData;const[n,a]=s.pageDimensions,[r,o,l,h]=s.getRectInCurrentCoords(t.rect,a);return s.x=r/n,s.y=o/a,s.width=l/n,s.height=h/a,s}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||null!==this.serialize())}remove(){if(this.#te?.abort(),this.#te=null,this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),this.#oe&&(clearTimeout(this.#oe),this.#oe=null),this.#pe(),this.removeEditToolbar(),this.#de){for(const t of this.#de.values())clearTimeout(t);this.#de=null}this.parent=null}get isResizable(){return!1}makeResizable(){this.isResizable&&(this.#be(),this.#Jt.classList.remove("hidden"),wt(this,this.div,["keydown"]))}get toolbarPosition(){return null}keydown(t){if(!this.isResizable||t.target!==this.div||"Enter"!==t.key)return;this._uiManager.setSelected(this),this.#Zt={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const e=this.#Jt.children;if(!this.#Kt){this.#Kt=Array.from(e);const t=this.#Ce.bind(this),i=this.#Ee.bind(this),s=this._uiManager._signal;for(const e of this.#Kt){const n=e.getAttribute("data-resizer-name");e.setAttribute("role","spinbutton"),e.addEventListener("keydown",t,{signal:s}),e.addEventListener("blur",i,{signal:s}),e.addEventListener("focus",this.#Se.bind(this,n),{signal:s}),e.setAttribute("data-l10n-id",kt._l10nResizer[n])}}const i=this.#Kt[0];let s=0;for(const t of e){if(t===i)break;s++}const n=(360-this.rotation+this.parentRotation)%360/90*(this.#Kt.length/4);if(n!==s){if(ns)for(let t=0;t{this.div?.classList.contains("selectedEditor")&&this._editToolbar?.show()}))}unselect(){this.#Jt?.classList.add("hidden"),this.div?.classList.remove("selectedEditor"),this.div?.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0}),this._editToolbar?.hide(),this.#o?.toggleAltTextBadge(!0)}updateParams(t,e){}disableEditing(){}enableEditing(){}enterInEditMode(){}getImageForAltText(){return null}get contentDiv(){return this.div}get isEditing(){return this.#ne}set isEditing(t){this.#ne=t,this.parent&&(t?(this.parent.setSelected(this),this.parent.setActiveEditor(this)):this.parent.setActiveEditor(null))}setAspectRatio(t,e){this.#Qt=!0;const i=t/e,{style:s}=this.div;s.aspectRatio=i,s.height="auto"}static get MIN_SIZE(){return 16}static canCreateNewEmptyEditor(){return!0}get telemetryInitialData(){return{action:"added"}}get telemetryFinalData(){return null}_reportTelemetry(t,e=!1){if(e){this.#de||=new Map;const{action:e}=t;let i=this.#de.get(e);return i&&clearTimeout(i),i=setTimeout((()=>{this._reportTelemetry(t),this.#de.delete(e),0===this.#de.size&&(this.#de=null)}),kt._telemetryTimeout),void this.#de.set(e,i)}t.type||=this.editorType,this._uiManager._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:t}})}show(t=this._isVisible){this.div.classList.toggle("hidden",!t),this._isVisible=t}enable(){this.div&&(this.div.tabIndex=0),this.#Yt=!1}disable(){this.div&&(this.div.tabIndex=-1),this.#Yt=!0}renderAnnotationElement(t){let e=t.container.querySelector(".annotationContent");if(e){if("CANVAS"===e.nodeName){const t=e;e=document.createElement("div"),e.classList.add("annotationContent",this.editorType),t.before(e)}}else e=document.createElement("div"),e.classList.add("annotationContent",this.editorType),t.container.prepend(e);return e}resetAnnotationElement(t){const{firstChild:e}=t.container;"DIV"===e?.nodeName&&e.classList.contains("annotationContent")&&e.remove()}}class It extends kt{constructor(t){super(t),this.annotationElementId=t.annotationElementId,this.deleted=!0}serialize(){return this.serializeDeleted()}}const Pt=3285377520,Rt=4294901760,Dt=65535;class Lt{constructor(t){this.h1=t?4294967295&t:Pt,this.h2=t?4294967295&t:Pt}update(t){let e,i;if("string"==typeof t){e=new Uint8Array(2*t.length),i=0;for(let s=0,n=t.length;s>>8,e[i++]=255&n)}}else{if(!ArrayBuffer.isView(t))throw new Error("Invalid data format, must be a string or TypedArray.");e=t.slice(),i=e.byteLength}const s=i>>2,n=i-4*s,a=new Uint32Array(e.buffer,0,s);let r=0,o=0,l=this.h1,h=this.h2;const d=3432918353,c=461845907,u=11601,p=13715;for(let t=0;t>>17,r=r*c&Rt|r*p&Dt,l^=r,l=l<<13|l>>>19,l=5*l+3864292196):(o=a[t],o=o*d&Rt|o*u&Dt,o=o<<15|o>>>17,o=o*c&Rt|o*p&Dt,h^=o,h=h<<13|h>>>19,h=5*h+3864292196);switch(r=0,n){case 3:r^=e[4*s+2]<<16;case 2:r^=e[4*s+1]<<8;case 1:r^=e[4*s],r=r*d&Rt|r*u&Dt,r=r<<15|r>>>17,r=r*c&Rt|r*p&Dt,1&s?l^=r:h^=r}this.h1=l,this.h2=h}hexdigest(){let t=this.h1,e=this.h2;return t^=e>>>1,t=3981806797*t&Rt|36045*t&Dt,e=4283543511*e&Rt|(2950163797*(e<<16|t>>>16)&Rt)>>>16,t^=e>>>1,t=444984403*t&Rt|60499*t&Dt,e=3301882366*e&Rt|(3120437893*(e<<16|t>>>16)&Rt)>>>16,t^=e>>>1,(t>>>0).toString(16).padStart(8,"0")+(e>>>0).toString(16).padStart(8,"0")}}const Ft=Object.freeze({map:null,hash:"",transfer:void 0});class Nt{#Me=!1;#ke=null;#Ie=new Map;constructor(){this.onSetModified=null,this.onResetModified=null,this.onAnnotationEditor=null}getValue(t,e){const i=this.#Ie.get(t);return void 0===i?e:Object.assign(e,i)}getRawValue(t){return this.#Ie.get(t)}remove(t){if(this.#Ie.delete(t),0===this.#Ie.size&&this.resetModified(),"function"==typeof this.onAnnotationEditor){for(const t of this.#Ie.values())if(t instanceof kt)return;this.onAnnotationEditor(null)}}setValue(t,e){const i=this.#Ie.get(t);let s=!1;if(void 0!==i)for(const[t,n]of Object.entries(e))i[t]!==n&&(s=!0,i[t]=n);else s=!0,this.#Ie.set(t,e);s&&this.#Pe(),e instanceof kt&&"function"==typeof this.onAnnotationEditor&&this.onAnnotationEditor(e.constructor._type)}has(t){return this.#Ie.has(t)}getAll(){return this.#Ie.size>0?N(this.#Ie):null}setAll(t){for(const[e,i]of Object.entries(t))this.setValue(e,i)}get size(){return this.#Ie.size}#Pe(){this.#Me||(this.#Me=!0,"function"==typeof this.onSetModified&&this.onSetModified())}resetModified(){this.#Me&&(this.#Me=!1,"function"==typeof this.onResetModified&&this.onResetModified())}get print(){return new Ot(this)}get serializable(){if(0===this.#Ie.size)return Ft;const t=new Map,e=new Lt,i=[],s=Object.create(null);let n=!1;for(const[i,a]of this.#Ie){const r=a instanceof kt?a.serialize(!1,s):a;r&&(t.set(i,r),e.update(`${i}:${JSON.stringify(r)}`),n||=!!r.bitmap)}if(n)for(const e of t.values())e.bitmap&&i.push(e.bitmap);return t.size>0?{map:t,hash:e.hexdigest(),transfer:i}:Ft}get editorStats(){let t=null;const e=new Map;for(const i of this.#Ie.values()){if(!(i instanceof kt))continue;const s=i.telemetryFinalData;if(!s)continue;const{type:n}=s;e.has(n)||e.set(n,Object.getPrototypeOf(i).constructor),t||=Object.create(null);const a=t[n]||=new Map;for(const[t,e]of Object.entries(s)){if("type"===t)continue;let i=a.get(t);i||(i=new Map,a.set(t,i));const s=i.get(e)??0;i.set(e,s+1)}}for(const[i,s]of e)t[i]=s.computeTelemetryFinalData(t[i]);return t}resetModifiedIds(){this.#ke=null}get modifiedIds(){if(this.#ke)return this.#ke;const t=[];for(const e of this.#Ie.values())e instanceof kt&&e.annotationElementId&&e.serialize()&&t.push(e.annotationElementId);return this.#ke={ids:new Set(t),hash:t.join(",")}}}class Ot extends Nt{#Re;constructor(t){super();const{map:e,hash:i,transfer:s}=t.serializable,n=structuredClone(e,s?{transfer:s}:null);this.#Re={map:n,hash:i,transfer:s}}get print(){_("Should not call PrintAnnotationStorage.print")}get serializable(){return this.#Re}get modifiedIds(){return E(this,"modifiedIds",{ids:new Set,hash:""})}}class Bt{#De=new Set;constructor({ownerDocument:t=globalThis.document,styleElement:e=null}){this._document=t,this.nativeFontFaces=new Set,this.styleElement=null,this.loadingRequests=[],this.loadTestFontId=0}addNativeFontFace(t){this.nativeFontFaces.add(t),this._document.fonts.add(t)}removeNativeFontFace(t){this.nativeFontFaces.delete(t),this._document.fonts.delete(t)}insertRule(t){this.styleElement||(this.styleElement=this._document.createElement("style"),this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement));const e=this.styleElement.sheet;e.insertRule(t,e.cssRules.length)}clear(){for(const t of this.nativeFontFaces)this._document.fonts.delete(t);this.nativeFontFaces.clear(),this.#De.clear(),this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}async loadSystemFont({systemFontInfo:t,_inspectFont:e}){if(t&&!this.#De.has(t.loadedName))if(x(!this.disableFontFace,"loadSystemFont shouldn't be called when `disableFontFace` is set."),this.isFontLoadingAPISupported){const{loadedName:i,src:s,style:n}=t,a=new FontFace(i,s,n);this.addNativeFontFace(a);try{await a.load(),this.#De.add(i),e?.(t)}catch{w(`Cannot load system font: ${t.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(a)}}else _("Not implemented: loadSystemFont without the Font Loading API.")}async bind(t){if(t.attached||t.missingFile&&!t.systemFontInfo)return;if(t.attached=!0,t.systemFontInfo)return void await this.loadSystemFont(t);if(this.isFontLoadingAPISupported){const e=t.createNativeFontFace();if(e){this.addNativeFontFace(e);try{await e.loaded}catch(i){throw w(`Failed to load font '${e.family}': '${i}'.`),t.disableFontFace=!0,i}}return}const e=t.createFontFaceRule();if(e){if(this.insertRule(e),this.isSyncFontLoadingSupported)return;await new Promise((e=>{const i=this._queueLoadingCallback(e);this._prepareFontLoadEvent(t,i)}))}}get isFontLoadingAPISupported(){return E(this,"isFontLoadingAPISupported",!!this._document?.fonts)}get isSyncFontLoadingSupported(){let t=!1;return(n||"undefined"!=typeof navigator&&"string"==typeof navigator?.userAgent&&/Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent))&&(t=!0),E(this,"isSyncFontLoadingSupported",t)}_queueLoadingCallback(t){const{loadingRequests:e}=this,i={done:!1,complete:function(){for(x(!i.done,"completeRequest() cannot be called twice."),i.done=!0;e.length>0&&e[0].done;){const t=e.shift();setTimeout(t.callback,0)}},callback:t};return e.push(i),i}get _loadTestFont(){return E(this,"_loadTestFont",atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA=="))}_prepareFontLoadEvent(t,e){function i(t,e){return t.charCodeAt(e)<<24|t.charCodeAt(e+1)<<16|t.charCodeAt(e+2)<<8|255&t.charCodeAt(e+3)}function s(t,e,i,s){return t.substring(0,e)+s+t.substring(e+i)}let n,a;const r=this._document.createElement("canvas");r.width=1,r.height=1;const o=r.getContext("2d");let l=0;const h=`lt${Date.now()}${this.loadTestFontId++}`;let d=this._loadTestFont;d=s(d,976,h.length,h);const c=1482184792;let u=i(d,16);for(n=0,a=h.length-3;n>24&255,p>>16&255,p>>8&255,255&p)));const g=`@font-face {font-family:"${h}";src:url(data:font/opentype;base64,${btoa(d)});}`;this.insertRule(g);const m=this._document.createElement("div");m.style.visibility="hidden",m.style.width=m.style.height="10px",m.style.position="absolute",m.style.top=m.style.left="0px";for(const e of[t.loadedName,h]){const t=this._document.createElement("span");t.textContent="Hi",t.style.fontFamily=e,m.append(t)}this._document.body.append(m),function t(e,i){if(++l>30)return w("Load test font never loaded."),void i();o.font="30px "+e,o.fillText(".",0,20),o.getImageData(0,0,1,1).data[3]>0?i():setTimeout(t.bind(null,e,i))}(h,(()=>{m.remove(),e.complete()}))}}class zt{constructor(t,{disableFontFace:e=!1,inspectFont:i=null}){this.compiledGlyphs=Object.create(null);for(const e in t)this[e]=t[e];this.disableFontFace=!0===e,this._inspectFont=i}createNativeFontFace(){if(!this.data||this.disableFontFace)return null;let t;if(this.cssFontInfo){const e={weight:this.cssFontInfo.fontWeight};this.cssFontInfo.italicAngle&&(e.style=`oblique ${this.cssFontInfo.italicAngle}deg`),t=new FontFace(this.cssFontInfo.fontFamily,this.data,e)}else t=new FontFace(this.loadedName,this.data,{});return this._inspectFont?.(this),t}createFontFaceRule(){if(!this.data||this.disableFontFace)return null;const t=L(this.data),e=`url(data:${this.mimetype};base64,${btoa(t)});`;let i;if(this.cssFontInfo){let t=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(t+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`),i=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${t}src:${e}}`}else i=`@font-face {font-family:"${this.loadedName}";src:${e}}`;return this._inspectFont?.(this,e),i}getPathGenerator(t,e){if(void 0!==this.compiledGlyphs[e])return this.compiledGlyphs[e];let i;try{i=t.get(this.loadedName+"_path_"+e)}catch(t){w(`getPathGenerator - ignoring character: "${t}".`)}if(!Array.isArray(i)||0===i.length)return this.compiledGlyphs[e]=function(t,e){};const s=[];for(let t=0,e=i.length;tt.bezierCurveTo(e,n,a,r,o,l))),t+=6}break;case 1:{const[e,n]=i.slice(t,t+2);s.push((t=>t.moveTo(e,n))),t+=2}break;case 2:{const[e,n]=i.slice(t,t+2);s.push((t=>t.lineTo(e,n))),t+=2}break;case 3:{const[e,n,a,r]=i.slice(t,t+4);s.push((t=>t.quadraticCurveTo(e,n,a,r))),t+=4}break;case 4:s.push((t=>t.restore()));break;case 5:s.push((t=>t.save()));break;case 6:x(2===s.length,"Scale command is only valid at the third position.");break;case 7:{const[e,n,a,r,o,l]=i.slice(t,t+6);s.push((t=>t.transform(e,n,a,r,o,l))),t+=6}break;case 8:{const[e,n]=i.slice(t,t+2);s.push((t=>t.translate(e,n))),t+=2}}return this.compiledGlyphs[e]=function(t,e){s[0](t),s[1](t),t.scale(e,-e);for(let e=2,i=s.length;e{const t=await import("fs"),e=await import("http"),i=await import("https"),s=await import("url");return new Map(Object.entries({fs:t,http:e,https:i,url:s,canvas:void 0,path2d:void 0}))})().then((t=>{jt=t,Ht.resolve()}),(t=>{w(`loadPackages: ${t}`),jt=new Map,Ht.resolve()}))}class Ut{static get promise(){return Ht.promise}static get(t){return jt?.get(t)}}const $t=function(t){return Ut.get("fs").promises.readFile(t).then((t=>new Uint8Array(t)))},Wt="Fill",Gt="Stroke",Vt="Shading";function qt(t,e){if(!e)return;const i=e[2]-e[0],s=e[3]-e[1],n=new Path2D;n.rect(e[0],e[1],i,s),t.clip(n)}class Xt{getPattern(){_("Abstract method `getPattern` called.")}}class Kt extends Xt{constructor(t){super(),this._type=t[1],this._bbox=t[2],this._colorStops=t[3],this._p0=t[4],this._p1=t[5],this._r0=t[6],this._r1=t[7],this.matrix=null}_createGradient(t){let e;"axial"===this._type?e=t.createLinearGradient(this._p0[0],this._p0[1],this._p1[0],this._p1[1]):"radial"===this._type&&(e=t.createRadialGradient(this._p0[0],this._p0[1],this._r0,this._p1[0],this._p1[1],this._r1));for(const t of this._colorStops)e.addColorStop(t[0],t[1]);return e}getPattern(t,e,i,s){let n;if(s===Gt||s===Wt){const a=e.current.getClippedPathBoundingBox(s,mt(t))||[0,0,0,0],r=Math.ceil(a[2]-a[0])||1,o=Math.ceil(a[3]-a[1])||1,l=e.cachedCanvases.getCanvas("pattern",r,o),h=l.context;h.clearRect(0,0,h.canvas.width,h.canvas.height),h.beginPath(),h.rect(0,0,h.canvas.width,h.canvas.height),h.translate(-a[0],-a[1]),i=z.transform(i,[1,0,0,1,a[0],a[1]]),h.transform(...e.baseTransform),this.matrix&&h.transform(...this.matrix),qt(h,this._bbox),h.fillStyle=this._createGradient(h),h.fill(),n=t.createPattern(l.canvas,"no-repeat");const d=new DOMMatrix(i);n.setTransform(d)}else qt(t,this._bbox),n=this._createGradient(t);return n}}function Yt(t,e,i,s,n,a,r,o){const l=e.coords,h=e.colors,d=t.data,c=4*t.width;let u;l[i+1]>l[s+1]&&(u=i,i=s,s=u,u=a,a=r,r=u),l[s+1]>l[n+1]&&(u=s,s=n,n=u,u=r,r=o,o=u),l[i+1]>l[s+1]&&(u=i,i=s,s=u,u=a,a=r,r=u);const p=(l[i]+e.offsetX)*e.scaleX,g=(l[i+1]+e.offsetY)*e.scaleY,m=(l[s]+e.offsetX)*e.scaleX,f=(l[s+1]+e.offsetY)*e.scaleY,b=(l[n]+e.offsetX)*e.scaleX,v=(l[n+1]+e.offsetY)*e.scaleY;if(g>=v)return;const A=h[a],y=h[a+1],w=h[a+2],_=h[r],x=h[r+1],C=h[r+2],E=h[o],S=h[o+1],T=h[o+2],M=Math.round(g),k=Math.round(v);let I,P,R,D,L,F,N,O;for(let t=M;t<=k;t++){if(tv?1:f===v?0:(f-t)/(f-v),I=m-(m-b)*e,P=_-(_-E)*e,R=x-(x-S)*e,D=C-(C-T)*e}let e;e=tv?1:(g-t)/(g-v),L=p-(p-b)*e,F=A-(A-E)*e,N=y-(y-S)*e,O=w-(w-T)*e;const i=Math.round(Math.min(I,L)),s=Math.round(Math.max(I,L));let n=c*t+4*i;for(let t=i;t<=s;t++)e=(I-t)/(I-L),e<0?e=0:e>1&&(e=1),d[n++]=P-(P-F)*e|0,d[n++]=R-(R-N)*e|0,d[n++]=D-(D-O)*e|0,d[n++]=255}}function Qt(t,e,i){const s=e.coords,n=e.colors;let a,r;switch(e.type){case"lattice":const o=e.verticesPerRow,l=Math.floor(s.length/o)-1,h=o-1;for(a=0;a=Math.ceil(p*b)?A=o:_=!0,E>=Math.ceil(g*v)?w=l:x=!0;const S=this.getSizeAndScale(A,this.ctx.canvas.width,b),T=this.getSizeAndScale(w,this.ctx.canvas.height,v),M=t.cachedCanvases.getCanvas("pattern",S.size,T.size),k=M.context,I=r.createCanvasGraphics(k);if(I.groupLevel=t.groupLevel,this.setFillAndStrokeStyleToContext(I,s,a),k.translate(-S.scale*h,-T.scale*d),I.transform(S.scale,0,0,T.scale,0,0),k.save(),this.clipBbox(I,h,d,c,u),I.baseTransform=mt(I.ctx),I.executeOperatorList(i),I.endDrawing(),k.restore(),_||x){const e=M.canvas;_&&(A=o),x&&(w=l);const i=this.getSizeAndScale(A,this.ctx.canvas.width,b),s=this.getSizeAndScale(w,this.ctx.canvas.height,v),n=i.size,a=s.size,r=t.cachedCanvases.getCanvas("pattern-workaround",n,a),c=r.context,u=_?Math.floor(p/o):0,m=x?Math.floor(g/l):0;for(let t=0;t<=u;t++)for(let i=0;i<=m;i++)c.drawImage(e,n*t,a*i,n,a,0,0,n,a);return{canvas:r.canvas,scaleX:i.scale,scaleY:s.scale,offsetX:h,offsetY:d}}return{canvas:M.canvas,scaleX:S.scale,scaleY:T.scale,offsetX:h,offsetY:d}}getSizeAndScale(t,e,i){const s=Math.max(te.MAX_PATTERN_SIZE,e);let n=Math.ceil(t*i);return n>=s?n=s:i=n/t,{scale:i,size:n}}clipBbox(t,e,i,s,n){const a=s-e,r=n-i;t.ctx.rect(e,i,a,r),t.current.updateRectMinMax(mt(t.ctx),[e,i,s,n]),t.clip(),t.endPath()}setFillAndStrokeStyleToContext(t,e,i){const s=t.ctx,n=t.current;switch(e){case 1:const t=this.ctx;s.fillStyle=t.fillStyle,s.strokeStyle=t.strokeStyle,n.fillColor=t.fillStyle,n.strokeColor=t.strokeStyle;break;case 2:const a=z.makeHexColor(i[0],i[1],i[2]);s.fillStyle=a,s.strokeStyle=a,n.fillColor=a,n.strokeColor=a;break;default:throw new R(`Unsupported paint type: ${e}`)}}getPattern(t,e,i,s){let n=i;s!==Vt&&(n=z.transform(n,e.baseTransform),this.matrix&&(n=z.transform(n,this.matrix)));const a=this.createPatternCanvas(e);let r=new DOMMatrix(n);r=r.translate(a.offsetX,a.offsetY),r=r.scale(1/a.scaleX,1/a.scaleY);const o=t.createPattern(a.canvas,"repeat");return o.setTransform(r),o}}function ee({src:t,srcPos:e=0,dest:i,width:s,height:n,nonBlackColor:a=4294967295,inverseDecode:r=!1}){const o=O.isLittleEndian?4278190080:255,[l,h]=r?[a,o]:[o,a],d=s>>3,c=7&s,u=t.length;i=new Uint32Array(i.buffer);let p=0;for(let s=0;s>2),u=i.length,f=s+7>>3,b=4294967295,v=O.isLittleEndian?4278190080:255;for(p=0;pf?s:8*t-7,r=-8&a;let o=0,c=0;for(;n>=1}for(;l=a&&(m=n,f=s*m),l=0,g=f;g--;)c[l++]=d[h++],c[l++]=d[h++],c[l++]=d[h++],c[l++]=255;t.putImageData(o,0,p*ie)}}}function oe(t,e){if(e.bitmap)return void t.drawImage(e.bitmap,0,0);const i=e.height,s=e.width,n=i%ie,a=(i-n)/ie,r=0===n?a:a+1,o=t.createImageData(s,ie);let l=0;const h=e.data,d=o.data;for(let e=0;e10&&"function"==typeof i,h=l?Date.now()+15:0;let d=0;const c=this.commonObjs,u=this.objs;let p;for(;;){if(void 0!==s&&r===s.nextBreakPoint)return s.breakIt(r,i),r;if(p=a[r],p!==m.dependency)this[p].apply(this,n[r]);else for(const t of n[r]){const e=t.startsWith("g_")?c:u;if(!e.has(t))return e.get(t,i),r}if(r++,r===o)return r;if(l&&++d>10){if(Date.now()>h)return i(),r;d=0}}}#Le(){for(;this.stateStack.length||this.inSMaskMode;)this.restore();this.current.activeSMask=null,this.ctx.restore(),this.transparentCanvas&&(this.ctx=this.compositeCtx,this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.drawImage(this.transparentCanvas,0,0),this.ctx.restore(),this.transparentCanvas=null)}endDrawing(){this.#Le(),this.cachedCanvases.clear(),this.cachedPatterns.clear();for(const t of this._cachedBitmapsMap.values()){for(const e of t.values())"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement&&(e.width=e.height=0);t.clear()}this._cachedBitmapsMap.clear(),this.#Fe()}#Fe(){if(this.pageColors){const t=this.filterFactory.addHCMFilter(this.pageColors.foreground,this.pageColors.background);if("none"!==t){const e=this.ctx.filter;this.ctx.filter=t,this.ctx.drawImage(this.ctx.canvas,0,0),this.ctx.filter=e}}}_scaleImage(t,e){const i=t.width,s=t.height;let n,a,r=Math.max(Math.hypot(e[0],e[1]),1),o=Math.max(Math.hypot(e[2],e[3]),1),l=i,h=s,d="prescale1";for(;r>2&&l>1||o>2&&h>1;){let e=l,i=h;r>2&&l>1&&(e=l>=16384?Math.floor(l/2)-1||1:Math.ceil(l/2),r/=l/e),o>2&&h>1&&(i=h>=16384?Math.floor(h/2)-1||1:Math.ceil(h)/2,o/=h/i),n=this.cachedCanvases.getCanvas(d,e,i),a=n.context,a.clearRect(0,0,e,i),a.drawImage(t,0,0,l,h,0,0,e,i),t=n.canvas,l=e,h=i,d="prescale1"===d?"prescale2":"prescale1"}return{img:t,paintWidth:l,paintHeight:h}}_createMaskCanvas(t){const e=this.ctx,{width:i,height:s}=t,n=this.current.fillColor,a=this.current.patternFill,r=mt(e);let o,l,h,d;if((t.bitmap||t.data)&&t.count>1){const e=t.bitmap||t.data.buffer;l=JSON.stringify(a?r:[r.slice(0,4),n]),o=this._cachedBitmapsMap.get(e),o||(o=new Map,this._cachedBitmapsMap.set(e,o));const i=o.get(l);if(i&&!a)return{canvas:i,offsetX:Math.round(Math.min(r[0],r[2])+r[4]),offsetY:Math.round(Math.min(r[1],r[3])+r[5])};h=i}h||(d=this.cachedCanvases.getCanvas("maskCanvas",i,s),oe(d.context,t));let c=z.transform(r,[1/i,0,0,-1/s,0,0]);c=z.transform(c,[1,0,0,1,0,-s]);const[u,p,g,m]=z.getAxialAlignedBoundingBox([0,0,i,s],c),f=Math.round(g-u)||1,b=Math.round(m-p)||1,v=this.cachedCanvases.getCanvas("fillCanvas",f,b),A=v.context,y=u,w=p;A.translate(-y,-w),A.transform(...c),h||(h=this._scaleImage(d.canvas,ft(A)),h=h.img,o&&a&&o.set(l,h)),A.imageSmoothingEnabled=de(mt(A),t.interpolate),ne(A,h,0,0,h.width,h.height,0,0,i,s),A.globalCompositeOperation="source-in";const _=z.transform(ft(A),[1,0,0,1,-y,-w]);return A.fillStyle=a?n.getPattern(e,this,_,Wt):n,A.fillRect(0,0,i,s),o&&!a&&(this.cachedCanvases.delete("fillCanvas"),o.set(l,v.canvas)),{canvas:v.canvas,offsetX:Math.round(y),offsetY:Math.round(w)}}setLineWidth(t){t!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=t,this.ctx.lineWidth=t}setLineCap(t){this.ctx.lineCap=ce[t]}setLineJoin(t){this.ctx.lineJoin=ue[t]}setMiterLimit(t){this.ctx.miterLimit=t}setDash(t,e){const i=this.ctx;void 0!==i.setLineDash&&(i.setLineDash(t),i.lineDashOffset=e)}setRenderingIntent(t){}setFlatness(t){}setGState(t){for(const[e,i]of t)switch(e){case"LW":this.setLineWidth(i);break;case"LC":this.setLineCap(i);break;case"LJ":this.setLineJoin(i);break;case"ML":this.setMiterLimit(i);break;case"D":this.setDash(i[0],i[1]);break;case"RI":this.setRenderingIntent(i);break;case"FL":this.setFlatness(i);break;case"Font":this.setFont(i[0],i[1]);break;case"CA":this.current.strokeAlpha=i;break;case"ca":this.current.fillAlpha=i,this.ctx.globalAlpha=i;break;case"BM":this.ctx.globalCompositeOperation=i;break;case"SMask":this.current.activeSMask=i?this.tempSMask:null,this.tempSMask=null,this.checkSMaskState();break;case"TR":this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(i)}}get inSMaskMode(){return!!this.suspendedCtx}checkSMaskState(){const t=this.inSMaskMode;this.current.activeSMask&&!t?this.beginSMaskMode():!this.current.activeSMask&&t&&this.endSMaskMode()}beginSMaskMode(){if(this.inSMaskMode)throw new Error("beginSMaskMode called while already in smask mode");const t=this.ctx.canvas.width,e=this.ctx.canvas.height,i="smaskGroupAt"+this.groupLevel,s=this.cachedCanvases.getCanvas(i,t,e);this.suspendedCtx=this.ctx,this.ctx=s.context;const n=this.ctx;n.setTransform(...mt(this.suspendedCtx)),le(this.suspendedCtx,n),function(t,e){if(t._removeMirroring)throw new Error("Context is already forwarding operations.");t.__originalSave=t.save,t.__originalRestore=t.restore,t.__originalRotate=t.rotate,t.__originalScale=t.scale,t.__originalTranslate=t.translate,t.__originalTransform=t.transform,t.__originalSetTransform=t.setTransform,t.__originalResetTransform=t.resetTransform,t.__originalClip=t.clip,t.__originalMoveTo=t.moveTo,t.__originalLineTo=t.lineTo,t.__originalBezierCurveTo=t.bezierCurveTo,t.__originalRect=t.rect,t.__originalClosePath=t.closePath,t.__originalBeginPath=t.beginPath,t._removeMirroring=()=>{t.save=t.__originalSave,t.restore=t.__originalRestore,t.rotate=t.__originalRotate,t.scale=t.__originalScale,t.translate=t.__originalTranslate,t.transform=t.__originalTransform,t.setTransform=t.__originalSetTransform,t.resetTransform=t.__originalResetTransform,t.clip=t.__originalClip,t.moveTo=t.__originalMoveTo,t.lineTo=t.__originalLineTo,t.bezierCurveTo=t.__originalBezierCurveTo,t.rect=t.__originalRect,t.closePath=t.__originalClosePath,t.beginPath=t.__originalBeginPath,delete t._removeMirroring},t.save=function(){e.save(),this.__originalSave()},t.restore=function(){e.restore(),this.__originalRestore()},t.translate=function(t,i){e.translate(t,i),this.__originalTranslate(t,i)},t.scale=function(t,i){e.scale(t,i),this.__originalScale(t,i)},t.transform=function(t,i,s,n,a,r){e.transform(t,i,s,n,a,r),this.__originalTransform(t,i,s,n,a,r)},t.setTransform=function(t,i,s,n,a,r){e.setTransform(t,i,s,n,a,r),this.__originalSetTransform(t,i,s,n,a,r)},t.resetTransform=function(){e.resetTransform(),this.__originalResetTransform()},t.rotate=function(t){e.rotate(t),this.__originalRotate(t)},t.clip=function(t){e.clip(t),this.__originalClip(t)},t.moveTo=function(t,i){e.moveTo(t,i),this.__originalMoveTo(t,i)},t.lineTo=function(t,i){e.lineTo(t,i),this.__originalLineTo(t,i)},t.bezierCurveTo=function(t,i,s,n,a,r){e.bezierCurveTo(t,i,s,n,a,r),this.__originalBezierCurveTo(t,i,s,n,a,r)},t.rect=function(t,i,s,n){e.rect(t,i,s,n),this.__originalRect(t,i,s,n)},t.closePath=function(){e.closePath(),this.__originalClosePath()},t.beginPath=function(){e.beginPath(),this.__originalBeginPath()}}(n,this.suspendedCtx),this.setGState([["BM","source-over"],["ca",1],["CA",1]])}endSMaskMode(){if(!this.inSMaskMode)throw new Error("endSMaskMode called while not in smask mode");this.ctx._removeMirroring(),le(this.ctx,this.suspendedCtx),this.ctx=this.suspendedCtx,this.suspendedCtx=null}compose(t){if(!this.current.activeSMask)return;t?(t[0]=Math.floor(t[0]),t[1]=Math.floor(t[1]),t[2]=Math.ceil(t[2]),t[3]=Math.ceil(t[3])):t=[0,0,this.ctx.canvas.width,this.ctx.canvas.height];const e=this.current.activeSMask,i=this.suspendedCtx;this.composeSMask(i,e,this.ctx,t),this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height),this.ctx.restore()}composeSMask(t,e,i,s){const n=s[0],a=s[1],r=s[2]-n,o=s[3]-a;0!==r&&0!==o&&(this.genericComposeSMask(e.context,i,r,o,e.subtype,e.backdrop,e.transferMap,n,a,e.offsetX,e.offsetY),t.save(),t.globalAlpha=1,t.globalCompositeOperation="source-over",t.setTransform(1,0,0,1,0,0),t.drawImage(i.canvas,0,0),t.restore())}genericComposeSMask(t,e,i,s,n,a,r,o,l,h,d){let c=t.canvas,u=o-h,p=l-d;if(a)if(u<0||p<0||u+i>c.width||p+s>c.height){const t=this.cachedCanvases.getCanvas("maskExtension",i,s),e=t.context;e.drawImage(c,-u,-p),a.some((t=>0!==t))&&(e.globalCompositeOperation="destination-atop",e.fillStyle=z.makeHexColor(...a),e.fillRect(0,0,i,s),e.globalCompositeOperation="source-over"),c=t.canvas,u=p=0}else if(a.some((t=>0!==t))){t.save(),t.globalAlpha=1,t.setTransform(1,0,0,1,0,0);const e=new Path2D;e.rect(u,p,i,s),t.clip(e),t.globalCompositeOperation="destination-atop",t.fillStyle=z.makeHexColor(...a),t.fillRect(u,p,i,s),t.restore()}e.save(),e.globalAlpha=1,e.setTransform(1,0,0,1,0,0),"Alpha"===n&&r?e.filter=this.filterFactory.addAlphaFilter(r):"Luminosity"===n&&(e.filter=this.filterFactory.addLuminosityFilter(r));const g=new Path2D;g.rect(o,l,i,s),e.clip(g),e.globalCompositeOperation="destination-in",e.drawImage(c,u,p,i,s,o,l,i,s),e.restore()}save(){this.inSMaskMode?(le(this.ctx,this.suspendedCtx),this.suspendedCtx.save()):this.ctx.save();const t=this.current;this.stateStack.push(t),this.current=t.clone()}restore(){0===this.stateStack.length&&this.inSMaskMode&&this.endSMaskMode(),0!==this.stateStack.length&&(this.current=this.stateStack.pop(),this.inSMaskMode?(this.suspendedCtx.restore(),le(this.suspendedCtx,this.ctx)):this.ctx.restore(),this.checkSMaskState(),this.pendingClip=null,this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null)}transform(t,e,i,s,n,a){this.ctx.transform(t,e,i,s,n,a),this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null}constructPath(t,e,i){const s=this.ctx,n=this.current;let a,r,o=n.x,l=n.y;const h=mt(s),d=0===h[0]&&0===h[3]||0===h[1]&&0===h[2],c=d?i.slice(0):null;for(let i=0,u=0,p=t.length;i100&&(h=100),this.current.fontSizeScale=e/h,this.ctx.font=`${l} ${o} ${h}px ${a}`}setTextRenderingMode(t){this.current.textRenderingMode=t}setTextRise(t){this.current.textRise=t}moveText(t,e){this.current.x=this.current.lineX+=t,this.current.y=this.current.lineY+=e}setLeadingMoveText(t,e){this.setLeading(-e),this.moveText(t,e)}setTextMatrix(t,e,i,s,n,a){this.current.textMatrix=[t,e,i,s,n,a],this.current.textMatrixScale=Math.hypot(t,e),this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0}nextLine(){this.moveText(0,this.current.leading)}paintChar(t,e,i,s){const n=this.ctx,a=this.current,r=a.font,o=a.textRenderingMode,l=a.fontSize/a.fontSizeScale,h=3&o,d=!!(4&o),c=a.patternFill&&!r.missingFile;let u;(r.disableFontFace||d||c)&&(u=r.getPathGenerator(this.commonObjs,t)),r.disableFontFace||c?(n.save(),n.translate(e,i),n.beginPath(),u(n,l),s&&n.setTransform(...s),0!==h&&2!==h||n.fill(),1!==h&&2!==h||n.stroke(),n.restore()):(0!==h&&2!==h||n.fillText(t,e,i),1!==h&&2!==h||n.strokeText(t,e,i)),d&&(this.pendingTextPaths||=[]).push({transform:mt(n),x:e,y:i,fontSize:l,addToPath:u})}get isFontSubpixelAAEnabled(){const{context:t}=this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled",10,10);t.scale(1.5,1),t.fillText("I",0,10);const e=t.getImageData(0,0,10,10).data;let i=!1;for(let t=3;t0&&e[t]<255){i=!0;break}return E(this,"isFontSubpixelAAEnabled",i)}showText(t){const e=this.current,i=e.font;if(i.isType3Font)return this.showType3Text(t);const s=e.fontSize;if(0===s)return;const n=this.ctx,a=e.fontSizeScale,r=e.charSpacing,o=e.wordSpacing,l=e.fontDirection,h=e.textHScale*l,d=t.length,c=i.vertical,u=c?1:-1,p=i.defaultVMetrics,g=s*e.fontMatrix[0],m=0===e.textRenderingMode&&!i.disableFontFace&&!e.patternFill;let f;if(n.save(),n.transform(...e.textMatrix),n.translate(e.x,e.y+e.textRise),l>0?n.scale(h,-1):n.scale(h,1),e.patternFill){n.save();const t=e.fillColor.getPattern(n,this,ft(n),Wt);f=mt(n),n.restore(),n.fillStyle=t}let b=e.lineWidth;const v=e.textMatrixScale;if(0===v||0===b){const t=3&e.textRenderingMode;1!==t&&2!==t||(b=this.getSinglePixelWidth())}else b/=v;if(1!==a&&(n.scale(a,a),b/=a),n.lineWidth=b,i.isInvalidPDFjsFont){const i=[];let s=0;for(const e of t)i.push(e.unicode),s+=e.width;return n.fillText(i.join(""),0,0),e.x+=s*g*h,n.restore(),void this.compose()}let A,y=0;for(A=0;A0){const t=1e3*n.measureText(b).width/s*a;if(xnew me(t,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack})};e=new te(t,i,this.ctx,n,s)}else e=this._getPattern(t[1],t[2]);return e}setStrokeColorN(){this.current.strokeColor=this.getColorN_Pattern(arguments)}setFillColorN(){this.current.fillColor=this.getColorN_Pattern(arguments),this.current.patternFill=!0}setStrokeRGBColor(t,e,i){this.ctx.strokeStyle=this.current.strokeColor=z.makeHexColor(t,e,i)}setStrokeTransparent(){this.ctx.strokeStyle=this.current.strokeColor="transparent"}setFillRGBColor(t,e,i){this.ctx.fillStyle=this.current.fillColor=z.makeHexColor(t,e,i),this.current.patternFill=!1}setFillTransparent(){this.ctx.fillStyle=this.current.fillColor="transparent",this.current.patternFill=!1}_getPattern(t,e=null){let i;return this.cachedPatterns.has(t)?i=this.cachedPatterns.get(t):(i=function(t){switch(t[0]){case"RadialAxial":return new Kt(t);case"Mesh":return new Jt(t);case"Dummy":return new Zt}throw new Error(`Unknown IR type: ${t[0]}`)}(this.getObject(t)),this.cachedPatterns.set(t,i)),e&&(i.matrix=e),i}shadingFill(t){if(!this.contentVisible)return;const e=this.ctx;this.save();const i=this._getPattern(t);e.fillStyle=i.getPattern(e,this,ft(e),Vt);const s=ft(e);if(s){const{width:t,height:i}=e.canvas,[n,a,r,o]=z.getAxialAlignedBoundingBox([0,0,t,i],s);this.ctx.fillRect(n,a,r-n,o-a)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.compose(this.current.getClippedPathBoundingBox()),this.restore()}beginInlineImage(){_("Should not call beginInlineImage")}beginImageData(){_("Should not call beginImageData")}paintFormXObjectBegin(t,e){if(this.contentVisible&&(this.save(),this.baseTransformStack.push(this.baseTransform),t&&this.transform(...t),this.baseTransform=mt(this.ctx),e)){const t=e[2]-e[0],i=e[3]-e[1];this.ctx.rect(e[0],e[1],t,i),this.current.updateRectMinMax(mt(this.ctx),e),this.clip(),this.endPath()}}paintFormXObjectEnd(){this.contentVisible&&(this.restore(),this.baseTransform=this.baseTransformStack.pop())}beginGroup(t){if(!this.contentVisible)return;this.save(),this.inSMaskMode&&(this.endSMaskMode(),this.current.activeSMask=null);const e=this.ctx;t.isolated||y("TODO: Support non-isolated groups."),t.knockout&&w("Knockout groups not supported.");const i=mt(e);if(t.matrix&&e.transform(...t.matrix),!t.bbox)throw new Error("Bounding box is required.");let s=z.getAxialAlignedBoundingBox(t.bbox,mt(e));const n=[0,0,e.canvas.width,e.canvas.height];s=z.intersect(s,n)||[0,0,0,0];const a=Math.floor(s[0]),r=Math.floor(s[1]),o=Math.max(Math.ceil(s[2])-a,1),l=Math.max(Math.ceil(s[3])-r,1);this.current.startNewPathAndClipBox([0,0,o,l]);let h="groupAt"+this.groupLevel;t.smask&&(h+="_smask_"+this.smaskCounter++%2);const d=this.cachedCanvases.getCanvas(h,o,l),c=d.context;c.translate(-a,-r),c.transform(...i),t.smask?this.smaskStack.push({canvas:d.canvas,context:c,offsetX:a,offsetY:r,subtype:t.smask.subtype,backdrop:t.smask.backdrop,transferMap:t.smask.transferMap||null,startTransformInverse:null}):(e.setTransform(1,0,0,1,0,0),e.translate(a,r),e.save()),le(e,c),this.ctx=c,this.setGState([["BM","source-over"],["ca",1],["CA",1]]),this.groupStack.push(e),this.groupLevel++}endGroup(t){if(!this.contentVisible)return;this.groupLevel--;const e=this.ctx,i=this.groupStack.pop();if(this.ctx=i,this.ctx.imageSmoothingEnabled=!1,t.smask)this.tempSMask=this.smaskStack.pop(),this.restore();else{this.ctx.restore();const t=mt(this.ctx);this.restore(),this.ctx.save(),this.ctx.setTransform(...t);const i=z.getAxialAlignedBoundingBox([0,0,e.canvas.width,e.canvas.height],t);this.ctx.drawImage(e.canvas,0,0),this.ctx.restore(),this.compose(i)}}beginAnnotation(t,e,i,s,n){if(this.#Le(),he(this.ctx),this.ctx.save(),this.save(),this.baseTransform&&this.ctx.setTransform(...this.baseTransform),e){const s=e[2]-e[0],a=e[3]-e[1];if(n&&this.annotationCanvasMap){(i=i.slice())[4]-=e[0],i[5]-=e[1],(e=e.slice())[0]=e[1]=0,e[2]=s,e[3]=a;const[n,r]=z.singularValueDecompose2dScale(mt(this.ctx)),{viewportScale:o}=this,l=Math.ceil(s*this.outputScaleX*o),h=Math.ceil(a*this.outputScaleY*o);this.annotationCanvas=this.canvasFactory.create(l,h);const{canvas:d,context:c}=this.annotationCanvas;this.annotationCanvasMap.set(t,d),this.annotationCanvas.savedCtx=this.ctx,this.ctx=c,this.ctx.save(),this.ctx.setTransform(n,0,0,-r,0,a*r),he(this.ctx)}else he(this.ctx),this.endPath(),this.ctx.rect(e[0],e[1],s,a),this.ctx.clip(),this.ctx.beginPath()}this.current=new ae(this.ctx.canvas.width,this.ctx.canvas.height),this.transform(...i),this.transform(...s)}endAnnotation(){this.annotationCanvas&&(this.ctx.restore(),this.#Fe(),this.ctx=this.annotationCanvas.savedCtx,delete this.annotationCanvas.savedCtx,delete this.annotationCanvas)}paintImageMaskXObject(t){if(!this.contentVisible)return;const e=t.count;(t=this.getObject(t.data,t)).count=e;const i=this.ctx,s=this.processingType3;if(s&&(void 0===s.compiled&&(s.compiled=function(t){const{width:e,height:i}=t;if(e>1e3||i>1e3)return null;const s=new Uint8Array([0,2,4,0,1,0,5,4,8,10,0,8,0,2,1,0]),n=e+1;let a,r,o,l=new Uint8Array(n*(i+1));const h=e+7&-8;let d=new Uint8Array(h*i),c=0;for(const e of t.data){let t=128;for(;t>0;)d[c++]=e&t?0:255,t>>=1}let u=0;for(c=0,0!==d[c]&&(l[0]=1,++u),r=1;r>2)+(d[c+1]?4:0)+(d[c-h+1]?8:0),s[t]&&(l[o+r]=s[t],++u),c++;if(d[c-h]!==d[c]&&(l[o+r]=d[c]?2:4,++u),u>1e3)return null}for(c=h*(i-1),o=a*n,0!==d[c]&&(l[o]=8,++u),r=1;r1e3)return null;const p=new Int32Array([0,n,-1,0,-n,0,0,0,1]),g=new Path2D;for(a=0;u&&a<=i;a++){let t=a*n;const i=t+e;for(;t>4,l[t]&=r>>2|r<<2),g.lineTo(t%n,t/n|0),l[t]||--u}while(s!==t);--a}return d=null,l=null,function(t){t.save(),t.scale(1/e,-1/i),t.translate(0,-i),t.fill(g),t.beginPath(),t.restore()}}(t)),s.compiled))return void s.compiled(i);const n=this._createMaskCanvas(t),a=n.canvas;i.save(),i.setTransform(1,0,0,1,0,0),i.drawImage(a,n.offsetX,n.offsetY),i.restore(),this.compose()}paintImageMaskXObjectRepeat(t,e,i=0,s=0,n,a){if(!this.contentVisible)return;t=this.getObject(t.data,t);const r=this.ctx;r.save();const o=mt(r);r.transform(e,i,s,n,0,0);const l=this._createMaskCanvas(t);r.setTransform(1,0,0,1,l.offsetX-o[4],l.offsetY-o[5]);for(let t=0,h=a.length;te?h/e:1,r=l>e?l/e:1}}this._cachedScaleForStroking[0]=a,this._cachedScaleForStroking[1]=r}return this._cachedScaleForStroking}rescaleAndStroke(t){const{ctx:e}=this,{lineWidth:i}=this.current,[s,n]=this.getScaleForStroking();if(e.lineWidth=i||1,1===s&&1===n)return void e.stroke();const a=e.getLineDash();if(t&&e.save(),e.scale(s,n),a.length>0){const t=Math.max(s,n);e.setLineDash(a.map((e=>e/t))),e.lineDashOffset/=t}e.stroke(),t&&e.restore()}isContentVisible(){for(let t=this.markedContentStack.length-1;t>=0;t--)if(!this.markedContentStack[t].visible)return!1;return!0}}for(const t in m)void 0!==me.prototype[t]&&(me.prototype[m[t]]=me.prototype[t]);class fe{static#Ne=null;static#Oe="";static get workerPort(){return this.#Ne}static set workerPort(t){if(!("undefined"!=typeof Worker&&t instanceof Worker)&&null!==t)throw new Error("Invalid `workerPort` type.");this.#Ne=t}static get workerSrc(){return this.#Oe}static set workerSrc(t){if("string"!=typeof t)throw new Error("Invalid `workerSrc` type.");this.#Oe=t}}function be(t){switch(t instanceof Error||"object"==typeof t&&null!==t||_('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),t.name){case"AbortException":return new D(t.message);case"MissingPDFException":return new I(t.message);case"PasswordException":return new T(t.message,t.code);case"UnexpectedResponseException":return new P(t.message,t.status);case"UnknownErrorException":return new M(t.message,t.details);default:return new M(t.message,t.toString())}}class ve{constructor(t,e,i){this.sourceName=t,this.targetName=e,this.comObj=i,this.callbackId=1,this.streamId=1,this.streamSinks=Object.create(null),this.streamControllers=Object.create(null),this.callbackCapabilities=Object.create(null),this.actionHandler=Object.create(null),this._onComObjOnMessage=t=>{const e=t.data;if(e.targetName!==this.sourceName)return;if(e.stream)return void this.#Be(e);if(e.callback){const t=e.callbackId,i=this.callbackCapabilities[t];if(!i)throw new Error(`Cannot resolve callback ${t}`);if(delete this.callbackCapabilities[t],1===e.callback)i.resolve(e.data);else{if(2!==e.callback)throw new Error("Unexpected callback case");i.reject(be(e.reason))}return}const s=this.actionHandler[e.action];if(!s)throw new Error(`Unknown action from worker: ${e.action}`);if(e.callbackId){const t=this.sourceName,n=e.sourceName;new Promise((function(t){t(s(e.data))})).then((function(s){i.postMessage({sourceName:t,targetName:n,callback:1,callbackId:e.callbackId,data:s})}),(function(s){i.postMessage({sourceName:t,targetName:n,callback:2,callbackId:e.callbackId,reason:be(s)})}))}else e.streamId?this.#ze(e):s(e.data)},i.addEventListener("message",this._onComObjOnMessage)}on(t,e){const i=this.actionHandler;if(i[t])throw new Error(`There is already an actionName called "${t}"`);i[t]=e}send(t,e,i){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,data:e},i)}sendWithPromise(t,e,i){const s=this.callbackId++,n=Promise.withResolvers();this.callbackCapabilities[s]=n;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,callbackId:s,data:e},i)}catch(t){n.reject(t)}return n.promise}sendWithStream(t,e,i,s){const n=this.streamId++,a=this.sourceName,r=this.targetName,o=this.comObj;return new ReadableStream({start:i=>{const l=Promise.withResolvers();return this.streamControllers[n]={controller:i,startCall:l,pullCall:null,cancelCall:null,isClosed:!1},o.postMessage({sourceName:a,targetName:r,action:t,streamId:n,data:e,desiredSize:i.desiredSize},s),l.promise},pull:t=>{const e=Promise.withResolvers();return this.streamControllers[n].pullCall=e,o.postMessage({sourceName:a,targetName:r,stream:6,streamId:n,desiredSize:t.desiredSize}),e.promise},cancel:t=>{x(t instanceof Error,"cancel must have a valid reason");const e=Promise.withResolvers();return this.streamControllers[n].cancelCall=e,this.streamControllers[n].isClosed=!0,o.postMessage({sourceName:a,targetName:r,stream:1,streamId:n,reason:be(t)}),e.promise}},i)}#ze(t){const e=t.streamId,i=this.sourceName,s=t.sourceName,n=this.comObj,a=this,r=this.actionHandler[t.action],o={enqueue(t,a=1,r){if(this.isCancelled)return;const o=this.desiredSize;this.desiredSize-=a,o>0&&this.desiredSize<=0&&(this.sinkCapability=Promise.withResolvers(),this.ready=this.sinkCapability.promise),n.postMessage({sourceName:i,targetName:s,stream:4,streamId:e,chunk:t},r)},close(){this.isCancelled||(this.isCancelled=!0,n.postMessage({sourceName:i,targetName:s,stream:3,streamId:e}),delete a.streamSinks[e])},error(t){x(t instanceof Error,"error must have a valid reason"),this.isCancelled||(this.isCancelled=!0,n.postMessage({sourceName:i,targetName:s,stream:5,streamId:e,reason:be(t)}))},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:t.desiredSize,ready:null};o.sinkCapability.resolve(),o.ready=o.sinkCapability.promise,this.streamSinks[e]=o,new Promise((function(e){e(r(t.data,o))})).then((function(){n.postMessage({sourceName:i,targetName:s,stream:8,streamId:e,success:!0})}),(function(t){n.postMessage({sourceName:i,targetName:s,stream:8,streamId:e,reason:be(t)})}))}#Be(t){const e=t.streamId,i=this.sourceName,s=t.sourceName,n=this.comObj,a=this.streamControllers[e],r=this.streamSinks[e];switch(t.stream){case 8:t.success?a.startCall.resolve():a.startCall.reject(be(t.reason));break;case 7:t.success?a.pullCall.resolve():a.pullCall.reject(be(t.reason));break;case 6:if(!r){n.postMessage({sourceName:i,targetName:s,stream:7,streamId:e,success:!0});break}r.desiredSize<=0&&t.desiredSize>0&&r.sinkCapability.resolve(),r.desiredSize=t.desiredSize,new Promise((function(t){t(r.onPull?.())})).then((function(){n.postMessage({sourceName:i,targetName:s,stream:7,streamId:e,success:!0})}),(function(t){n.postMessage({sourceName:i,targetName:s,stream:7,streamId:e,reason:be(t)})}));break;case 4:if(x(a,"enqueue should have stream controller"),a.isClosed)break;a.controller.enqueue(t.chunk);break;case 3:if(x(a,"close should have stream controller"),a.isClosed)break;a.isClosed=!0,a.controller.close(),this.#He(a,e);break;case 5:x(a,"error should have stream controller"),a.controller.error(be(t.reason)),this.#He(a,e);break;case 2:t.success?a.cancelCall.resolve():a.cancelCall.reject(be(t.reason)),this.#He(a,e);break;case 1:if(!r)break;new Promise((function(e){e(r.onCancel?.(be(t.reason)))})).then((function(){n.postMessage({sourceName:i,targetName:s,stream:2,streamId:e,success:!0})}),(function(t){n.postMessage({sourceName:i,targetName:s,stream:2,streamId:e,reason:be(t)})})),r.sinkCapability.reject(be(t.reason)),r.isCancelled=!0,delete this.streamSinks[e];break;default:throw new Error("Unexpected stream case")}}async#He(t,e){await Promise.allSettled([t.startCall?.promise,t.pullCall?.promise,t.cancelCall?.promise]),delete this.streamControllers[e]}destroy(){this.comObj.removeEventListener("message",this._onComObjOnMessage)}}class Ae{#je;#Ue;constructor({parsedData:t,rawData:e}){this.#je=t,this.#Ue=e}getRaw(){return this.#Ue}get(t){return this.#je.get(t)??null}getAll(){return N(this.#je)}has(t){return this.#je.has(t)}}const ye=Symbol("INTERNAL");class we{#$e=!1;#We=!1;#Ge=!1;#Ve=!0;constructor(t,{name:e,intent:i,usage:s}){this.#$e=!!(2&t),this.#We=!!(4&t),this.name=e,this.intent=i,this.usage=s}get visible(){if(this.#Ge)return this.#Ve;if(!this.#Ve)return!1;const{print:t,view:e}=this.usage;return this.#$e?"OFF"!==e?.viewState:!this.#We||"OFF"!==t?.printState}_setVisible(t,e,i=!1){t!==ye&&_("Internal method `_setVisible` called."),this.#Ge=i,this.#Ve=e}}class _e{#qe=null;#Xe=new Map;#Ke=null;#Ye=null;constructor(t,e=2){if(this.renderingIntent=e,this.name=null,this.creator=null,null!==t){this.name=t.name,this.creator=t.creator,this.#Ye=t.order;for(const i of t.groups)this.#Xe.set(i.id,new we(e,i));if("OFF"===t.baseState)for(const t of this.#Xe.values())t._setVisible(ye,!1);for(const e of t.on)this.#Xe.get(e)._setVisible(ye,!0);for(const e of t.off)this.#Xe.get(e)._setVisible(ye,!1);this.#Ke=this.getHash()}}#Qe(t){const e=t.length;if(e<2)return!0;const i=t[0];for(let s=1;s0?N(this.#Xe):null}getGroup(t){return this.#Xe.get(t)||null}getHash(){if(null!==this.#qe)return this.#qe;const t=new Lt;for(const[e,i]of this.#Xe)t.update(`${e}:${i.visible}`);return this.#qe=t.hexdigest()}}class xe{constructor(t,{disableRange:e=!1,disableStream:i=!1}){x(t,'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');const{length:s,initialData:n,progressiveDone:a,contentDispositionFilename:r}=t;if(this._queuedChunks=[],this._progressiveDone=a,this._contentDispositionFilename=r,n?.length>0){const t=n instanceof Uint8Array&&n.byteLength===n.buffer.byteLength?n.buffer:new Uint8Array(n).buffer;this._queuedChunks.push(t)}this._pdfDataRangeTransport=t,this._isStreamingSupported=!i,this._isRangeSupported=!e,this._contentLength=s,this._fullRequestReader=null,this._rangeReaders=[],t.addRangeListener(((t,e)=>{this._onReceiveData({begin:t,chunk:e})})),t.addProgressListener(((t,e)=>{this._onProgress({loaded:t,total:e})})),t.addProgressiveReadListener((t=>{this._onReceiveData({chunk:t})})),t.addProgressiveDoneListener((()=>{this._onProgressiveDone()})),t.transportReady()}_onReceiveData({begin:t,chunk:e}){const i=e instanceof Uint8Array&&e.byteLength===e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer;void 0===t?this._fullRequestReader?this._fullRequestReader._enqueue(i):this._queuedChunks.push(i):x(this._rangeReaders.some((function(e){return e._begin===t&&(e._enqueue(i),!0)})),"_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.")}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}_onProgress(t){void 0===t.total?this._rangeReaders[0]?.onProgress?.({loaded:t.loaded}):this._fullRequestReader?.onProgress?.({loaded:t.loaded,total:t.total})}_onProgressiveDone(){this._fullRequestReader?.progressiveDone(),this._progressiveDone=!0}_removeRangeReader(t){const e=this._rangeReaders.indexOf(t);e>=0&&this._rangeReaders.splice(e,1)}getFullReader(){x(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");const t=this._queuedChunks;return this._queuedChunks=null,new Ce(this,t,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const i=new Ee(this,t,e);return this._pdfDataRangeTransport.requestDataRange(t,e),this._rangeReaders.push(i),i}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeReaders.slice(0))e.cancel(t);this._pdfDataRangeTransport.abort()}}class Ce{constructor(t,e,i=!1,s=null){this._stream=t,this._done=i||!1,this._filename=nt(s)?s:null,this._queuedChunks=e||[],this._loaded=0;for(const t of this._queuedChunks)this._loaded+=t.byteLength;this._requests=[],this._headersReady=Promise.resolve(),t._fullRequestReader=this,this.onProgress=null}_enqueue(t){this._done||(this._requests.length>0?this._requests.shift().resolve({value:t,done:!1}):this._queuedChunks.push(t),this._loaded+=t.byteLength)}get headersReady(){return this._headersReady}get filename(){return this._filename}get isRangeSupported(){return this._stream._isRangeSupported}get isStreamingSupported(){return this._stream._isStreamingSupported}get contentLength(){return this._stream._contentLength}async read(){if(this._queuedChunks.length>0)return{value:this._queuedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}progressiveDone(){this._done||(this._done=!0)}}class Ee{constructor(t,e,i){this._stream=t,this._begin=e,this._end=i,this._queuedChunk=null,this._requests=[],this._done=!1,this.onProgress=null}_enqueue(t){if(!this._done){if(0===this._requests.length)this._queuedChunk=t;else{this._requests.shift().resolve({value:t,done:!1});for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}this._done=!0,this._stream._removeRangeReader(this)}}get isStreamingSupported(){return!1}async read(){if(this._queuedChunk){const t=this._queuedChunk;return this._queuedChunk=null,{value:t,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0,this._stream._removeRangeReader(this)}}function Se(t,e){const i=new Headers;if(!t||!e||"object"!=typeof e)return i;for(const t in e){const s=e[t];void 0!==s&&i.append(t,s)}return i}function Te({responseHeaders:t,isHttp:e,rangeChunkSize:i,disableRange:s}){const n={allowRangeRequests:!1,suggestedLength:void 0},a=parseInt(t.get("Content-Length"),10);return Number.isInteger(a)?(n.suggestedLength=a,a<=2*i||s||!e||"bytes"!==t.get("Accept-Ranges")||"identity"!==(t.get("Content-Encoding")||"identity")||(n.allowRangeRequests=!0),n):n}function Me(t){const e=t.get("Content-Disposition");if(e){let t=function(t){let e=!0,i=s("filename\\*","i").exec(t);if(i){i=i[1];let t=r(i);return t=unescape(t),t=o(t),t=l(t),a(t)}if(i=function(t){const e=[];let i;const n=s("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;null!==(i=n.exec(t));){let[,t,s,n]=i;if(t=parseInt(t,10),t in e){if(0===t)break}else e[t]=[s,n]}const a=[];for(let t=0;t{if(!Ie(e.status))throw ke(e.status,s);this._reader=e.body.getReader(),this._headersCapability.resolve();const i=e.headers,{allowRangeRequests:n,suggestedLength:a}=Te({responseHeaders:i,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=n,this._contentLength=a||this._contentLength,this._filename=Me(i),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new D("Streaming is disabled."))})).catch(this._headersCapability.reject),this.onProgress=null}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._headersCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:(this._loaded+=t.byteLength,this.onProgress?.({loaded:this._loaded,total:this._contentLength}),{value:Re(t),done:!1})}cancel(t){this._reader?.cancel(t),this._abortController.abort()}}class Fe{constructor(t,e,i){this._stream=t,this._reader=null,this._loaded=0;const s=t.source;this._withCredentials=s.withCredentials||!1,this._readCapability=Promise.withResolvers(),this._isStreamingSupported=!s.disableStream,this._abortController=new AbortController;const n=new Headers(t.headers);n.append("Range",`bytes=${e}-${i-1}`);const a=s.url;fetch(a,Pe(n,this._withCredentials,this._abortController)).then((t=>{if(!Ie(t.status))throw ke(t.status,a);this._readCapability.resolve(),this._reader=t.body.getReader()})).catch(this._readCapability.reject),this.onProgress=null}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._readCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:(this._loaded+=t.byteLength,this.onProgress?.({loaded:this._loaded}),{value:Re(t),done:!1})}cancel(t){this._reader?.cancel(t),this._abortController.abort()}}class Ne{constructor({url:t,httpHeaders:e,withCredentials:i}){this.url=t,this.isHttp=/^https?:/i.test(t),this.headers=Se(this.isHttp,e),this.withCredentials=i||!1,this.currXhrId=0,this.pendingRequests=Object.create(null)}requestRange(t,e,i){const s={begin:t,end:e};for(const t in i)s[t]=i[t];return this.request(s)}requestFull(t){return this.request(t)}request(t){const e=new XMLHttpRequest,i=this.currXhrId++,s=this.pendingRequests[i]={xhr:e};e.open("GET",this.url),e.withCredentials=this.withCredentials;for(const[t,i]of this.headers)e.setRequestHeader(t,i);return this.isHttp&&"begin"in t&&"end"in t?(e.setRequestHeader("Range",`bytes=${t.begin}-${t.end-1}`),s.expectedStatus=206):s.expectedStatus=200,e.responseType="arraybuffer",t.onError&&(e.onerror=function(i){t.onError(e.status)}),e.onreadystatechange=this.onStateChange.bind(this,i),e.onprogress=this.onProgress.bind(this,i),s.onHeadersReceived=t.onHeadersReceived,s.onDone=t.onDone,s.onError=t.onError,s.onProgress=t.onProgress,e.send(null),i}onProgress(t,e){const i=this.pendingRequests[t];i&&i.onProgress?.(e)}onStateChange(t,e){const i=this.pendingRequests[t];if(!i)return;const s=i.xhr;if(s.readyState>=2&&i.onHeadersReceived&&(i.onHeadersReceived(),delete i.onHeadersReceived),4!==s.readyState)return;if(!(t in this.pendingRequests))return;if(delete this.pendingRequests[t],0===s.status&&this.isHttp)return void i.onError?.(s.status);const n=s.status||200;if((200!==n||206!==i.expectedStatus)&&n!==i.expectedStatus)return void i.onError?.(s.status);const a=function(t){const e=t.response;return"string"!=typeof e?e:F(e).buffer}(s);if(206===n){const t=s.getResponseHeader("Content-Range"),e=/bytes (\d+)-(\d+)\/(\d+)/.exec(t);i.onDone({begin:parseInt(e[1],10),chunk:a})}else a?i.onDone({begin:0,chunk:a}):i.onError?.(s.status)}getRequestXhr(t){return this.pendingRequests[t].xhr}isPendingRequest(t){return t in this.pendingRequests}abortRequest(t){const e=this.pendingRequests[t].xhr;delete this.pendingRequests[t],e.abort()}}class Oe{constructor(t){this._source=t,this._manager=new Ne(t),this._rangeChunkSize=t.rangeChunkSize,this._fullRequestReader=null,this._rangeRequestReaders=[]}_onRangeRequestReaderClosed(t){const e=this._rangeRequestReaders.indexOf(t);e>=0&&this._rangeRequestReaders.splice(e,1)}getFullReader(){return x(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once."),this._fullRequestReader=new Be(this._manager,this._source),this._fullRequestReader}getRangeReader(t,e){const i=new ze(this._manager,t,e);return i.onClosed=this._onRangeRequestReaderClosed.bind(this),this._rangeRequestReaders.push(i),i}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class Be{constructor(t,e){this._manager=t;const i={onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)};this._url=e.url,this._fullRequestId=t.requestFull(i),this._headersCapability=Promise.withResolvers(),this._disableRange=e.disableRange||!1,this._contentLength=e.length,this._rangeChunkSize=e.rangeChunkSize,this._rangeChunkSize||this._disableRange||(this._disableRange=!0),this._isStreamingSupported=!1,this._isRangeSupported=!1,this._cachedChunks=[],this._requests=[],this._done=!1,this._storedError=void 0,this._filename=null,this.onProgress=null}_onHeadersReceived(){const t=this._fullRequestId,e=this._manager.getRequestXhr(t),i=new Headers(e.getAllResponseHeaders().trim().split(/[\r\n]+/).map((t=>{const[e,...i]=t.split(": ");return[e,i.join(": ")]}))),{allowRangeRequests:s,suggestedLength:n}=Te({responseHeaders:i,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});s&&(this._isRangeSupported=!0),this._contentLength=n||this._contentLength,this._filename=Me(i),this._isRangeSupported&&this._manager.abortRequest(t),this._headersCapability.resolve()}_onDone(t){if(t&&(this._requests.length>0?this._requests.shift().resolve({value:t.chunk,done:!1}):this._cachedChunks.push(t.chunk)),this._done=!0,!(this._cachedChunks.length>0)){for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}}_onError(t){this._storedError=ke(t,this._url),this._headersCapability.reject(this._storedError);for(const t of this._requests)t.reject(this._storedError);this._requests.length=0,this._cachedChunks.length=0}_onProgress(t){this.onProgress?.({loaded:t.loaded,total:t.lengthComputable?t.total:this._contentLength})}get filename(){return this._filename}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}get contentLength(){return this._contentLength}get headersReady(){return this._headersCapability.promise}async read(){if(this._storedError)throw this._storedError;if(this._cachedChunks.length>0)return{value:this._cachedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0,this._headersCapability.reject(t);for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._fullRequestId)&&this._manager.abortRequest(this._fullRequestId),this._fullRequestReader=null}}class ze{constructor(t,e,i){this._manager=t;const s={onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)};this._url=t.url,this._requestId=t.requestRange(e,i,s),this._requests=[],this._queuedChunk=null,this._done=!1,this._storedError=void 0,this.onProgress=null,this.onClosed=null}_close(){this.onClosed?.(this)}_onDone(t){const e=t.chunk;this._requests.length>0?this._requests.shift().resolve({value:e,done:!1}):this._queuedChunk=e,this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0,this._close()}_onError(t){this._storedError=ke(t,this._url);for(const t of this._requests)t.reject(this._storedError);this._requests.length=0,this._queuedChunk=null}_onProgress(t){this.isStreamingSupported||this.onProgress?.({loaded:t.loaded})}get isStreamingSupported(){return!1}async read(){if(this._storedError)throw this._storedError;if(null!==this._queuedChunk){const t=this._queuedChunk;return this._queuedChunk=null,{value:t,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._requestId)&&this._manager.abortRequest(this._requestId),this._close()}}const He=/^[a-z][a-z0-9\-+.]+:/i;function je(t,e,i){return"http:"===t.protocol?Ut.get("http").request(t,{headers:e},i):Ut.get("https").request(t,{headers:e},i)}class Ue{constructor(t){this.source=t,this.url=function(t){if(He.test(t))return new URL(t);const e=Ut.get("url");return new URL(e.pathToFileURL(t))}(t.url),this.isHttp="http:"===this.url.protocol||"https:"===this.url.protocol,this.isFsUrl="file:"===this.url.protocol,this.headers=Se(this.isHttp,t.httpHeaders),this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return x(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once."),this._fullRequestReader=this.isFsUrl?new qe(this):new Ge(this),this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const i=this.isFsUrl?new Xe(this,t,e):new Ve(this,t,e);return this._rangeRequestReaders.push(i),i}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class $e{constructor(t){this._url=t.url,this._done=!1,this._storedError=null,this.onProgress=null;const e=t.source;this._contentLength=e.length,this._loaded=0,this._filename=null,this._disableRange=e.disableRange||!1,this._rangeChunkSize=e.rangeChunkSize,this._rangeChunkSize||this._disableRange||(this._disableRange=!0),this._isStreamingSupported=!e.disableStream,this._isRangeSupported=!e.disableRange,this._readableStream=null,this._readCapability=Promise.withResolvers(),this._headersCapability=Promise.withResolvers()}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const t=this._readableStream.read();return null===t?(this._readCapability=Promise.withResolvers(),this.read()):(this._loaded+=t.length,this.onProgress?.({loaded:this._loaded,total:this._contentLength}),{value:new Uint8Array(t).buffer,done:!1})}cancel(t){this._readableStream?this._readableStream.destroy(t):this._error(t)}_error(t){this._storedError=t,this._readCapability.resolve()}_setReadableStream(t){this._readableStream=t,t.on("readable",(()=>{this._readCapability.resolve()})),t.on("end",(()=>{t.destroy(),this._done=!0,this._readCapability.resolve()})),t.on("error",(t=>{this._error(t)})),!this._isStreamingSupported&&this._isRangeSupported&&this._error(new D("streaming is disabled")),this._storedError&&this._readableStream.destroy(this._storedError)}}class We{constructor(t){this._url=t.url,this._done=!1,this._storedError=null,this.onProgress=null,this._loaded=0,this._readableStream=null,this._readCapability=Promise.withResolvers();const e=t.source;this._isStreamingSupported=!e.disableStream}get isStreamingSupported(){return this._isStreamingSupported}async read(){if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const t=this._readableStream.read();return null===t?(this._readCapability=Promise.withResolvers(),this.read()):(this._loaded+=t.length,this.onProgress?.({loaded:this._loaded}),{value:new Uint8Array(t).buffer,done:!1})}cancel(t){this._readableStream?this._readableStream.destroy(t):this._error(t)}_error(t){this._storedError=t,this._readCapability.resolve()}_setReadableStream(t){this._readableStream=t,t.on("readable",(()=>{this._readCapability.resolve()})),t.on("end",(()=>{t.destroy(),this._done=!0,this._readCapability.resolve()})),t.on("error",(t=>{this._error(t)})),this._storedError&&this._readableStream.destroy(this._storedError)}}class Ge extends $e{constructor(t){super(t);const e=Object.fromEntries(t.headers);this._request=je(this._url,e,(e=>{if(404===e.statusCode){const t=new I(`Missing PDF "${this._url}".`);return this._storedError=t,void this._headersCapability.reject(t)}this._headersCapability.resolve(),this._setReadableStream(e);const i=new Headers(this._readableStream.headers),{allowRangeRequests:s,suggestedLength:n}=Te({responseHeaders:i,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=s,this._contentLength=n||this._contentLength,this._filename=Me(i)})),this._request.on("error",(t=>{this._storedError=t,this._headersCapability.reject(t)})),this._request.end()}}class Ve extends We{constructor(t,e,i){super(t);const s=Object.fromEntries(t.headers);s.Range=`bytes=${e}-${i-1}`,this._request=je(this._url,s,(t=>{if(404!==t.statusCode)this._setReadableStream(t);else{const t=new I(`Missing PDF "${this._url}".`);this._storedError=t}})),this._request.on("error",(t=>{this._storedError=t})),this._request.end()}}class qe extends $e{constructor(t){super(t);const e=Ut.get("fs");e.promises.lstat(this._url).then((t=>{this._contentLength=t.size,this._setReadableStream(e.createReadStream(this._url)),this._headersCapability.resolve()}),(t=>{"ENOENT"===t.code&&(t=new I(`Missing PDF "${this._url}".`)),this._storedError=t,this._headersCapability.reject(t)}))}}class Xe extends We{constructor(t,e,i){super(t);const s=Ut.get("fs");this._setReadableStream(s.createReadStream(this._url,{start:e,end:i-1}))}}const Ke=30;class Ye{#Je=Promise.withResolvers();#ut=null;#Ze=!1;#ti=!!globalThis.FontInspector?.enabled;#ei=null;#ii=null;#si=0;#ni=0;#ai=null;#ri=null;#oi=0;#li=0;#hi=Object.create(null);#di=[];#ci=null;#ui=[];#pi=new WeakMap;#gi=null;static#mi=new Map;static#fi=new Map;static#bi=new WeakMap;static#vi=null;static#Ai=new Set;constructor({textContentSource:t,container:e,viewport:i}){if(t instanceof ReadableStream)this.#ci=t;else{if("object"!=typeof t)throw new Error('No "textContentSource" parameter specified.');this.#ci=new ReadableStream({start(e){e.enqueue(t),e.close()}})}this.#ut=this.#ri=e,this.#li=i.scale*(globalThis.devicePixelRatio||1),this.#oi=i.rotation,this.#ii={div:null,properties:null,ctx:null};const{pageWidth:s,pageHeight:n,pageX:a,pageY:r}=i.rawDims;this.#gi=[1,0,0,-1,-a,r+n],this.#ni=s,this.#si=n,Ye.#yi(),bt(e,i),this.#Je.promise.finally((()=>{Ye.#Ai.delete(this),this.#ii=null,this.#hi=null})).catch((()=>{}))}static get fontFamilyMap(){const{isWindows:t,isFirefox:e}=O.platform;return E(this,"fontFamilyMap",new Map([["sans-serif",(t&&e?"Calibri, ":"")+"sans-serif"],["monospace",(t&&e?"Lucida Console, ":"")+"monospace"]]))}render(){const t=()=>{this.#ai.read().then((({value:e,done:i})=>{i?this.#Je.resolve():(this.#ei??=e.lang,Object.assign(this.#hi,e.styles),this.#wi(e.items),t())}),this.#Je.reject)};return this.#ai=this.#ci.getReader(),Ye.#Ai.add(this),t(),this.#Je.promise}update({viewport:t,onBefore:e=null}){const i=t.scale*(globalThis.devicePixelRatio||1),s=t.rotation;if(s!==this.#oi&&(e?.(),this.#oi=s,bt(this.#ri,{rotation:s})),i!==this.#li){e?.(),this.#li=i;const t={div:null,properties:null,ctx:Ye.#_i(this.#ei)};for(const e of this.#ui)t.properties=this.#pi.get(e),t.div=e,this.#xi(t)}}cancel(){const t=new D("TextLayer task cancelled.");this.#ai?.cancel(t).catch((()=>{})),this.#ai=null,this.#Je.reject(t)}get textDivs(){return this.#ui}get textContentItemsStr(){return this.#di}#wi(t){if(this.#Ze)return;this.#ii.ctx??=Ye.#_i(this.#ei);const e=this.#ui,i=this.#di;for(const s of t){if(e.length>1e5)return w("Ignoring additional textDivs for performance reasons."),void(this.#Ze=!0);if(void 0!==s.str)i.push(s.str),this.#Ci(s);else if("beginMarkedContentProps"===s.type||"beginMarkedContent"===s.type){const t=this.#ut;this.#ut=document.createElement("span"),this.#ut.classList.add("markedContent"),null!==s.id&&this.#ut.setAttribute("id",`${s.id}`),t.append(this.#ut)}else"endMarkedContent"===s.type&&(this.#ut=this.#ut.parentNode)}}#Ci(t){const e=document.createElement("span"),i={angle:0,canvasWidth:0,hasText:""!==t.str,hasEOL:t.hasEOL,fontSize:0};this.#ui.push(e);const s=z.transform(this.#gi,t.transform);let n=Math.atan2(s[1],s[0]);const a=this.#hi[t.fontName];a.vertical&&(n+=Math.PI/2);let r=this.#ti&&a.fontSubstitution||a.fontFamily;r=Ye.fontFamilyMap.get(r)||r;const o=Math.hypot(s[2],s[3]),l=o*Ye.#Ei(r,this.#ei);let h,d;0===n?(h=s[4],d=s[5]-l):(h=s[4]+l*Math.sin(n),d=s[5]-l*Math.cos(n));const c="calc(var(--scale-factor)*",u=e.style;this.#ut===this.#ri?(u.left=`${(100*h/this.#ni).toFixed(2)}%`,u.top=`${(100*d/this.#si).toFixed(2)}%`):(u.left=`${c}${h.toFixed(2)}px)`,u.top=`${c}${d.toFixed(2)}px)`),u.fontSize=`${c}${(Ye.#vi*o).toFixed(2)}px)`,u.fontFamily=r,i.fontSize=o,e.setAttribute("role","presentation"),e.textContent=t.str,e.dir=t.dir,this.#ti&&(e.dataset.fontName=a.fontSubstitutionLoadedName||t.fontName),0!==n&&(i.angle=n*(180/Math.PI));let p=!1;if(t.str.length>1)p=!0;else if(" "!==t.str&&t.transform[0]!==t.transform[3]){const e=Math.abs(t.transform[0]),i=Math.abs(t.transform[3]);e!==i&&Math.max(e,i)/Math.min(e,i)>1.5&&(p=!0)}if(p&&(i.canvasWidth=a.vertical?t.height:t.width),this.#pi.set(e,i),this.#ii.div=e,this.#ii.properties=i,this.#xi(this.#ii),i.hasText&&this.#ut.append(e),i.hasEOL){const t=document.createElement("br");t.setAttribute("role","presentation"),this.#ut.append(t)}}#xi(t){const{div:e,properties:i,ctx:s}=t,{style:n}=e;let a="";if(Ye.#vi>1&&(a=`scale(${1/Ye.#vi})`),0!==i.canvasWidth&&i.hasText){const{fontFamily:t}=n,{canvasWidth:r,fontSize:o}=i;Ye.#Si(s,o*this.#li,t);const{width:l}=s.measureText(e.textContent);l>0&&(a=`scaleX(${r*this.#li/l}) ${a}`)}0!==i.angle&&(a=`rotate(${i.angle}deg) ${a}`),a.length>0&&(n.transform=a)}static cleanup(){if(!(this.#Ai.size>0)){this.#mi.clear();for(const{canvas:t}of this.#fi.values())t.remove();this.#fi.clear()}}static#_i(t=null){let e=this.#fi.get(t||="");if(!e){const i=document.createElement("canvas");i.className="hiddenCanvasElement",i.lang=t,document.body.append(i),e=i.getContext("2d",{alpha:!1,willReadFrequently:!0}),this.#fi.set(t,e),this.#bi.set(e,{size:0,family:""})}return e}static#Si(t,e,i){const s=this.#bi.get(t);e===s.size&&i===s.family||(t.font=`${e}px ${i}`,s.size=e,s.family=i)}static#yi(){if(null!==this.#vi)return;const t=document.createElement("div");t.style.opacity=0,t.style.lineHeight=1,t.style.fontSize="1px",t.style.position="absolute",t.textContent="X",document.body.append(t),this.#vi=t.getBoundingClientRect().height,t.remove()}static#Ei(t,e){const i=this.#mi.get(t);if(i)return i;const s=this.#_i(e);s.canvas.width=s.canvas.height=Ke,this.#Si(s,Ke,t);const n=s.measureText("");let a=n.fontBoundingBoxAscent,r=Math.abs(n.fontBoundingBoxDescent);if(a){const e=a/(a+r);return this.#mi.set(t,e),s.canvas.width=s.canvas.height=0,e}s.strokeStyle="red",s.clearRect(0,0,Ke,Ke),s.strokeText("g",0,0);let o=s.getImageData(0,0,Ke,Ke).data;r=0;for(let t=o.length-1-3;t>=0;t-=4)if(o[t]>0){r=Math.ceil(t/4/Ke);break}s.clearRect(0,0,Ke,Ke),s.strokeText("A",0,Ke),o=s.getImageData(0,0,Ke,Ke).data,a=0;for(let t=0,e=o.length;t0){a=Ke-Math.floor(t/4/Ke);break}s.canvas.width=s.canvas.height=0;const l=a?a/(a+r):.8;return this.#mi.set(t,l),l}}class Qe{static textContent(t){const e=[],i={items:e,styles:Object.create(null)};return function t(i){if(!i)return;let s=null;const n=i.name;if("#text"===n)s=i.value;else{if(!Qe.shouldBuildText(n))return;i?.attributes?.textContent?s=i.attributes.textContent:i.value&&(s=i.value)}if(null!==s&&e.push({str:s}),i.children)for(const e of i.children)t(e)}(t),i}static shouldBuildText(t){return!("textarea"===t||"input"===t||"option"===t||"select"===t)}}const Je=n?class extends G{_createCanvas(t,e){return Ut.get("canvas").createCanvas(t,e)}}:class extends G{constructor({ownerDocument:t=globalThis.document,enableHWA:e=!1}){super({enableHWA:e}),this._document=t}_createCanvas(t,e){const i=this._document.createElement("canvas");return i.width=t,i.height=e,i}},Ze=n?class extends V{_fetchData(t,e){return $t(t).then((t=>({cMapData:t,compressionType:e})))}}:J,ti=n?class extends W{}:class extends W{#Ti;#Mi;#ki;#Ii;#Pi;#Ri;#A=0;constructor({docId:t,ownerDocument:e=globalThis.document}){super(),this.#Ii=t,this.#Pi=e}get#w(){return this.#Mi||=new Map}get#Di(){return this.#Ri||=new Map}get#Li(){if(!this.#ki){const t=this.#Pi.createElement("div"),{style:e}=t;e.visibility="hidden",e.contain="strict",e.width=e.height=0,e.position="absolute",e.top=e.left=0,e.zIndex=-1;const i=this.#Pi.createElementNS(K,"svg");i.setAttribute("width",0),i.setAttribute("height",0),this.#ki=this.#Pi.createElementNS(K,"defs"),t.append(i),i.append(this.#ki),this.#Pi.body.append(t)}return this.#ki}#Fi(t){if(1===t.length){const e=t[0],i=new Array(256);for(let t=0;t<256;t++)i[t]=e[t]/255;const s=i.join(",");return[s,s,s]}const[e,i,s]=t,n=new Array(256),a=new Array(256),r=new Array(256);for(let t=0;t<256;t++)n[t]=e[t]/255,a[t]=i[t]/255,r[t]=s[t]/255;return[n.join(","),a.join(","),r.join(",")]}#Ni(t){if(void 0===this.#Ti){this.#Ti="";const t=this.#Pi.URL;t!==this.#Pi.baseURI&&(st(t)?w('#createUrl: ignore "data:"-URL for performance reasons.'):this.#Ti=t.split("#",1)[0])}return`url(${this.#Ti}#${t})`}addFilter(t){if(!t)return"none";let e=this.#w.get(t);if(e)return e;const[i,s,n]=this.#Fi(t),a=1===t.length?i:`${i}${s}${n}`;if(e=this.#w.get(a),e)return this.#w.set(t,e),e;const r=`g_${this.#Ii}_transfer_map_${this.#A++}`,o=this.#Ni(r);this.#w.set(t,o),this.#w.set(a,o);const l=this.#Oi(r);return this.#Bi(i,s,n,l),o}addHCMFilter(t,e){const i=`${t}-${e}`,s="base";let n=this.#Di.get(s);if(n?.key===i)return n.url;if(n?(n.filter?.remove(),n.key=i,n.url="none",n.filter=null):(n={key:i,url:"none",filter:null},this.#Di.set(s,n)),!t||!e)return n.url;const a=this.#zi(t);t=z.makeHexColor(...a);const r=this.#zi(e);if(e=z.makeHexColor(...r),this.#Li.style.color="","#000000"===t&&"#ffffff"===e||t===e)return n.url;const o=new Array(256);for(let t=0;t<=255;t++){const e=t/255;o[t]=e<=.03928?e/12.92:((e+.055)/1.055)**2.4}const l=o.join(","),h=`g_${this.#Ii}_hcm_filter`,d=n.filter=this.#Oi(h);this.#Bi(l,l,l,d),this.#Hi(d);const c=(t,e)=>{const i=a[t]/255,s=r[t]/255,n=new Array(e+1);for(let t=0;t<=e;t++)n[t]=i+t/e*(s-i);return n.join(",")};return this.#Bi(c(0,5),c(1,5),c(2,5),d),n.url=this.#Ni(h),n.url}addAlphaFilter(t){let e=this.#w.get(t);if(e)return e;const[i]=this.#Fi([t]),s=`alpha_${i}`;if(e=this.#w.get(s),e)return this.#w.set(t,e),e;const n=`g_${this.#Ii}_alpha_map_${this.#A++}`,a=this.#Ni(n);this.#w.set(t,a),this.#w.set(s,a);const r=this.#Oi(n);return this.#ji(i,r),a}addLuminosityFilter(t){let e,i,s=this.#w.get(t||"luminosity");if(s)return s;if(t?([e]=this.#Fi([t]),i=`luminosity_${e}`):i="luminosity",s=this.#w.get(i),s)return this.#w.set(t,s),s;const n=`g_${this.#Ii}_luminosity_map_${this.#A++}`,a=this.#Ni(n);this.#w.set(t,a),this.#w.set(i,a);const r=this.#Oi(n);return this.#Ui(r),t&&this.#ji(e,r),a}addHighlightHCMFilter(t,e,i,s,n){const a=`${e}-${i}-${s}-${n}`;let r=this.#Di.get(t);if(r?.key===a)return r.url;if(r?(r.filter?.remove(),r.key=a,r.url="none",r.filter=null):(r={key:a,url:"none",filter:null},this.#Di.set(t,r)),!e||!i)return r.url;const[o,l]=[e,i].map(this.#zi.bind(this));let h=Math.round(.2126*o[0]+.7152*o[1]+.0722*o[2]),d=Math.round(.2126*l[0]+.7152*l[1]+.0722*l[2]),[c,u]=[s,n].map(this.#zi.bind(this));d{const s=new Array(256),n=(d-h)/i,a=t/255,r=(e-t)/(255*i);let o=0;for(let t=0;t<=i;t++){const e=Math.round(h+t*n),i=a+t*r;for(let t=o;t<=e;t++)s[t]=i;o=e+1}for(let t=o;t<256;t++)s[t]=s[o-1];return s.join(",")},g=`g_${this.#Ii}_hcm_${t}_filter`,m=r.filter=this.#Oi(g);return this.#Hi(m),this.#Bi(p(c[0],u[0],5),p(c[1],u[1],5),p(c[2],u[2],5),m),r.url=this.#Ni(g),r.url}destroy(t=!1){t&&0!==this.#Di.size||(this.#ki&&(this.#ki.parentNode.parentNode.remove(),this.#ki=null),this.#Mi&&(this.#Mi.clear(),this.#Mi=null),this.#A=0)}#Ui(t){const e=this.#Pi.createElementNS(K,"feColorMatrix");e.setAttribute("type","matrix"),e.setAttribute("values","0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0.59 0.11 0 0"),t.append(e)}#Hi(t){const e=this.#Pi.createElementNS(K,"feColorMatrix");e.setAttribute("type","matrix"),e.setAttribute("values","0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0"),t.append(e)}#Oi(t){const e=this.#Pi.createElementNS(K,"filter");return e.setAttribute("color-interpolation-filters","sRGB"),e.setAttribute("id",t),this.#Li.append(e),e}#$i(t,e,i){const s=this.#Pi.createElementNS(K,e);s.setAttribute("type","discrete"),s.setAttribute("tableValues",i),t.append(s)}#Bi(t,e,i,s){const n=this.#Pi.createElementNS(K,"feComponentTransfer");s.append(n),this.#$i(n,"feFuncR",t),this.#$i(n,"feFuncG",e),this.#$i(n,"feFuncB",i)}#ji(t,e){const i=this.#Pi.createElementNS(K,"feComponentTransfer");e.append(i),this.#$i(i,"feFuncA",t)}#zi(t){return this.#Li.style.color=t,gt(getComputedStyle(this.#Li).getPropertyValue("color"))}},ei=n?class extends q{_fetchData(t){return $t(t)}}:Z;function ii(t={}){"string"==typeof t||t instanceof URL?t={url:t}:(t instanceof ArrayBuffer||ArrayBuffer.isView(t))&&(t={data:t});const e=new ni,{docId:i}=e,s=t.url?function(t){if(t instanceof URL)return t.href;try{return new URL(t,window.location).href}catch{if(n&&"string"==typeof t)return t}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}(t.url):null,a=t.data?function(t){if(n&&"undefined"!=typeof Buffer&&t instanceof Buffer)throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");if(t instanceof Uint8Array&&t.byteLength===t.buffer.byteLength)return t;if("string"==typeof t)return F(t);if(t instanceof ArrayBuffer||ArrayBuffer.isView(t)||"object"==typeof t&&!isNaN(t?.length))return new Uint8Array(t);throw new Error("Invalid PDF binary data: either TypedArray, string, or array-like object is expected in the data property.")}(t.data):null,r=t.httpHeaders||null,o=!0===t.withCredentials,l=t.password??null,h=t.range instanceof ai?t.range:null,d=Number.isInteger(t.rangeChunkSize)&&t.rangeChunkSize>0?t.rangeChunkSize:65536;let c=t.worker instanceof hi?t.worker:null;const u=t.verbosity,p="string"!=typeof t.docBaseUrl||st(t.docBaseUrl)?null:t.docBaseUrl,g="string"==typeof t.cMapUrl?t.cMapUrl:null,m=!1!==t.cMapPacked,f=t.CMapReaderFactory||Ze,b="string"==typeof t.standardFontDataUrl?t.standardFontDataUrl:null,A=t.StandardFontDataFactory||ei,y=!0!==t.stopAtErrors,w=Number.isInteger(t.maxImageSize)&&t.maxImageSize>-1?t.maxImageSize:-1,_=!1!==t.isEvalSupported,x="boolean"==typeof t.isOffscreenCanvasSupported?t.isOffscreenCanvasSupported:!n,C=Number.isInteger(t.canvasMaxAreaInBytes)?t.canvasMaxAreaInBytes:-1,E="boolean"==typeof t.disableFontFace?t.disableFontFace:n,S=!0===t.fontExtraProperties,T=!0===t.enableXfa,M=t.ownerDocument||globalThis.document,k=!0===t.disableRange,I=!0===t.disableStream,P=!0===t.disableAutoFetch,R=!0===t.pdfBug,D=t.CanvasFactory||Je,L=t.FilterFactory||ti,N=!0===t.enableHWA,O=h?h.length:t.length??NaN,B="boolean"==typeof t.useSystemFonts?t.useSystemFonts:!n&&!E,z="boolean"==typeof t.useWorkerFetch?t.useWorkerFetch:f===J&&A===Z&&g&&b&<(g,document.baseURI)&<(b,document.baseURI);t.canvasFactory&&dt("`canvasFactory`-instance option, please use `CanvasFactory` instead."),t.filterFactory&&dt("`filterFactory`-instance option, please use `FilterFactory` instead."),v(u);const H={canvasFactory:new D({ownerDocument:M,enableHWA:N}),filterFactory:new L({docId:i,ownerDocument:M}),cMapReaderFactory:z?null:new f({baseUrl:g,isCompressed:m}),standardFontDataFactory:z?null:new A({baseUrl:b})};if(!c){const t={verbosity:u,port:fe.workerPort};c=t.port?hi.fromPort(t):new hi(t),e._worker=c}const j={docId:i,apiVersion:"4.7.76",data:a,password:l,disableAutoFetch:P,rangeChunkSize:d,length:O,docBaseUrl:p,enableXfa:T,evaluatorOptions:{maxImageSize:w,disableFontFace:E,ignoreErrors:y,isEvalSupported:_,isOffscreenCanvasSupported:x,canvasMaxAreaInBytes:C,fontExtraProperties:S,useSystemFonts:B,cMapUrl:z?g:null,standardFontDataUrl:z?b:null}},U={disableFontFace:E,fontExtraProperties:S,ownerDocument:M,pdfBug:R,styleElement:null,loadingParams:{disableAutoFetch:P,enableXfa:T}};return c.promise.then((function(){if(e.destroyed)throw new Error("Loading aborted");if(c.destroyed)throw new Error("Worker was destroyed");const t=c.messageHandler.sendWithPromise("GetDocRequest",j,a?[a.buffer]:null);let l;if(h)l=new xe(h,{disableRange:k,disableStream:I});else if(!a){if(!s)throw new Error("getDocument - no `url` parameter provided.");let t;t=n?"undefined"!=typeof fetch&&"undefined"!=typeof Response&&"body"in Response.prototype&<(s)?De:Ue:lt(s)?De:Oe,l=new t({url:s,length:O,httpHeaders:r,withCredentials:o,rangeChunkSize:d,disableRange:k,disableStream:I})}return t.then((t=>{if(e.destroyed)throw new Error("Loading aborted");if(c.destroyed)throw new Error("Worker was destroyed");const s=new ve(i,t,c.port),n=new di(s,e,l,U,H);e._transport=n,s.send("Ready",null)}))})).catch(e._capability.reject),e}function si(t){return"object"==typeof t&&Number.isInteger(t?.num)&&t.num>=0&&Number.isInteger(t?.gen)&&t.gen>=0}class ni{static#Ii=0;constructor(){this._capability=Promise.withResolvers(),this._transport=null,this._worker=null,this.docId="d"+ni.#Ii++,this.destroyed=!1,this.onPassword=null,this.onProgress=null}get promise(){return this._capability.promise}async destroy(){this.destroyed=!0;try{this._worker?.port&&(this._worker._pendingDestroy=!0),await(this._transport?.destroy())}catch(t){throw this._worker?.port&&delete this._worker._pendingDestroy,t}this._transport=null,this._worker&&(this._worker.destroy(),this._worker=null)}}class ai{constructor(t,e,i=!1,s=null){this.length=t,this.initialData=e,this.progressiveDone=i,this.contentDispositionFilename=s,this._rangeListeners=[],this._progressListeners=[],this._progressiveReadListeners=[],this._progressiveDoneListeners=[],this._readyCapability=Promise.withResolvers()}addRangeListener(t){this._rangeListeners.push(t)}addProgressListener(t){this._progressListeners.push(t)}addProgressiveReadListener(t){this._progressiveReadListeners.push(t)}addProgressiveDoneListener(t){this._progressiveDoneListeners.push(t)}onDataRange(t,e){for(const i of this._rangeListeners)i(t,e)}onDataProgress(t,e){this._readyCapability.promise.then((()=>{for(const i of this._progressListeners)i(t,e)}))}onDataProgressiveRead(t){this._readyCapability.promise.then((()=>{for(const e of this._progressiveReadListeners)e(t)}))}onDataProgressiveDone(){this._readyCapability.promise.then((()=>{for(const t of this._progressiveDoneListeners)t()}))}transportReady(){this._readyCapability.resolve()}requestDataRange(t,e){_("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class ri{constructor(t,e){this._pdfInfo=t,this._transport=e}get annotationStorage(){return this._transport.annotationStorage}get canvasFactory(){return this._transport.canvasFactory}get filterFactory(){return this._transport.filterFactory}get numPages(){return this._pdfInfo.numPages}get fingerprints(){return this._pdfInfo.fingerprints}get isPureXfa(){return E(this,"isPureXfa",!!this._transport._htmlForXfa)}get allXfaHtml(){return this._transport._htmlForXfa}getPage(t){return this._transport.getPage(t)}getPageIndex(t){return this._transport.getPageIndex(t)}getDestinations(){return this._transport.getDestinations()}getDestination(t){return this._transport.getDestination(t)}getPageLabels(){return this._transport.getPageLabels()}getPageLayout(){return this._transport.getPageLayout()}getPageMode(){return this._transport.getPageMode()}getViewerPreferences(){return this._transport.getViewerPreferences()}getOpenAction(){return this._transport.getOpenAction()}getAttachments(){return this._transport.getAttachments()}getJSActions(){return this._transport.getDocJSActions()}getOutline(){return this._transport.getOutline()}getOptionalContentConfig({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getOptionalContentConfig(e)}getPermissions(){return this._transport.getPermissions()}getMetadata(){return this._transport.getMetadata()}getMarkInfo(){return this._transport.getMarkInfo()}getData(){return this._transport.getData()}saveDocument(){return this._transport.saveDocument()}getDownloadInfo(){return this._transport.downloadInfoCapability.promise}cleanup(t=!1){return this._transport.startCleanup(t||this.isPureXfa)}destroy(){return this.loadingTask.destroy()}cachedPageNumber(t){return this._transport.cachedPageNumber(t)}get loadingParams(){return this._transport.loadingParams}get loadingTask(){return this._transport.loadingTask}getFieldObjects(){return this._transport.getFieldObjects()}hasJSActions(){return this._transport.hasJSActions()}getCalculationOrderIds(){return this._transport.getCalculationOrderIds()}}class oi{#Wi=null;#Gi=!1;constructor(t,e,i,s=!1){this._pageIndex=t,this._pageInfo=e,this._transport=i,this._stats=s?new ot:null,this._pdfBug=s,this.commonObjs=i.commonObjs,this.objs=new ui,this._maybeCleanupAfterRender=!1,this._intentStates=new Map,this.destroyed=!1}get pageNumber(){return this._pageIndex+1}get rotate(){return this._pageInfo.rotate}get ref(){return this._pageInfo.ref}get userUnit(){return this._pageInfo.userUnit}get view(){return this._pageInfo.view}getViewport({scale:t,rotation:e=this.rotate,offsetX:i=0,offsetY:s=0,dontFlip:n=!1}={}){return new et({viewBox:this.view,scale:t,rotation:e,offsetX:i,offsetY:s,dontFlip:n})}getAnnotations({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getAnnotations(this._pageIndex,e)}getJSActions(){return this._transport.getPageJSActions(this._pageIndex)}get filterFactory(){return this._transport.filterFactory}get isPureXfa(){return E(this,"isPureXfa",!!this._transport._htmlForXfa)}async getXfa(){return this._transport._htmlForXfa?.children[this._pageIndex]||null}render({canvasContext:t,viewport:e,intent:i="display",annotationMode:s=l.ENABLE,transform:n=null,background:a=null,optionalContentConfigPromise:r=null,annotationCanvasMap:o=null,pageColors:h=null,printAnnotationStorage:d=null,isEditing:c=!1}){this._stats?.time("Overall");const u=this._transport.getRenderingIntent(i,s,d,c),{renderingIntent:p,cacheKey:g}=u;this.#Gi=!1,this.#Vi(),r||=this._transport.getOptionalContentConfig(p);let m=this._intentStates.get(g);m||(m=Object.create(null),this._intentStates.set(g,m)),m.streamReaderCancelTimeout&&(clearTimeout(m.streamReaderCancelTimeout),m.streamReaderCancelTimeout=null);const f=!!(4&p);m.displayReadyCapability||(m.displayReadyCapability=Promise.withResolvers(),m.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(u));const b=t=>{m.renderTasks.delete(v),(this._maybeCleanupAfterRender||f)&&(this.#Gi=!0),this.#qi(!f),t?(v.capability.reject(t),this._abortOperatorList({intentState:m,reason:t instanceof Error?t:new Error(t)})):v.capability.resolve(),this._stats&&(this._stats.timeEnd("Rendering"),this._stats.timeEnd("Overall"),globalThis.Stats?.enabled&&globalThis.Stats.add(this.pageNumber,this._stats))},v=new gi({callback:b,params:{canvasContext:t,viewport:e,transform:n,background:a},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:o,operatorList:m.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!f,pdfBug:this._pdfBug,pageColors:h});(m.renderTasks||=new Set).add(v);const A=v.task;return Promise.all([m.displayReadyCapability.promise,r]).then((([t,e])=>{if(this.destroyed)b();else{if(this._stats?.time("Rendering"),!(e.renderingIntent&p))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");v.initializeGraphics({transparency:t,optionalContentConfig:e}),v.operatorListChanged()}})).catch(b),A}getOperatorList({intent:t="display",annotationMode:e=l.ENABLE,printAnnotationStorage:i=null,isEditing:s=!1}={}){const n=this._transport.getRenderingIntent(t,e,i,s,!0);let a,r=this._intentStates.get(n.cacheKey);return r||(r=Object.create(null),this._intentStates.set(n.cacheKey,r)),r.opListReadCapability||(a=Object.create(null),a.operatorListChanged=function(){r.operatorList.lastChunk&&(r.opListReadCapability.resolve(r.operatorList),r.renderTasks.delete(a))},r.opListReadCapability=Promise.withResolvers(),(r.renderTasks||=new Set).add(a),r.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(n)),r.opListReadCapability.promise}streamTextContent({includeMarkedContent:t=!1,disableNormalization:e=!1}={}){return this._transport.messageHandler.sendWithStream("GetTextContent",{pageIndex:this._pageIndex,includeMarkedContent:!0===t,disableNormalization:!0===e},{highWaterMark:100,size:t=>t.items.length})}getTextContent(t={}){if(this._transport._htmlForXfa)return this.getXfa().then((t=>Qe.textContent(t)));const e=this.streamTextContent(t);return new Promise((function(t,i){const s=e.getReader(),n={items:[],styles:Object.create(null),lang:null};!function e(){s.read().then((function({value:i,done:s}){s?t(n):(n.lang??=i.lang,Object.assign(n.styles,i.styles),n.items.push(...i.items),e())}),i)}()}))}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;const t=[];for(const e of this._intentStates.values())if(this._abortOperatorList({intentState:e,reason:new Error("Page was destroyed."),force:!0}),!e.opListReadCapability)for(const i of e.renderTasks)t.push(i.completed),i.cancel();return this.objs.clear(),this.#Gi=!1,this.#Vi(),Promise.all(t)}cleanup(t=!1){this.#Gi=!0;const e=this.#qi(!1);return t&&e&&(this._stats&&=new ot),e}#qi(t=!1){if(this.#Vi(),!this.#Gi||this.destroyed)return!1;if(t)return this.#Wi=setTimeout((()=>{this.#Wi=null,this.#qi(!1)}),5e3),!1;for(const{renderTasks:t,operatorList:e}of this._intentStates.values())if(t.size>0||!e.lastChunk)return!1;return this._intentStates.clear(),this.objs.clear(),this.#Gi=!1,!0}#Vi(){this.#Wi&&(clearTimeout(this.#Wi),this.#Wi=null)}_startRenderPage(t,e){const i=this._intentStates.get(e);i&&(this._stats?.timeEnd("Page Request"),i.displayReadyCapability?.resolve(t))}_renderPageChunk(t,e){for(let i=0,s=t.length;i{r.read().then((({value:t,done:e})=>{e?o.streamReader=null:this._transport.destroyed||(this._renderPageChunk(t,o),l())}),(t=>{if(o.streamReader=null,!this._transport.destroyed){if(o.operatorList){o.operatorList.lastChunk=!0;for(const t of o.renderTasks)t.operatorListChanged();this.#qi(!0)}if(o.displayReadyCapability)o.displayReadyCapability.reject(t);else{if(!o.opListReadCapability)throw t;o.opListReadCapability.reject(t)}}}))};l()}_abortOperatorList({intentState:t,reason:e,force:i=!1}){if(t.streamReader){if(t.streamReaderCancelTimeout&&(clearTimeout(t.streamReaderCancelTimeout),t.streamReaderCancelTimeout=null),!i){if(t.renderTasks.size>0)return;if(e instanceof it){let i=100;return e.extraDelay>0&&e.extraDelay<1e3&&(i+=e.extraDelay),void(t.streamReaderCancelTimeout=setTimeout((()=>{t.streamReaderCancelTimeout=null,this._abortOperatorList({intentState:t,reason:e,force:!0})}),i))}}if(t.streamReader.cancel(new D(e.message)).catch((()=>{})),t.streamReader=null,!this._transport.destroyed){for(const[e,i]of this._intentStates)if(i===t){this._intentStates.delete(e);break}this.cleanup()}}}get stats(){return this._stats}}class li{#Xi=new Set;#Ki=Promise.resolve();postMessage(t,e){const i={data:structuredClone(t,e?{transfer:e}:null)};this.#Ki.then((()=>{for(const t of this.#Xi)t.call(this,i)}))}addEventListener(t,e){this.#Xi.add(e)}removeEventListener(t,e){this.#Xi.delete(e)}terminate(){this.#Xi.clear()}}class hi{static#Yi=0;static#Qi=!1;static#Ji;static{n&&(this.#Qi=!0,fe.workerSrc||="./pdf.worker.mjs"),this._isSameOrigin=(t,e)=>{let i;try{if(i=new URL(t),!i.origin||"null"===i.origin)return!1}catch{return!1}const s=new URL(e,i);return i.origin===s.origin},this._createCDNWrapper=t=>{const e=`await import("${t}");`;return URL.createObjectURL(new Blob([e],{type:"text/javascript"}))}}constructor({name:t=null,port:e=null,verbosity:i=A()}={}){if(this.name=t,this.destroyed=!1,this.verbosity=i,this._readyCapability=Promise.withResolvers(),this._port=null,this._webWorker=null,this._messageHandler=null,e){if(hi.#Ji?.has(e))throw new Error("Cannot use more than one PDFWorker per port.");return(hi.#Ji||=new WeakMap).set(e,this),void this._initializeFromPort(e)}this._initialize()}get promise(){return n?Promise.all([Ut.promise,this._readyCapability.promise]):this._readyCapability.promise}#Zi(){this._readyCapability.resolve(),this._messageHandler.send("configure",{verbosity:this.verbosity})}get port(){return this._port}get messageHandler(){return this._messageHandler}_initializeFromPort(t){this._port=t,this._messageHandler=new ve("main","worker",t),this._messageHandler.on("ready",(function(){})),this.#Zi()}_initialize(){if(hi.#Qi||hi.#ts)return void this._setupFakeWorker();let{workerSrc:t}=hi;try{hi._isSameOrigin(window.location.href,t)||(t=hi._createCDNWrapper(new URL(t,window.location).href));const e=new Worker(t,{type:"module"}),i=new ve("main","worker",e),s=()=>{n.abort(),i.destroy(),e.terminate(),this.destroyed?this._readyCapability.reject(new Error("Worker was destroyed")):this._setupFakeWorker()},n=new AbortController;e.addEventListener("error",(()=>{this._webWorker||s()}),{signal:n.signal}),i.on("test",(t=>{n.abort(),!this.destroyed&&t?(this._messageHandler=i,this._port=e,this._webWorker=e,this.#Zi()):s()})),i.on("ready",(t=>{if(n.abort(),this.destroyed)s();else try{a()}catch{this._setupFakeWorker()}}));const a=()=>{const t=new Uint8Array;i.send("test",t,[t.buffer])};return void a()}catch{y("The worker has been disabled.")}this._setupFakeWorker()}_setupFakeWorker(){hi.#Qi||(w("Setting up fake worker."),hi.#Qi=!0),hi._setupFakeWorkerGlobal.then((t=>{if(this.destroyed)return void this._readyCapability.reject(new Error("Worker was destroyed"));const e=new li;this._port=e;const i="fake"+hi.#Yi++,s=new ve(i+"_worker",i,e);t.setup(s,e),this._messageHandler=new ve(i,i+"_worker",e),this.#Zi()})).catch((t=>{this._readyCapability.reject(new Error(`Setting up fake worker failed: "${t.message}".`))}))}destroy(){this.destroyed=!0,this._webWorker&&(this._webWorker.terminate(),this._webWorker=null),hi.#Ji?.delete(this._port),this._port=null,this._messageHandler&&(this._messageHandler.destroy(),this._messageHandler=null)}static fromPort(t){if(!t?.port)throw new Error("PDFWorker.fromPort - invalid method signature.");const e=this.#Ji?.get(t.port);if(e){if(e._pendingDestroy)throw new Error("PDFWorker.fromPort - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return e}return new hi(t)}static get workerSrc(){if(fe.workerSrc)return fe.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get#ts(){try{return globalThis.pdfjsWorker?.WorkerMessageHandler||null}catch{return null}}static get _setupFakeWorkerGlobal(){return E(this,"_setupFakeWorkerGlobal",(async()=>this.#ts?this.#ts:(await import(this.workerSrc)).WorkerMessageHandler)())}}class di{#es=new Map;#is=new Map;#ss=new Map;#ns=new Map;#as=null;constructor(t,e,i,s,n){this.messageHandler=t,this.loadingTask=e,this.commonObjs=new ui,this.fontLoader=new Bt({ownerDocument:s.ownerDocument,styleElement:s.styleElement}),this.loadingParams=s.loadingParams,this._params=s,this.canvasFactory=n.canvasFactory,this.filterFactory=n.filterFactory,this.cMapReaderFactory=n.cMapReaderFactory,this.standardFontDataFactory=n.standardFontDataFactory,this.destroyed=!1,this.destroyCapability=null,this._networkStream=i,this._fullReader=null,this._lastProgress=null,this.downloadInfoCapability=Promise.withResolvers(),this.setupMessageHandler()}#rs(t,e=null){const i=this.#es.get(t);if(i)return i;const s=this.messageHandler.sendWithPromise(t,e);return this.#es.set(t,s),s}get annotationStorage(){return E(this,"annotationStorage",new Nt)}getRenderingIntent(t,e=l.ENABLE,i=null,s=!1,n=!1){let a=2,r=Ft;switch(t){case"any":a=1;break;case"display":break;case"print":a=4;break;default:w(`getRenderingIntent - invalid intent: ${t}`)}const o=4&a&&i instanceof Ot?i:this.annotationStorage;switch(e){case l.DISABLE:a+=64;break;case l.ENABLE:break;case l.ENABLE_FORMS:a+=16;break;case l.ENABLE_STORAGE:a+=32,r=o.serializable;break;default:w(`getRenderingIntent - invalid annotationMode: ${e}`)}s&&(a+=128),n&&(a+=256);const{ids:h,hash:d}=o.modifiedIds;return{renderingIntent:a,cacheKey:[a,r.hash,d].join("_"),annotationStorageSerializable:r,modifiedIds:h}}destroy(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=Promise.withResolvers(),this.#as?.reject(new Error("Worker was destroyed during onPassword callback"));const t=[];for(const e of this.#is.values())t.push(e._destroy());this.#is.clear(),this.#ss.clear(),this.#ns.clear(),this.hasOwnProperty("annotationStorage")&&this.annotationStorage.resetModified();const e=this.messageHandler.sendWithPromise("Terminate",null);return t.push(e),Promise.all(t).then((()=>{this.commonObjs.clear(),this.fontLoader.clear(),this.#es.clear(),this.filterFactory.destroy(),Ye.cleanup(),this._networkStream?.cancelAllRequests(new D("Worker was terminated.")),this.messageHandler&&(this.messageHandler.destroy(),this.messageHandler=null),this.destroyCapability.resolve()}),this.destroyCapability.reject),this.destroyCapability.promise}setupMessageHandler(){const{messageHandler:t,loadingTask:e}=this;t.on("GetReader",((t,e)=>{x(this._networkStream,"GetReader - no `IPDFStream` instance available."),this._fullReader=this._networkStream.getFullReader(),this._fullReader.onProgress=t=>{this._lastProgress={loaded:t.loaded,total:t.total}},e.onPull=()=>{this._fullReader.read().then((function({value:t,done:i}){i?e.close():(x(t instanceof ArrayBuffer,"GetReader - expected an ArrayBuffer."),e.enqueue(new Uint8Array(t),1,[t]))})).catch((t=>{e.error(t)}))},e.onCancel=t=>{this._fullReader.cancel(t),e.ready.catch((t=>{if(!this.destroyed)throw t}))}})),t.on("ReaderHeadersReady",(t=>{const i=Promise.withResolvers(),s=this._fullReader;return s.headersReady.then((()=>{s.isStreamingSupported&&s.isRangeSupported||(this._lastProgress&&e.onProgress?.(this._lastProgress),s.onProgress=t=>{e.onProgress?.({loaded:t.loaded,total:t.total})}),i.resolve({isStreamingSupported:s.isStreamingSupported,isRangeSupported:s.isRangeSupported,contentLength:s.contentLength})}),i.reject),i.promise})),t.on("GetRangeReader",((t,e)=>{x(this._networkStream,"GetRangeReader - no `IPDFStream` instance available.");const i=this._networkStream.getRangeReader(t.begin,t.end);i?(e.onPull=()=>{i.read().then((function({value:t,done:i}){i?e.close():(x(t instanceof ArrayBuffer,"GetRangeReader - expected an ArrayBuffer."),e.enqueue(new Uint8Array(t),1,[t]))})).catch((t=>{e.error(t)}))},e.onCancel=t=>{i.cancel(t),e.ready.catch((t=>{if(!this.destroyed)throw t}))}):e.close()})),t.on("GetDoc",(({pdfInfo:t})=>{this._numPages=t.numPages,this._htmlForXfa=t.htmlForXfa,delete t.htmlForXfa,e._capability.resolve(new ri(t,this))})),t.on("DocException",(function(t){let i;switch(t.name){case"PasswordException":i=new T(t.message,t.code);break;case"InvalidPDFException":i=new k(t.message);break;case"MissingPDFException":i=new I(t.message);break;case"UnexpectedResponseException":i=new P(t.message,t.status);break;case"UnknownErrorException":i=new M(t.message,t.details);break;default:_("DocException - expected a valid Error.")}e._capability.reject(i)})),t.on("PasswordRequest",(t=>{if(this.#as=Promise.withResolvers(),e.onPassword){const i=t=>{t instanceof Error?this.#as.reject(t):this.#as.resolve({password:t})};try{e.onPassword(i,t.code)}catch(t){this.#as.reject(t)}}else this.#as.reject(new T(t.message,t.code));return this.#as.promise})),t.on("DataLoaded",(t=>{e.onProgress?.({loaded:t.length,total:t.length}),this.downloadInfoCapability.resolve(t)})),t.on("StartRenderPage",(t=>{this.destroyed||this.#is.get(t.pageIndex)._startRenderPage(t.transparency,t.cacheKey)})),t.on("commonobj",(([e,i,s])=>{if(this.destroyed)return null;if(this.commonObjs.has(e))return null;switch(i){case"Font":const{disableFontFace:n,fontExtraProperties:a,pdfBug:r}=this._params;if("error"in s){const t=s.error;w(`Error during font loading: ${t}`),this.commonObjs.resolve(e,t);break}const o=r&&globalThis.FontInspector?.enabled?(t,e)=>globalThis.FontInspector.fontAdded(t,e):null,l=new zt(s,{disableFontFace:n,inspectFont:o});this.fontLoader.bind(l).catch((()=>t.sendWithPromise("FontFallback",{id:e}))).finally((()=>{!a&&l.data&&(l.data=null),this.commonObjs.resolve(e,l)}));break;case"CopyLocalImage":const{imageRef:h}=s;x(h,"The imageRef must be defined.");for(const t of this.#is.values())for(const[,i]of t.objs)if(i?.ref===h)return i.dataLen?(this.commonObjs.resolve(e,structuredClone(i)),i.dataLen):null;break;case"FontPath":case"Image":case"Pattern":this.commonObjs.resolve(e,s);break;default:throw new Error(`Got unknown common object type ${i}`)}return null})),t.on("obj",(([t,e,i,s])=>{if(this.destroyed)return;const n=this.#is.get(e);if(!n.objs.has(t))if(0!==n._intentStates.size)switch(i){case"Image":n.objs.resolve(t,s),s?.dataLen>1e7&&(n._maybeCleanupAfterRender=!0);break;case"Pattern":n.objs.resolve(t,s);break;default:throw new Error(`Got unknown object type ${i}`)}else s?.bitmap?.close()})),t.on("DocProgress",(t=>{this.destroyed||e.onProgress?.({loaded:t.loaded,total:t.total})})),t.on("FetchBuiltInCMap",(t=>this.destroyed?Promise.reject(new Error("Worker was destroyed.")):this.cMapReaderFactory?this.cMapReaderFactory.fetch(t):Promise.reject(new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter.")))),t.on("FetchStandardFontData",(t=>this.destroyed?Promise.reject(new Error("Worker was destroyed.")):this.standardFontDataFactory?this.standardFontDataFactory.fetch(t):Promise.reject(new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter."))))}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){this.annotationStorage.size<=0&&w("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");const{map:t,transfer:e}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:t,filename:this._fullReader?.filename??null},e).finally((()=>{this.annotationStorage.resetModified()}))}getPage(t){if(!Number.isInteger(t)||t<=0||t>this._numPages)return Promise.reject(new Error("Invalid page request."));const e=t-1,i=this.#ss.get(e);if(i)return i;const s=this.messageHandler.sendWithPromise("GetPage",{pageIndex:e}).then((i=>{if(this.destroyed)throw new Error("Transport destroyed");i.refStr&&this.#ns.set(i.refStr,t);const s=new oi(e,i,this,this._params.pdfBug);return this.#is.set(e,s),s}));return this.#ss.set(e,s),s}getPageIndex(t){return si(t)?this.messageHandler.sendWithPromise("GetPageIndex",{num:t.num,gen:t.gen}):Promise.reject(new Error("Invalid pageIndex request."))}getAnnotations(t,e){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:t,intent:e})}getFieldObjects(){return this.#rs("GetFieldObjects")}hasJSActions(){return this.#rs("HasJSActions")}getCalculationOrderIds(){return this.messageHandler.sendWithPromise("GetCalculationOrderIds",null)}getDestinations(){return this.messageHandler.sendWithPromise("GetDestinations",null)}getDestination(t){return"string"!=typeof t?Promise.reject(new Error("Invalid destination request.")):this.messageHandler.sendWithPromise("GetDestination",{id:t})}getPageLabels(){return this.messageHandler.sendWithPromise("GetPageLabels",null)}getPageLayout(){return this.messageHandler.sendWithPromise("GetPageLayout",null)}getPageMode(){return this.messageHandler.sendWithPromise("GetPageMode",null)}getViewerPreferences(){return this.messageHandler.sendWithPromise("GetViewerPreferences",null)}getOpenAction(){return this.messageHandler.sendWithPromise("GetOpenAction",null)}getAttachments(){return this.messageHandler.sendWithPromise("GetAttachments",null)}getDocJSActions(){return this.#rs("GetDocJSActions")}getPageJSActions(t){return this.messageHandler.sendWithPromise("GetPageJSActions",{pageIndex:t})}getStructTree(t){return this.messageHandler.sendWithPromise("GetStructTree",{pageIndex:t})}getOutline(){return this.messageHandler.sendWithPromise("GetOutline",null)}getOptionalContentConfig(t){return this.#rs("GetOptionalContentConfig").then((e=>new _e(e,t)))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const t="GetMetadata",e=this.#es.get(t);if(e)return e;const i=this.messageHandler.sendWithPromise(t,null).then((t=>({info:t[0],metadata:t[1]?new Ae(t[1]):null,contentDispositionFilename:this._fullReader?.filename??null,contentLength:this._fullReader?.contentLength??null})));return this.#es.set(t,i),i}getMarkInfo(){return this.messageHandler.sendWithPromise("GetMarkInfo",null)}async startCleanup(t=!1){if(!this.destroyed){await this.messageHandler.sendWithPromise("Cleanup",null);for(const t of this.#is.values())if(!t.cleanup())throw new Error(`startCleanup: Page ${t.pageNumber} is currently rendering.`);this.commonObjs.clear(),t||this.fontLoader.clear(),this.#es.clear(),this.filterFactory.destroy(!0),Ye.cleanup()}}cachedPageNumber(t){if(!si(t))return null;const e=0===t.gen?`${t.num}R`:`${t.num}R${t.gen}`;return this.#ns.get(e)??null}}const ci=Symbol("INITIAL_DATA");class ui{#os=Object.create(null);#ls(t){return this.#os[t]||={...Promise.withResolvers(),data:ci}}get(t,e=null){if(e){const i=this.#ls(t);return i.promise.then((()=>e(i.data))),null}const i=this.#os[t];if(!i||i.data===ci)throw new Error(`Requesting object that isn't resolved yet ${t}.`);return i.data}has(t){const e=this.#os[t];return!!e&&e.data!==ci}resolve(t,e=null){const i=this.#ls(t);i.data=e,i.resolve()}clear(){for(const t in this.#os){const{data:e}=this.#os[t];e?.bitmap?.close()}this.#os=Object.create(null)}*[Symbol.iterator](){for(const t in this.#os){const{data:e}=this.#os[t];e!==ci&&(yield[t,e])}}}class pi{#hs=null;constructor(t){this.#hs=t,this.onContinue=null}get promise(){return this.#hs.capability.promise}cancel(t=0){this.#hs.cancel(null,t)}get separateAnnots(){const{separateAnnots:t}=this.#hs.operatorList;if(!t)return!1;const{annotationCanvasMap:e}=this.#hs;return t.form||t.canvas&&e?.size>0}}class gi{#ds=null;static#cs=new WeakSet;constructor({callback:t,params:e,objs:i,commonObjs:s,annotationCanvasMap:n,operatorList:a,pageIndex:r,canvasFactory:o,filterFactory:l,useRequestAnimationFrame:h=!1,pdfBug:d=!1,pageColors:c=null}){this.callback=t,this.params=e,this.objs=i,this.commonObjs=s,this.annotationCanvasMap=n,this.operatorListIdx=null,this.operatorList=a,this._pageIndex=r,this.canvasFactory=o,this.filterFactory=l,this._pdfBug=d,this.pageColors=c,this.running=!1,this.graphicsReadyCallback=null,this.graphicsReady=!1,this._useRequestAnimationFrame=!0===h&&"undefined"!=typeof window,this.cancelled=!1,this.capability=Promise.withResolvers(),this.task=new pi(this),this._cancelBound=this.cancel.bind(this),this._continueBound=this._continue.bind(this),this._scheduleNextBound=this._scheduleNext.bind(this),this._nextBound=this._next.bind(this),this._canvas=e.canvasContext.canvas}get completed(){return this.capability.promise.catch((function(){}))}initializeGraphics({transparency:t=!1,optionalContentConfig:e}){if(this.cancelled)return;if(this._canvas){if(gi.#cs.has(this._canvas))throw new Error("Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.");gi.#cs.add(this._canvas)}this._pdfBug&&globalThis.StepperManager?.enabled&&(this.stepper=globalThis.StepperManager.create(this._pageIndex),this.stepper.init(this.operatorList),this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint());const{canvasContext:i,viewport:s,transform:n,background:a}=this.params;this.gfx=new me(i,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:e},this.annotationCanvasMap,this.pageColors),this.gfx.beginDrawing({transform:n,viewport:s,transparency:t,background:a}),this.operatorListIdx=0,this.graphicsReady=!0,this.graphicsReadyCallback?.()}cancel(t=null,e=0){this.running=!1,this.cancelled=!0,this.gfx?.endDrawing(),this.#ds&&(window.cancelAnimationFrame(this.#ds),this.#ds=null),gi.#cs.delete(this._canvas),this.callback(t||new it(`Rendering cancelled, page ${this._pageIndex+1}`,e))}operatorListChanged(){this.graphicsReady?(this.stepper?.updateOperatorList(this.operatorList),this.running||this._continue()):this.graphicsReadyCallback||=this._continueBound}_continue(){this.running=!0,this.cancelled||(this.task.onContinue?this.task.onContinue(this._scheduleNextBound):this._scheduleNext())}_scheduleNext(){this._useRequestAnimationFrame?this.#ds=window.requestAnimationFrame((()=>{this.#ds=null,this._nextBound().catch(this._cancelBound)})):Promise.resolve().then(this._nextBound).catch(this._cancelBound)}async _next(){this.cancelled||(this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper),this.operatorListIdx===this.operatorList.argsArray.length&&(this.running=!1,this.operatorList.lastChunk&&(this.gfx.endDrawing(),gi.#cs.delete(this._canvas),this.callback())))}}const mi="4.7.76",fi="8b73b828b";function bi(t){return Math.floor(255*Math.max(0,Math.min(1,t))).toString(16).padStart(2,"0")}function vi(t){return Math.max(0,Math.min(255,255*t))}class Ai{static CMYK_G([t,e,i,s]){return["G",1-Math.min(1,.3*t+.59*i+.11*e+s)]}static G_CMYK([t]){return["CMYK",0,0,0,1-t]}static G_RGB([t]){return["RGB",t,t,t]}static G_rgb([t]){return[t=vi(t),t,t]}static G_HTML([t]){const e=bi(t);return`#${e}${e}${e}`}static RGB_G([t,e,i]){return["G",.3*t+.59*e+.11*i]}static RGB_rgb(t){return t.map(vi)}static RGB_HTML(t){return`#${t.map(bi).join("")}`}static T_HTML(){return"#00000000"}static T_rgb(){return[null]}static CMYK_RGB([t,e,i,s]){return["RGB",1-Math.min(1,t+s),1-Math.min(1,i+s),1-Math.min(1,e+s)]}static CMYK_rgb([t,e,i,s]){return[vi(1-Math.min(1,t+s)),vi(1-Math.min(1,i+s)),vi(1-Math.min(1,e+s))]}static CMYK_HTML(t){const e=this.CMYK_RGB(t).slice(1);return this.RGB_HTML(e)}static RGB_CMYK([t,e,i]){const s=1-t,n=1-e,a=1-i;return["CMYK",s,n,a,Math.min(s,n,a)]}}class yi{static setupStorage(t,e,i,s,n){const a=s.getValue(e,{value:null});switch(i.name){case"textarea":if(null!==a.value&&(t.textContent=a.value),"print"===n)break;t.addEventListener("input",(t=>{s.setValue(e,{value:t.target.value})}));break;case"input":if("radio"===i.attributes.type||"checkbox"===i.attributes.type){if(a.value===i.attributes.xfaOn?t.setAttribute("checked",!0):a.value===i.attributes.xfaOff&&t.removeAttribute("checked"),"print"===n)break;t.addEventListener("change",(t=>{s.setValue(e,{value:t.target.checked?t.target.getAttribute("xfaOn"):t.target.getAttribute("xfaOff")})}))}else{if(null!==a.value&&t.setAttribute("value",a.value),"print"===n)break;t.addEventListener("input",(t=>{s.setValue(e,{value:t.target.value})}))}break;case"select":if(null!==a.value){t.setAttribute("value",a.value);for(const t of i.children)t.attributes.value===a.value?t.attributes.selected=!0:t.attributes.hasOwnProperty("selected")&&delete t.attributes.selected}t.addEventListener("input",(t=>{const i=t.target.options,n=-1===i.selectedIndex?"":i[i.selectedIndex].value;s.setValue(e,{value:n})}))}}static setAttributes({html:t,element:e,storage:i=null,intent:s,linkService:n}){const{attributes:a}=e,r=t instanceof HTMLAnchorElement;"radio"===a.type&&(a.name=`${a.name}-${s}`);for(const[e,i]of Object.entries(a))if(null!=i)switch(e){case"class":i.length&&t.setAttribute(e,i.join(" "));break;case"dataId":break;case"id":t.setAttribute("data-element-id",i);break;case"style":Object.assign(t.style,i);break;case"textContent":t.textContent=i;break;default:(!r||"href"!==e&&"newWindow"!==e)&&t.setAttribute(e,i)}r&&n.addLinkAttributes(t,a.href,a.newWindow),i&&a.dataId&&this.setupStorage(t,a.dataId,e,i)}static render(t){const e=t.annotationStorage,i=t.linkService,s=t.xfaHtml,n=t.intent||"display",a=document.createElement(s.name);s.attributes&&this.setAttributes({html:a,element:s,intent:n,linkService:i});const r="richText"!==n,o=t.div;if(o.append(a),t.viewport){const e=`matrix(${t.viewport.transform.join(",")})`;o.style.transform=e}r&&o.setAttribute("class","xfaLayer xfaFont");const l=[];if(0===s.children.length){if(s.value){const t=document.createTextNode(s.value);a.append(t),r&&Qe.shouldBuildText(s.name)&&l.push(t)}return{textDivs:l}}const h=[[s,-1,a]];for(;h.length>0;){const[t,s,a]=h.at(-1);if(s+1===t.children.length){h.pop();continue}const o=t.children[++h.at(-1)[1]];if(null===o)continue;const{name:d}=o;if("#text"===d){const t=document.createTextNode(o.value);l.push(t),a.append(t);continue}const c=o?.attributes?.xmlns?document.createElementNS(o.attributes.xmlns,d):document.createElement(d);if(a.append(c),o.attributes&&this.setAttributes({html:c,element:o,storage:e,intent:n,linkService:i}),o.children?.length>0)h.push([o,-1,c]);else if(o.value){const t=document.createTextNode(o.value);r&&Qe.shouldBuildText(d)&&l.push(t),c.append(t)}}for(const t of o.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))t.setAttribute("readOnly",!0);return{textDivs:l}}static update(t){const e=`matrix(${t.viewport.transform.join(",")})`;t.div.style.transform=e,t.div.hidden=!1}}const wi=1e3,_i=new WeakSet;function xi(t){return{width:t[2]-t[0],height:t[3]-t[1]}}class Ci{static create(t){switch(t.data.annotationType){case 2:return new Si(t);case 1:return new Ti(t);case 20:switch(t.data.fieldType){case"Tx":return new ki(t);case"Btn":return t.data.radioButton?new Ri(t):t.data.checkBox?new Pi(t):new Di(t);case"Ch":return new Li(t);case"Sig":return new Ii(t)}return new Mi(t);case 16:return new Fi(t);case 3:return new Oi(t);case 4:return new Bi(t);case 5:return new zi(t);case 6:return new Hi(t);case 8:return new ji(t);case 14:return new $i(t);case 15:return new Wi(t);case 7:return new Ui(t);case 9:return new Gi(t);case 10:return new Vi(t);case 11:return new qi(t);case 12:return new Xi(t);case 13:return new Ki(t);case 17:return new Yi(t);default:return new Ei(t)}}}class Ei{#us=null;#ps=!1;#gs=null;constructor(t,{isRenderable:e=!1,ignoreBorder:i=!1,createQuadrilaterals:s=!1}={}){this.isRenderable=e,this.data=t.data,this.layer=t.layer,this.linkService=t.linkService,this.downloadManager=t.downloadManager,this.imageResourcesPath=t.imageResourcesPath,this.renderForms=t.renderForms,this.svgFactory=t.svgFactory,this.annotationStorage=t.annotationStorage,this.enableScripting=t.enableScripting,this.hasJSActions=t.hasJSActions,this._fieldObjects=t.fieldObjects,this.parent=t.parent,e&&(this.container=this._createContainer(i)),s&&this._createQuadrilaterals()}static _hasPopupData({titleObj:t,contentsObj:e,richText:i}){return!!(t?.str||e?.str||i?.str)}get _isEditable(){return this.data.isEditable}get hasPopupData(){return Ei._hasPopupData(this.data)}updateEdited(t){if(!this.container)return;this.#us||={rect:this.data.rect.slice(0)};const{rect:e}=t;e&&this.#ms(e),this.#gs?.popup.updateEdited(t)}resetEdited(){this.#us&&(this.#ms(this.#us.rect),this.#gs?.popup.resetEdited(),this.#us=null)}#ms(t){const{container:{style:e},data:{rect:i,rotation:s},parent:{viewport:{rawDims:{pageWidth:n,pageHeight:a,pageX:r,pageY:o}}}}=this;i?.splice(0,4,...t);const{width:l,height:h}=xi(t);e.left=100*(t[0]-r)/n+"%",e.top=100*(a-t[3]+o)/a+"%",0===s?(e.width=100*l/n+"%",e.height=100*h/a+"%"):this.setRotation(s)}_createContainer(t){const{data:e,parent:{page:i,viewport:s}}=this,n=document.createElement("section");n.setAttribute("data-annotation-id",e.id),this instanceof Mi||(n.tabIndex=wi);const{style:a}=n;if(a.zIndex=this.parent.zIndex++,e.popupRef&&n.setAttribute("aria-haspopup","dialog"),e.alternativeText&&(n.title=e.alternativeText),e.noRotate&&n.classList.add("norotate"),!e.rect||this instanceof Fi){const{rotation:t}=e;return e.hasOwnCanvas||0===t||this.setRotation(t,n),n}const{width:r,height:o}=xi(e.rect);if(!t&&e.borderStyle.width>0){a.borderWidth=`${e.borderStyle.width}px`;const t=e.borderStyle.horizontalCornerRadius,i=e.borderStyle.verticalCornerRadius;if(t>0||i>0){const e=`calc(${t}px * var(--scale-factor)) / calc(${i}px * var(--scale-factor))`;a.borderRadius=e}else if(this instanceof Ri){const t=`calc(${r}px * var(--scale-factor)) / calc(${o}px * var(--scale-factor))`;a.borderRadius=t}switch(e.borderStyle.style){case 1:a.borderStyle="solid";break;case 2:a.borderStyle="dashed";break;case 3:w("Unimplemented border style: beveled");break;case 4:w("Unimplemented border style: inset");break;case 5:a.borderBottomStyle="solid"}const s=e.borderColor||null;s?(this.#ps=!0,a.borderColor=z.makeHexColor(0|s[0],0|s[1],0|s[2])):a.borderWidth=0}const l=z.normalizeRect([e.rect[0],i.view[3]-e.rect[1]+i.view[1],e.rect[2],i.view[3]-e.rect[3]+i.view[1]]),{pageWidth:h,pageHeight:d,pageX:c,pageY:u}=s.rawDims;a.left=100*(l[0]-c)/h+"%",a.top=100*(l[1]-u)/d+"%";const{rotation:p}=e;return e.hasOwnCanvas||0===p?(a.width=100*r/h+"%",a.height=100*o/d+"%"):this.setRotation(p,n),n}setRotation(t,e=this.container){if(!this.data.rect)return;const{pageWidth:i,pageHeight:s}=this.parent.viewport.rawDims,{width:n,height:a}=xi(this.data.rect);let r,o;t%180==0?(r=100*n/i,o=100*a/s):(r=100*a/i,o=100*n/s),e.style.width=`${r}%`,e.style.height=`${o}%`,e.setAttribute("data-main-rotation",(360-t)%360)}get _commonActions(){const t=(t,e,i)=>{const s=i.detail[t],n=s[0],a=s.slice(1);i.target.style[e]=Ai[`${n}_HTML`](a),this.annotationStorage.setValue(this.data.id,{[e]:Ai[`${n}_rgb`](a)})};return E(this,"_commonActions",{display:t=>{const{display:e}=t.detail,i=e%2==1;this.container.style.visibility=i?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noView:i,noPrint:1===e||2===e})},print:t=>{this.annotationStorage.setValue(this.data.id,{noPrint:!t.detail.print})},hidden:t=>{const{hidden:e}=t.detail;this.container.style.visibility=e?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noPrint:e,noView:e})},focus:t=>{setTimeout((()=>t.target.focus({preventScroll:!1})),0)},userName:t=>{t.target.title=t.detail.userName},readonly:t=>{t.target.disabled=t.detail.readonly},required:t=>{this._setRequired(t.target,t.detail.required)},bgColor:e=>{t("bgColor","backgroundColor",e)},fillColor:e=>{t("fillColor","backgroundColor",e)},fgColor:e=>{t("fgColor","color",e)},textColor:e=>{t("textColor","color",e)},borderColor:e=>{t("borderColor","borderColor",e)},strokeColor:e=>{t("strokeColor","borderColor",e)},rotation:t=>{const e=t.detail.rotation;this.setRotation(e),this.annotationStorage.setValue(this.data.id,{rotation:e})}})}_dispatchEventFromSandbox(t,e){const i=this._commonActions;for(const s of Object.keys(e.detail))(t[s]||i[s])?.(e)}_setDefaultPropertiesFromJS(t){if(!this.enableScripting)return;const e=this.annotationStorage.getRawValue(this.data.id);if(!e)return;const i=this._commonActions;for(const[s,n]of Object.entries(e)){const a=i[s];a&&(a({detail:{[s]:n},target:t}),delete e[s])}}_createQuadrilaterals(){if(!this.container)return;const{quadPoints:t}=this.data;if(!t)return;const[e,i,s,n]=this.data.rect.map((t=>Math.fround(t)));if(8===t.length){const[a,r,o,l]=t.subarray(2,6);if(s===a&&n===r&&e===o&&i===l)return}const{style:a}=this.container;let r;if(this.#ps){const{borderColor:t,borderWidth:e}=a;a.borderWidth=0,r=["url('data:image/svg+xml;utf8,",'',``],this.container.classList.add("hasBorder")}const o=s-e,l=n-i,{svgFactory:h}=this,d=h.createElement("svg");d.classList.add("quadrilateralsContainer"),d.setAttribute("width",0),d.setAttribute("height",0);const c=h.createElement("defs");d.append(c);const u=h.createElement("clipPath"),p=`clippath_${this.data.id}`;u.setAttribute("id",p),u.setAttribute("clipPathUnits","objectBoundingBox"),c.append(u);for(let i=2,s=t.length;i`)}this.#ps&&(r.push("')"),a.backgroundImage=r.join("")),this.container.append(d),this.container.style.clipPath=`url(#${p})`}_createPopup(){const{container:t,data:e}=this;t.setAttribute("aria-haspopup","dialog");const i=this.#gs=new Fi({data:{color:e.color,titleObj:e.titleObj,modificationDate:e.modificationDate,contentsObj:e.contentsObj,richText:e.richText,parentRect:e.rect,borderStyle:0,id:`popup_${e.id}`,rotation:e.rotation},parent:this.parent,elements:[this]});this.parent.div.append(i.render())}render(){_("Abstract method `AnnotationElement.render` called")}_getElementsByName(t,e=null){const i=[];if(this._fieldObjects){const s=this._fieldObjects[t];if(s)for(const{page:t,id:n,exportValues:a}of s){if(-1===t)continue;if(n===e)continue;const s="string"==typeof a?a:null,r=document.querySelector(`[data-element-id="${n}"]`);!r||_i.has(r)?i.push({id:n,exportValue:s,domElement:r}):w(`_getElementsByName - element not allowed: ${n}`)}return i}for(const s of document.getElementsByName(t)){const{exportValue:t}=s,n=s.getAttribute("data-element-id");n!==e&&_i.has(s)&&i.push({id:n,exportValue:t,domElement:s})}return i}show(){this.container&&(this.container.hidden=!1),this.popup?.maybeShow()}hide(){this.container&&(this.container.hidden=!0),this.popup?.forceHide()}getElementsToTriggerPopup(){return this.container}addHighlightArea(){const t=this.getElementsToTriggerPopup();if(Array.isArray(t))for(const e of t)e.classList.add("highlightArea");else t.classList.add("highlightArea")}_editOnDoubleClick(){if(!this._isEditable)return;const{annotationEditorType:t,data:{id:e}}=this;this.container.addEventListener("dblclick",(()=>{this.linkService.eventBus?.dispatch("switchannotationeditormode",{source:this,mode:t,editId:e})}))}}class Si extends Ei{constructor(t,e=null){super(t,{isRenderable:!0,ignoreBorder:!!e?.ignoreBorder,createQuadrilaterals:!0}),this.isTooltipOnly=t.data.isTooltipOnly}render(){const{data:t,linkService:e}=this,i=document.createElement("a");i.setAttribute("data-element-id",t.id);let s=!1;return t.url?(e.addLinkAttributes(i,t.url,t.newWindow),s=!0):t.action?(this._bindNamedAction(i,t.action),s=!0):t.attachment?(this.#fs(i,t.attachment,t.attachmentDest),s=!0):t.setOCGState?(this.#bs(i,t.setOCGState),s=!0):t.dest?(this._bindLink(i,t.dest),s=!0):(t.actions&&(t.actions.Action||t.actions["Mouse Up"]||t.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions&&(this._bindJSAction(i,t),s=!0),t.resetForm?(this._bindResetFormAction(i,t.resetForm),s=!0):this.isTooltipOnly&&!s&&(this._bindLink(i,""),s=!0)),this.container.classList.add("linkAnnotation"),s&&this.container.append(i),this.container}#vs(){this.container.setAttribute("data-internal-link","")}_bindLink(t,e){t.href=this.linkService.getDestinationHash(e),t.onclick=()=>(e&&this.linkService.goToDestination(e),!1),(e||""===e)&&this.#vs()}_bindNamedAction(t,e){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeNamedAction(e),!1),this.#vs()}#fs(t,e,i=null){t.href=this.linkService.getAnchorUrl(""),e.description&&(t.title=e.description),t.onclick=()=>(this.downloadManager?.openOrDownloadData(e.content,e.filename,i),!1),this.#vs()}#bs(t,e){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeSetOCGState(e),!1),this.#vs()}_bindJSAction(t,e){t.href=this.linkService.getAnchorUrl("");const i=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(const s of Object.keys(e.actions)){const n=i.get(s);n&&(t[n]=()=>(this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e.id,name:s}}),!1))}t.onclick||(t.onclick=()=>!1),this.#vs()}_bindResetFormAction(t,e){const i=t.onclick;if(i||(t.href=this.linkService.getAnchorUrl("")),this.#vs(),!this._fieldObjects)return w('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.'),void(i||(t.onclick=()=>!1));t.onclick=()=>{i?.();const{fields:t,refs:s,include:n}=e,a=[];if(0!==t.length||0!==s.length){const e=new Set(s);for(const i of t){const t=this._fieldObjects[i]||[];for(const{id:i}of t)e.add(i)}for(const t of Object.values(this._fieldObjects))for(const i of t)e.has(i.id)===n&&a.push(i)}else for(const t of Object.values(this._fieldObjects))a.push(...t);const r=this.annotationStorage,o=[];for(const t of a){const{id:e}=t;switch(o.push(e),t.type){case"text":{const i=t.defaultValue||"";r.setValue(e,{value:i});break}case"checkbox":case"radiobutton":{const i=t.defaultValue===t.exportValues;r.setValue(e,{value:i});break}case"combobox":case"listbox":{const i=t.defaultValue||"";r.setValue(e,{value:i});break}default:continue}const i=document.querySelector(`[data-element-id="${e}"]`);i&&(_i.has(i)?i.dispatchEvent(new Event("resetform")):w(`_bindResetFormAction - element not allowed: ${e}`))}return this.enableScripting&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:o,name:"ResetForm"}}),!1}}}class Ti extends Ei{constructor(t){super(t,{isRenderable:!0})}render(){this.container.classList.add("textAnnotation");const t=document.createElement("img");return t.src=this.imageResourcesPath+"annotation-"+this.data.name.toLowerCase()+".svg",t.setAttribute("data-l10n-id","pdfjs-text-annotation-type"),t.setAttribute("data-l10n-args",JSON.stringify({type:this.data.name})),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.append(t),this.container}}class Mi extends Ei{render(){return this.container}showElementAndHideCanvas(t){this.data.hasOwnCanvas&&("CANVAS"===t.previousSibling?.nodeName&&(t.previousSibling.hidden=!0),t.hidden=!1)}_getKeyModifier(t){return O.platform.isMac?t.metaKey:t.ctrlKey}_setEventListener(t,e,i,s,n){i.includes("mouse")?t.addEventListener(i,(t=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:s,value:n(t),shift:t.shiftKey,modifier:this._getKeyModifier(t)}})})):t.addEventListener(i,(t=>{if("blur"===i){if(!e.focused||!t.relatedTarget)return;e.focused=!1}else if("focus"===i){if(e.focused)return;e.focused=!0}n&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:s,value:n(t)}})}))}_setEventListeners(t,e,i,s){for(const[n,a]of i)("Action"===a||this.data.actions?.[a])&&("Focus"!==a&&"Blur"!==a||(e||={focused:!1}),this._setEventListener(t,e,n,a,s),"Focus"!==a||this.data.actions?.Blur?"Blur"!==a||this.data.actions?.Focus||this._setEventListener(t,e,"focus","Focus",null):this._setEventListener(t,e,"blur","Blur",null))}_setBackgroundColor(t){const e=this.data.backgroundColor||null;t.style.backgroundColor=null===e?"transparent":z.makeHexColor(e[0],e[1],e[2])}_setTextStyle(t){const{fontColor:e}=this.data.defaultAppearanceData,i=this.data.defaultAppearanceData.fontSize||9,s=t.style;let n;const a=t=>Math.round(10*t)/10;if(this.data.multiLine){const t=Math.abs(this.data.rect[3]-this.data.rect[1]-2),e=t/(Math.round(t/(o*i))||1);n=Math.min(i,a(e/o))}else{const t=Math.abs(this.data.rect[3]-this.data.rect[1]-2);n=Math.min(i,a(t/o))}s.fontSize=`calc(${n}px * var(--scale-factor))`,s.color=z.makeHexColor(e[0],e[1],e[2]),null!==this.data.textAlignment&&(s.textAlign=["left","center","right"][this.data.textAlignment])}_setRequired(t,e){e?t.setAttribute("required",!0):t.removeAttribute("required"),t.setAttribute("aria-required",e)}}class ki extends Mi{constructor(t){super(t,{isRenderable:t.renderForms||t.data.hasOwnCanvas||!t.data.hasAppearance&&!!t.data.fieldValue})}setPropertyOnSiblings(t,e,i,s){const n=this.annotationStorage;for(const a of this._getElementsByName(t.name,t.id))a.domElement&&(a.domElement[e]=i),n.setValue(a.id,{[s]:i})}render(){const t=this.annotationStorage,e=this.data.id;this.container.classList.add("textWidgetAnnotation");let i=null;if(this.renderForms){const s=t.getValue(e,{value:this.data.fieldValue});let n=s.value||"";const a=t.getValue(e,{charLimit:this.data.maxLen}).charLimit;a&&n.length>a&&(n=n.slice(0,a));let r=s.formattedValue||this.data.textContent?.join("\n")||null;r&&this.data.comb&&(r=r.replaceAll(/\s+/g,""));const o={userValue:n,formattedValue:r,lastCommittedValue:null,commitKey:1,focused:!1};this.data.multiLine?(i=document.createElement("textarea"),i.textContent=r??n,this.data.doNotScroll&&(i.style.overflowY="hidden")):(i=document.createElement("input"),i.type="text",i.setAttribute("value",r??n),this.data.doNotScroll&&(i.style.overflowX="hidden")),this.data.hasOwnCanvas&&(i.hidden=!0),_i.add(i),i.setAttribute("data-element-id",e),i.disabled=this.data.readOnly,i.name=this.data.fieldName,i.tabIndex=wi,this._setRequired(i,this.data.required),a&&(i.maxLength=a),i.addEventListener("input",(s=>{t.setValue(e,{value:s.target.value}),this.setPropertyOnSiblings(i,"value",s.target.value,"value"),o.formattedValue=null})),i.addEventListener("resetform",(t=>{const e=this.data.defaultFieldValue??"";i.value=o.userValue=e,o.formattedValue=null}));let l=t=>{const{formattedValue:e}=o;null!=e&&(t.target.value=e),t.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){i.addEventListener("focus",(t=>{if(o.focused)return;const{target:e}=t;o.userValue&&(e.value=o.userValue),o.lastCommittedValue=e.value,o.commitKey=1,this.data.actions?.Focus||(o.focused=!0)})),i.addEventListener("updatefromsandbox",(i=>{this.showElementAndHideCanvas(i.target);const s={value(i){o.userValue=i.detail.value??"",t.setValue(e,{value:o.userValue.toString()}),i.target.value=o.userValue},formattedValue(i){const{formattedValue:s}=i.detail;o.formattedValue=s,null!=s&&i.target!==document.activeElement&&(i.target.value=s),t.setValue(e,{formattedValue:s})},selRange(t){t.target.setSelectionRange(...t.detail.selRange)},charLimit:i=>{const{charLimit:s}=i.detail,{target:n}=i;if(0===s)return void n.removeAttribute("maxLength");n.setAttribute("maxLength",s);let a=o.userValue;!a||a.length<=s||(a=a.slice(0,s),n.value=o.userValue=a,t.setValue(e,{value:a}),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:a,willCommit:!0,commitKey:1,selStart:n.selectionStart,selEnd:n.selectionEnd}}))}};this._dispatchEventFromSandbox(s,i)})),i.addEventListener("keydown",(t=>{o.commitKey=1;let i=-1;if("Escape"===t.key?i=0:"Enter"!==t.key||this.data.multiLine?"Tab"===t.key&&(o.commitKey=3):i=2,-1===i)return;const{value:s}=t.target;o.lastCommittedValue!==s&&(o.lastCommittedValue=s,o.userValue=s,this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:s,willCommit:!0,commitKey:i,selStart:t.target.selectionStart,selEnd:t.target.selectionEnd}}))}));const s=l;l=null,i.addEventListener("blur",(t=>{if(!o.focused||!t.relatedTarget)return;this.data.actions?.Blur||(o.focused=!1);const{value:i}=t.target;o.userValue=i,o.lastCommittedValue!==i&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:i,willCommit:!0,commitKey:o.commitKey,selStart:t.target.selectionStart,selEnd:t.target.selectionEnd}}),s(t)})),this.data.actions?.Keystroke&&i.addEventListener("beforeinput",(t=>{o.lastCommittedValue=null;const{data:i,target:s}=t,{value:n,selectionStart:a,selectionEnd:r}=s;let l=a,h=r;switch(t.inputType){case"deleteWordBackward":{const t=n.substring(0,a).match(/\w*[^\w]*$/);t&&(l-=t[0].length);break}case"deleteWordForward":{const t=n.substring(a).match(/^[^\w]*\w*/);t&&(h+=t[0].length);break}case"deleteContentBackward":a===r&&(l-=1);break;case"deleteContentForward":a===r&&(h+=1)}t.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:n,change:i||"",willCommit:!1,selStart:l,selEnd:h}})})),this._setEventListeners(i,o,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(t=>t.target.value))}if(l&&i.addEventListener("blur",l),this.data.comb){const t=(this.data.rect[2]-this.data.rect[0])/a;i.classList.add("comb"),i.style.letterSpacing=`calc(${t}px * var(--scale-factor) - 1ch)`}}else i=document.createElement("div"),i.textContent=this.data.fieldValue,i.style.verticalAlign="middle",i.style.display="table-cell",this.data.hasOwnCanvas&&(i.hidden=!0);return this._setTextStyle(i),this._setBackgroundColor(i),this._setDefaultPropertiesFromJS(i),this.container.append(i),this.container}}class Ii extends Mi{constructor(t){super(t,{isRenderable:!!t.data.hasOwnCanvas})}}class Pi extends Mi{constructor(t){super(t,{isRenderable:t.renderForms})}render(){const t=this.annotationStorage,e=this.data,i=e.id;let s=t.getValue(i,{value:e.exportValue===e.fieldValue}).value;"string"==typeof s&&(s="Off"!==s,t.setValue(i,{value:s})),this.container.classList.add("buttonWidgetAnnotation","checkBox");const n=document.createElement("input");return _i.add(n),n.setAttribute("data-element-id",i),n.disabled=e.readOnly,this._setRequired(n,this.data.required),n.type="checkbox",n.name=e.fieldName,s&&n.setAttribute("checked",!0),n.setAttribute("exportValue",e.exportValue),n.tabIndex=wi,n.addEventListener("change",(s=>{const{name:n,checked:a}=s.target;for(const s of this._getElementsByName(n,i)){const i=a&&s.exportValue===e.exportValue;s.domElement&&(s.domElement.checked=i),t.setValue(s.id,{value:i})}t.setValue(i,{value:a})})),n.addEventListener("resetform",(t=>{const i=e.defaultFieldValue||"Off";t.target.checked=i===e.exportValue})),this.enableScripting&&this.hasJSActions&&(n.addEventListener("updatefromsandbox",(e=>{const s={value(e){e.target.checked="Off"!==e.detail.value,t.setValue(i,{value:e.target.checked})}};this._dispatchEventFromSandbox(s,e)})),this._setEventListeners(n,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(t=>t.target.checked))),this._setBackgroundColor(n),this._setDefaultPropertiesFromJS(n),this.container.append(n),this.container}}class Ri extends Mi{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("buttonWidgetAnnotation","radioButton");const t=this.annotationStorage,e=this.data,i=e.id;let s=t.getValue(i,{value:e.fieldValue===e.buttonValue}).value;if("string"==typeof s&&(s=s!==e.buttonValue,t.setValue(i,{value:s})),s)for(const s of this._getElementsByName(e.fieldName,i))t.setValue(s.id,{value:!1});const n=document.createElement("input");if(_i.add(n),n.setAttribute("data-element-id",i),n.disabled=e.readOnly,this._setRequired(n,this.data.required),n.type="radio",n.name=e.fieldName,s&&n.setAttribute("checked",!0),n.tabIndex=wi,n.addEventListener("change",(e=>{const{name:s,checked:n}=e.target;for(const e of this._getElementsByName(s,i))t.setValue(e.id,{value:!1});t.setValue(i,{value:n})})),n.addEventListener("resetform",(t=>{const i=e.defaultFieldValue;t.target.checked=null!=i&&i===e.buttonValue})),this.enableScripting&&this.hasJSActions){const s=e.buttonValue;n.addEventListener("updatefromsandbox",(e=>{const n={value:e=>{const n=s===e.detail.value;for(const s of this._getElementsByName(e.target.name)){const e=n&&s.id===i;s.domElement&&(s.domElement.checked=e),t.setValue(s.id,{value:e})}}};this._dispatchEventFromSandbox(n,e)})),this._setEventListeners(n,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(t=>t.target.checked))}return this._setBackgroundColor(n),this._setDefaultPropertiesFromJS(n),this.container.append(n),this.container}}class Di extends Si{constructor(t){super(t,{ignoreBorder:t.data.hasAppearance})}render(){const t=super.render();t.classList.add("buttonWidgetAnnotation","pushButton");const e=t.lastChild;return this.enableScripting&&this.hasJSActions&&e&&(this._setDefaultPropertiesFromJS(e),e.addEventListener("updatefromsandbox",(t=>{this._dispatchEventFromSandbox({},t)}))),t}}class Li extends Mi{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("choiceWidgetAnnotation");const t=this.annotationStorage,e=this.data.id,i=t.getValue(e,{value:this.data.fieldValue}),s=document.createElement("select");_i.add(s),s.setAttribute("data-element-id",e),s.disabled=this.data.readOnly,this._setRequired(s,this.data.required),s.name=this.data.fieldName,s.tabIndex=wi;let n=this.data.combo&&this.data.options.length>0;this.data.combo||(s.size=this.data.options.length,this.data.multiSelect&&(s.multiple=!0)),s.addEventListener("resetform",(t=>{const e=this.data.defaultFieldValue;for(const t of s.options)t.selected=t.value===e}));for(const t of this.data.options){const e=document.createElement("option");e.textContent=t.displayValue,e.value=t.exportValue,i.value.includes(t.exportValue)&&(e.setAttribute("selected",!0),n=!1),s.append(e)}let a=null;if(n){const t=document.createElement("option");t.value=" ",t.setAttribute("hidden",!0),t.setAttribute("selected",!0),s.prepend(t),a=()=>{t.remove(),s.removeEventListener("input",a),a=null},s.addEventListener("input",a)}const r=t=>{const e=t?"value":"textContent",{options:i,multiple:n}=s;return n?Array.prototype.filter.call(i,(t=>t.selected)).map((t=>t[e])):-1===i.selectedIndex?null:i[i.selectedIndex][e]};let o=r(!1);const l=t=>{const e=t.target.options;return Array.prototype.map.call(e,(t=>({displayValue:t.textContent,exportValue:t.value})))};return this.enableScripting&&this.hasJSActions?(s.addEventListener("updatefromsandbox",(i=>{const n={value(i){a?.();const n=i.detail.value,l=new Set(Array.isArray(n)?n:[n]);for(const t of s.options)t.selected=l.has(t.value);t.setValue(e,{value:r(!0)}),o=r(!1)},multipleSelection(t){s.multiple=!0},remove(i){const n=s.options,a=i.detail.remove;n[a].selected=!1,s.remove(a),n.length>0&&-1===Array.prototype.findIndex.call(n,(t=>t.selected))&&(n[0].selected=!0),t.setValue(e,{value:r(!0),items:l(i)}),o=r(!1)},clear(i){for(;0!==s.length;)s.remove(0);t.setValue(e,{value:null,items:[]}),o=r(!1)},insert(i){const{index:n,displayValue:a,exportValue:h}=i.detail.insert,d=s.children[n],c=document.createElement("option");c.textContent=a,c.value=h,d?d.before(c):s.append(c),t.setValue(e,{value:r(!0),items:l(i)}),o=r(!1)},items(i){const{items:n}=i.detail;for(;0!==s.length;)s.remove(0);for(const t of n){const{displayValue:e,exportValue:i}=t,n=document.createElement("option");n.textContent=e,n.value=i,s.append(n)}s.options.length>0&&(s.options[0].selected=!0),t.setValue(e,{value:r(!0),items:l(i)}),o=r(!1)},indices(i){const s=new Set(i.detail.indices);for(const t of i.target.options)t.selected=s.has(t.index);t.setValue(e,{value:r(!0)}),o=r(!1)},editable(t){t.target.disabled=!t.detail.editable}};this._dispatchEventFromSandbox(n,i)})),s.addEventListener("input",(i=>{const s=r(!0),n=r(!1);t.setValue(e,{value:s}),i.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:o,change:n,changeEx:s,willCommit:!1,commitKey:1,keyDown:!1}})})),this._setEventListeners(s,null,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"],["input","Action"],["input","Validate"]],(t=>t.target.value))):s.addEventListener("input",(function(i){t.setValue(e,{value:r(!0)})})),this.data.combo&&this._setTextStyle(s),this._setBackgroundColor(s),this._setDefaultPropertiesFromJS(s),this.container.append(s),this.container}}class Fi extends Ei{constructor(t){const{data:e,elements:i}=t;super(t,{isRenderable:Ei._hasPopupData(e)}),this.elements=i,this.popup=null}render(){this.container.classList.add("popupAnnotation");const t=this.popup=new Ni({container:this.container,color:this.data.color,titleObj:this.data.titleObj,modificationDate:this.data.modificationDate,contentsObj:this.data.contentsObj,richText:this.data.richText,rect:this.data.rect,parentRect:this.data.parentRect||null,parent:this.parent,elements:this.elements,open:this.data.open}),e=[];for(const i of this.elements)i.popup=t,e.push(i.data.id),i.addHighlightArea();return this.container.setAttribute("aria-controls",e.map((t=>`${$}${t}`)).join(",")),this.container}}class Ni{#As=this.#ys.bind(this);#ws=this.#_s.bind(this);#xs=this.#Cs.bind(this);#Es=this.#Ss.bind(this);#Ts=null;#ut=null;#Ms=null;#ks=null;#Is=null;#Ps=null;#Rs=null;#Ds=!1;#Ls=null;#S=null;#Fs=null;#Ns=null;#Os=null;#us=null;#Bs=!1;constructor({container:t,color:e,elements:i,titleObj:s,modificationDate:n,contentsObj:a,richText:r,parent:o,rect:l,parentRect:h,open:d}){this.#ut=t,this.#Os=s,this.#Ms=a,this.#Ns=r,this.#Ps=o,this.#Ts=e,this.#Fs=l,this.#Rs=h,this.#Is=i,this.#ks=ut.toDateObject(n),this.trigger=i.flatMap((t=>t.getElementsToTriggerPopup()));for(const t of this.trigger)t.addEventListener("click",this.#Es),t.addEventListener("mouseenter",this.#xs),t.addEventListener("mouseleave",this.#ws),t.classList.add("popupTriggerArea");for(const t of i)t.container?.addEventListener("keydown",this.#As);this.#ut.hidden=!0,d&&this.#Ss()}render(){if(this.#Ls)return;const t=this.#Ls=document.createElement("div");if(t.className="popup",this.#Ts){const e=t.style.outlineColor=z.makeHexColor(...this.#Ts);if(CSS.supports("background-color","color-mix(in srgb, red 30%, white)"))t.style.backgroundColor=`color-mix(in srgb, ${e} 30%, white)`;else{const e=.7;t.style.backgroundColor=z.makeHexColor(...this.#Ts.map((t=>Math.floor(e*(255-t)+t))))}}const e=document.createElement("span");e.className="header";const i=document.createElement("h1");if(e.append(i),({dir:i.dir,str:i.textContent}=this.#Os),t.append(e),this.#ks){const t=document.createElement("span");t.classList.add("popupDate"),t.setAttribute("data-l10n-id","pdfjs-annotation-date-time-string"),t.setAttribute("data-l10n-args",JSON.stringify({dateObj:this.#ks.valueOf()})),e.append(t)}const s=this.#zs;if(s)yi.render({xfaHtml:s,intent:"richText",div:t}),t.lastChild.classList.add("richText","popupContent");else{const e=this._formatContents(this.#Ms);t.append(e)}this.#ut.append(t)}get#zs(){const t=this.#Ns,e=this.#Ms;return!t?.str||e?.str&&e.str!==t.str?null:this.#Ns.html||null}get#Hs(){return this.#zs?.attributes?.style?.fontSize||0}get#js(){return this.#zs?.attributes?.style?.color||null}#Us(t){const e=[],i={str:t,html:{name:"div",attributes:{dir:"auto"},children:[{name:"p",children:e}]}},s={style:{color:this.#js,fontSize:this.#Hs?`calc(${this.#Hs}px * var(--scale-factor))`:""}};for(const i of t.split("\n"))e.push({name:"span",value:i,attributes:s});return i}_formatContents({str:t,dir:e}){const i=document.createElement("p");i.classList.add("popupContent"),i.dir=e;const s=t.split(/(?:\r\n?|\n)/);for(let t=0,e=s.length;t{"Enter"===t.key&&(s?t.metaKey:t.ctrlKey)&&this.#Ys()})),!e.popupRef&&this.hasPopupData?this._createPopup():i.classList.add("popupTriggerArea"),t.append(i),t}getElementsToTriggerPopup(){return this.#Ks}addHighlightArea(){this.container.classList.add("highlightArea")}#Ys(){this.downloadManager?.openOrDownloadData(this.content,this.filename)}}class Qi{#Qs=null;#Js=null;#Zs=new Map;#tn=null;constructor({div:t,accessibilityManager:e,annotationCanvasMap:i,annotationEditorUIManager:s,page:n,viewport:a,structTreeLayer:r}){this.div=t,this.#Qs=e,this.#Js=i,this.#tn=r||null,this.page=n,this.viewport=a,this.zIndex=0,this._annotationEditorUIManager=s}hasEditableAnnotations(){return this.#Zs.size>0}async#en(t,e){const i=t.firstChild||t,s=i.id=`${$}${e}`,n=await(this.#tn?.getAriaAttributes(s));if(n)for(const[t,e]of n)i.setAttribute(t,e);this.div.append(t),this.#Qs?.moveElementInDOM(this.div,t,i,!1)}async render(t){const{annotations:e}=t,i=this.div;bt(i,this.viewport);const s=new Map,n={data:null,layer:i,linkService:t.linkService,downloadManager:t.downloadManager,imageResourcesPath:t.imageResourcesPath||"",renderForms:!1!==t.renderForms,svgFactory:new tt,annotationStorage:t.annotationStorage||new Nt,enableScripting:!0===t.enableScripting,hasJSActions:t.hasJSActions,fieldObjects:t.fieldObjects,parent:this,elements:null};for(const t of e){if(t.noHTML)continue;const e=16===t.annotationType;if(e){const e=s.get(t.id);if(!e)continue;n.elements=e}else{const{width:e,height:i}=xi(t.rect);if(e<=0||i<=0)continue}n.data=t;const i=Ci.create(n);if(!i.isRenderable)continue;if(!e&&t.popupRef){const e=s.get(t.popupRef);e?e.push(i):s.set(t.popupRef,[i])}const a=i.render();t.hidden&&(a.style.visibility="hidden"),await this.#en(a,t.id),i._isEditable&&(this.#Zs.set(i.data.id,i),this._annotationEditorUIManager?.renderAnnotationElement(i))}this.#in()}update({viewport:t}){const e=this.div;this.viewport=t,bt(e,{rotation:t.rotation}),this.#in(),e.hidden=!1}#in(){if(!this.#Js)return;const t=this.div;for(const[e,i]of this.#Js){const s=t.querySelector(`[data-annotation-id="${e}"]`);if(!s)continue;i.className="annotationContent";const{firstChild:n}=s;n?"CANVAS"===n.nodeName?n.replaceWith(i):n.classList.contains("annotationContent")?n.after(i):n.before(i):s.append(i)}this.#Js.clear()}getEditableAnnotations(){return Array.from(this.#Zs.values())}getEditableAnnotation(t){return this.#Zs.get(t)}}const Ji=/\r\n?|\n/g;class Zi extends kt{#Ts;#sn="";#nn=`${this.id}-editor`;#an=null;#Hs;static _freeTextDefaultContent="";static _internalPadding=0;static _defaultColor=null;static _defaultFontSize=10;static get _keyboardManager(){const t=Zi.prototype,e=t=>t.isEmpty(),i=Tt.TRANSLATE_SMALL,s=Tt.TRANSLATE_BIG;return E(this,"_keyboardManager",new Et([[["ctrl+s","mac+meta+s","ctrl+p","mac+meta+p"],t.commitOrRemove,{bubbles:!0}],[["ctrl+Enter","mac+meta+Enter","Escape","mac+Escape"],t.commitOrRemove],[["ArrowLeft","mac+ArrowLeft"],t._translateEmpty,{args:[-i,0],checker:e}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t._translateEmpty,{args:[-s,0],checker:e}],[["ArrowRight","mac+ArrowRight"],t._translateEmpty,{args:[i,0],checker:e}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t._translateEmpty,{args:[s,0],checker:e}],[["ArrowUp","mac+ArrowUp"],t._translateEmpty,{args:[0,-i],checker:e}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t._translateEmpty,{args:[0,-s],checker:e}],[["ArrowDown","mac+ArrowDown"],t._translateEmpty,{args:[0,i],checker:e}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t._translateEmpty,{args:[0,s],checker:e}]]))}static _type="freetext";static _editorType=h.FREETEXT;constructor(t){super({...t,name:"freeTextEditor"}),this.#Ts=t.color||Zi._defaultColor||kt._defaultLineColor,this.#Hs=t.fontSize||Zi._defaultFontSize}static initialize(t,e){kt.initialize(t,e,{strings:["pdfjs-free-text-default-content"]});const i=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(i.getPropertyValue("--freetext-padding"))}static updateDefaultParams(t,e){switch(t){case d.FREETEXT_SIZE:Zi._defaultFontSize=e;break;case d.FREETEXT_COLOR:Zi._defaultColor=e}}updateParams(t,e){switch(t){case d.FREETEXT_SIZE:this.#rn(e);break;case d.FREETEXT_COLOR:this.#on(e)}}static get defaultPropertiesToUpdate(){return[[d.FREETEXT_SIZE,Zi._defaultFontSize],[d.FREETEXT_COLOR,Zi._defaultColor||kt._defaultLineColor]]}get propertiesToUpdate(){return[[d.FREETEXT_SIZE,this.#Hs],[d.FREETEXT_COLOR,this.#Ts]]}#rn(t){const e=t=>{this.editorDiv.style.fontSize=`calc(${t}px * var(--scale-factor))`,this.translate(0,-(t-this.#Hs)*this.parentScale),this.#Hs=t,this.#ln()},i=this.#Hs;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:d.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})}#on(t){const e=t=>{this.#Ts=this.editorDiv.style.color=t},i=this.#Ts;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:d.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})}_translateEmpty(t,e){this._uiManager.translateSelectedEditors(t,e,!0)}getInitialTranslation(){const t=this.parentScale;return[-Zi._internalPadding*t,-(Zi._internalPadding+this.#Hs)*t]}rebuild(){this.parent&&(super.rebuild(),null!==this.div&&(this.isAttachedToDOM||this.parent.add(this)))}enableEditMode(){if(this.isInEditMode())return;this.parent.setEditingState(!1),this.parent.updateToolbar(h.FREETEXT),super.enableEditMode(),this.overlayDiv.classList.remove("enabled"),this.editorDiv.contentEditable=!0,this._isDraggable=!1,this.div.removeAttribute("aria-activedescendant"),this.#an=new AbortController;const t=this._uiManager.combinedSignal(this.#an);this.editorDiv.addEventListener("keydown",this.editorDivKeydown.bind(this),{signal:t}),this.editorDiv.addEventListener("focus",this.editorDivFocus.bind(this),{signal:t}),this.editorDiv.addEventListener("blur",this.editorDivBlur.bind(this),{signal:t}),this.editorDiv.addEventListener("input",this.editorDivInput.bind(this),{signal:t}),this.editorDiv.addEventListener("paste",this.editorDivPaste.bind(this),{signal:t})}disableEditMode(){this.isInEditMode()&&(this.parent.setEditingState(!0),super.disableEditMode(),this.overlayDiv.classList.add("enabled"),this.editorDiv.contentEditable=!1,this.div.setAttribute("aria-activedescendant",this.#nn),this._isDraggable=!0,this.#an?.abort(),this.#an=null,this.div.focus({preventScroll:!0}),this.isEditing=!1,this.parent.div.classList.add("freetextEditing"))}focusin(t){this._focusEventsAllowed&&(super.focusin(t),t.target!==this.editorDiv&&this.editorDiv.focus())}onceAdded(){this.width||(this.enableEditMode(),this.editorDiv.focus(),this._initialOptions?.isCentered&&this.center(),this._initialOptions=null)}isEmpty(){return!this.editorDiv||""===this.editorDiv.innerText.trim()}remove(){this.isEditing=!1,this.parent&&(this.parent.setEditingState(!0),this.parent.div.classList.add("freetextEditing")),super.remove()}#hn(){const t=[];this.editorDiv.normalize();let e=null;for(const i of this.editorDiv.childNodes)e?.nodeType===Node.TEXT_NODE&&"BR"===i.nodeName||(t.push(Zi.#dn(i)),e=i);return t.join("\n")}#ln(){const[t,e]=this.parentDimensions;let i;if(this.isAttachedToDOM)i=this.div.getBoundingClientRect();else{const{currentLayer:t,div:e}=this,s=e.style.display,n=e.classList.contains("hidden");e.classList.remove("hidden"),e.style.display="hidden",t.div.append(this.div),i=e.getBoundingClientRect(),e.remove(),e.style.display=s,e.classList.toggle("hidden",n)}this.rotation%180==this.parentRotation%180?(this.width=i.width/t,this.height=i.height/e):(this.width=i.height/t,this.height=i.width/e),this.fixAndSetPosition()}commit(){if(!this.isInEditMode())return;super.commit(),this.disableEditMode();const t=this.#sn,e=this.#sn=this.#hn().trimEnd();if(t===e)return;const i=t=>{this.#sn=t,t?(this.#cn(),this._uiManager.rebuild(this),this.#ln()):this.remove()};this.addCommands({cmd:()=>{i(e)},undo:()=>{i(t)},mustExec:!1}),this.#ln()}shouldGetKeyboardEvents(){return this.isInEditMode()}enterInEditMode(){this.enableEditMode(),this.editorDiv.focus()}dblclick(t){this.enterInEditMode()}keydown(t){t.target===this.div&&"Enter"===t.key&&(this.enterInEditMode(),t.preventDefault())}editorDivKeydown(t){Zi._keyboardManager.exec(this,t)}editorDivFocus(t){this.isEditing=!0}editorDivBlur(t){this.isEditing=!1}editorDivInput(t){this.parent.div.classList.toggle("freetextEditing",this.isEmpty())}disableEditing(){this.editorDiv.setAttribute("role","comment"),this.editorDiv.removeAttribute("aria-multiline")}enableEditing(){this.editorDiv.setAttribute("role","textbox"),this.editorDiv.setAttribute("aria-multiline",!0)}render(){if(this.div)return this.div;let t,e;this.width&&(t=this.x,e=this.y),super.render(),this.editorDiv=document.createElement("div"),this.editorDiv.className="internal",this.editorDiv.setAttribute("id",this.#nn),this.editorDiv.setAttribute("data-l10n-id","pdfjs-free-text"),this.enableEditing(),kt._l10nPromise.get("pdfjs-free-text-default-content").then((t=>this.editorDiv?.setAttribute("default-content",t))),this.editorDiv.contentEditable=!0;const{style:i}=this.editorDiv;if(i.fontSize=`calc(${this.#Hs}px * var(--scale-factor))`,i.color=this.#Ts,this.div.append(this.editorDiv),this.overlayDiv=document.createElement("div"),this.overlayDiv.classList.add("overlay","enabled"),this.div.append(this.overlayDiv),wt(this,this.div,["dblclick","keydown"]),this.width){const[i,s]=this.parentDimensions;if(this.annotationElementId){const{position:n}=this._initialData;let[a,r]=this.getInitialTranslation();[a,r]=this.pageTranslationToScreen(a,r);const[o,l]=this.pageDimensions,[h,d]=this.pageTranslation;let c,u;switch(this.rotation){case 0:c=t+(n[0]-h)/o,u=e+this.height-(n[1]-d)/l;break;case 90:c=t+(n[0]-h)/o,u=e-(n[1]-d)/l,[a,r]=[r,-a];break;case 180:c=t-this.width+(n[0]-h)/o,u=e-(n[1]-d)/l,[a,r]=[-a,-r];break;case 270:c=t+(n[0]-h-this.height*l)/o,u=e+(n[1]-d-this.width*o)/l,[a,r]=[-r,a]}this.setAt(c*i,u*s,a,r)}else this.setAt(t*i,e*s,this.width*i,this.height*s);this.#cn(),this._isDraggable=!0,this.editorDiv.contentEditable=!1}else this._isDraggable=!1,this.editorDiv.contentEditable=!0;return this.div}static#dn(t){return(t.nodeType===Node.TEXT_NODE?t.nodeValue:t.innerText).replaceAll(Ji,"")}editorDivPaste(t){const e=t.clipboardData||window.clipboardData,{types:i}=e;if(1===i.length&&"text/plain"===i[0])return;t.preventDefault();const s=Zi.#un(e.getData("text")||"").replaceAll(Ji,"\n");if(!s)return;const n=window.getSelection();if(!n.rangeCount)return;this.editorDiv.normalize(),n.deleteFromDocument();const a=n.getRangeAt(0);if(!s.includes("\n"))return a.insertNode(document.createTextNode(s)),this.editorDiv.normalize(),void n.collapseToStart();const{startContainer:r,startOffset:o}=a,l=[],h=[];if(r.nodeType===Node.TEXT_NODE){const t=r.parentElement;if(h.push(r.nodeValue.slice(o).replaceAll(Ji,"")),t!==this.editorDiv){let e=l;for(const i of this.editorDiv.childNodes)i!==t?e.push(Zi.#dn(i)):e=h}l.push(r.nodeValue.slice(0,o).replaceAll(Ji,""))}else if(r===this.editorDiv){let t=l,e=0;for(const i of this.editorDiv.childNodes)e++===o&&(t=h),t.push(Zi.#dn(i))}this.#sn=`${l.join("\n")}${s}${h.join("\n")}`,this.#cn();const d=new Range;let c=l.reduce(((t,e)=>t+e.length),0);for(const{firstChild:t}of this.editorDiv.childNodes)if(t.nodeType===Node.TEXT_NODE){const e=t.nodeValue.length;if(c<=e){d.setStart(t,c),d.setEnd(t,c);break}c-=e}n.removeAllRanges(),n.addRange(d)}#cn(){if(this.editorDiv.replaceChildren(),this.#sn)for(const t of this.#sn.split("\n")){const e=document.createElement("div");e.append(t?document.createTextNode(t):document.createElement("br")),this.editorDiv.append(e)}}#pn(){return this.#sn.replaceAll(" "," ")}static#un(t){return t.replaceAll(" "," ")}get contentDiv(){return this.editorDiv}static async deserialize(t,e,i){let s=null;if(t instanceof Oi){const{data:{defaultAppearanceData:{fontSize:e,fontColor:i},rect:n,rotation:a,id:r,popupRef:o},textContent:l,textPosition:d,parent:{page:{pageNumber:c}}}=t;if(!l||0===l.length)return null;s=t={annotationType:h.FREETEXT,color:Array.from(i),fontSize:e,value:l.join("\n"),position:d,pageIndex:c-1,rect:n.slice(0),rotation:a,id:r,deleted:!1,popupRef:o}}const n=await super.deserialize(t,e,i);return n.#Hs=t.fontSize,n.#Ts=z.makeHexColor(...t.color),n.#sn=Zi.#un(t.value),n.annotationElementId=t.id||null,n._initialData=s,n}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const e=Zi._internalPadding*this.parentScale,i=this.getRect(e,e),s=kt._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:this.#Ts),n={annotationType:h.FREETEXT,color:s,fontSize:this.#Hs,value:this.#pn(),pageIndex:this.pageIndex,rect:i,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return t?n:this.annotationElementId&&!this.#gn(n)?null:(n.id=this.annotationElementId,n)}#gn(t){const{value:e,fontSize:i,color:s,pageIndex:n}=this._initialData;return this._hasBeenMoved||t.value!==e||t.fontSize!==i||t.color.some(((t,e)=>t!==s[e]))||t.pageIndex!==n}renderAnnotationElement(t){const e=super.renderAnnotationElement(t);if(this.deleted)return e;const{style:i}=e;i.fontSize=`calc(${this.#Hs}px * var(--scale-factor))`,i.color=this.#Ts,e.replaceChildren();for(const t of this.#sn.split("\n")){const i=document.createElement("div");i.append(t?document.createTextNode(t):document.createElement("br")),e.append(i)}const s=Zi._internalPadding*this.parentScale;return t.updateEdited({rect:this.getRect(s,s),popupContent:this.#sn}),e}resetAnnotationElement(t){super.resetAnnotationElement(t),t.resetEdited()}}class ts{#mn;#fn=[];#bn=[];constructor(t,e=0,i=0,s=!0){let n=1/0,a=-1/0,r=1/0,o=-1/0;const l=10**-4;for(const{x:i,y:s,width:h,height:d}of t){const t=Math.floor((i-e)/l)*l,c=Math.ceil((i+h+e)/l)*l,u=Math.floor((s-e)/l)*l,p=Math.ceil((s+d+e)/l)*l,g=[t,u,p,!0],m=[c,u,p,!1];this.#fn.push(g,m),n=Math.min(n,t),a=Math.max(a,c),r=Math.min(r,u),o=Math.max(o,p)}const h=a-n+2*i,d=o-r+2*i,c=n-i,u=r-i,p=this.#fn.at(s?-1:-2),g=[p[0],p[2]];for(const t of this.#fn){const[e,i,s]=t;t[0]=(e-c)/h,t[1]=(i-u)/d,t[2]=(s-u)/d}this.#mn={x:c,y:u,width:h,height:d,lastPoint:g}}getOutlines(){this.#fn.sort(((t,e)=>t[0]-e[0]||t[1]-e[1]||t[2]-e[2]));const t=[];for(const e of this.#fn)e[3]?(t.push(...this.#vn(e)),this.#An(e)):(this.#yn(e),t.push(...this.#vn(e)));return this.#wn(t)}#wn(t){const e=[],i=new Set;for(const i of t){const[t,s,n]=i;e.push([t,s,i],[t,n,i])}e.sort(((t,e)=>t[1]-e[1]||t[0]-e[0]));for(let t=0,s=e.length;t0;){const t=i.values().next().value;let[e,a,r,o,l]=t;i.delete(t);let h=e,d=a;for(n=[e,r],s.push(n);;){let t;if(i.has(o))t=o;else{if(!i.has(l))break;t=l}i.delete(t),[e,a,r,o,l]=t,h!==e&&(n.push(h,d,e,d===a?a:r),h=e),d=d===a?r:a}n.push(h,d)}return new is(s,this.#mn)}#_n(t){const e=this.#bn;let i=0,s=e.length-1;for(;i<=s;){const n=i+s>>1,a=e[n][0];if(a===t)return n;a=0;s--){const[i,n]=this.#bn[s];if(i!==t)break;if(i===t&&n===e)return void this.#bn.splice(s,1)}}#vn(t){const[e,i,s]=t,n=[[e,i,s]],a=this.#_n(s);for(let t=0;t=i)if(o>s)n[t][1]=s;else{if(1===a)return[];n.splice(t,1),t--,a--}else n[t][2]=i,o>s&&n.push([e,s,o])}}return n}}class es{toSVGPath(){throw new Error("Abstract method `toSVGPath` must be implemented.")}get box(){throw new Error("Abstract getter `box` must be implemented.")}serialize(t,e){throw new Error("Abstract method `serialize` must be implemented.")}get free(){return this instanceof ns}}class is extends es{#mn;#xn;constructor(t,e){super(),this.#xn=t,this.#mn=e}toSVGPath(){const t=[];for(const e of this.#xn){let[i,s]=e;t.push(`M${i} ${s}`);for(let n=2;n=6;t-=6)isNaN(e[t])?u.push(`L${e[t+4]} ${e[t+5]}`):u.push(`C${e[t]} ${e[t+1]} ${e[t+2]} ${e[t+3]} ${e[t+4]} ${e[t+5]}`);return u.push(`L${e[4]} ${e[5]} Z`),u.join(" ")}getOutlines(){const t=this.#Tn,e=this.#Cn,i=this.#Mn,s=i.subarray(4,6),n=i.subarray(16,18),[a,r,o,l]=this.#mn,h=new Float64Array((this.#Fn?.length??0)+2);for(let t=0,e=h.length-2;t=6;t-=6)for(let i=0;i<6;i+=2)isNaN(e[t+i])?(g[m]=g[m+1]=NaN,m+=2):(g[m]=e[t+i],g[m+1]=e[t+i+1],m+=2);return g.set([NaN,NaN,NaN,NaN,e[4],e[5]],m),new ns(g,h,this.#mn,this.#Dn,this.#En,this.#Sn)}}class ns extends es{#mn;#Hn=null;#En;#Sn;#Fn;#Dn;#jn;constructor(t,e,i,s,n,a){super(),this.#jn=t,this.#Fn=e,this.#mn=i,this.#Dn=s,this.#En=n,this.#Sn=a,this.#Un(a);const{x:r,y:o,width:l,height:h}=this.#Hn;for(let e=0,i=t.length;e-1?(this.#ga=!0,this.#ya(t),this.#wa()):this.#oa&&(this.#aa=t.anchorNode,this.#ra=t.anchorOffset,this.#da=t.focusNode,this.#ca=t.focusOffset,this.#_a(),this.#wa(),this.rotate(this.rotation))}get telemetryInitialData(){return{action:"added",type:this.#ga?"free_highlight":"highlight",color:this._uiManager.highlightColorNames.get(this.color),thickness:this.#Ln,methodOfCreation:this.#Aa}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.highlightColorNames.get(this.color)}}static computeTelemetryFinalData(t){return{numberOfColors:t.get("color").size}}#_a(){const t=new ts(this.#oa,.001);this.#pa=t.getOutlines(),({x:this.x,y:this.y,width:this.width,height:this.height}=this.#pa.box);const e=new ts(this.#oa,.0025,.001,"ltr"===this._uiManager.direction);this.#ha=e.getOutlines();const{lastPoint:i}=this.#ha.box;this.#ma=[(i[0]-this.x)/this.width,(i[1]-this.y)/this.height]}#ya({highlightOutlines:t,highlightId:e,clipPathId:i}){if(this.#pa=t,this.#ha=t.getNewOutline(this.#Ln/2+1.5,.0025),e>=0)this.#A=e,this.#la=i,this.parent.drawLayer.finalizeLine(e,t),this.#ba=this.parent.drawLayer.highlightOutline(this.#ha);else if(this.parent){const e=this.parent.viewport.rotation;this.parent.drawLayer.updateLine(this.#A,t),this.parent.drawLayer.updateBox(this.#A,rs.#xa(this.#pa.box,(e-this.rotation+360)%360)),this.parent.drawLayer.updateLine(this.#ba,this.#ha),this.parent.drawLayer.updateBox(this.#ba,rs.#xa(this.#ha.box,e))}const{x:s,y:n,width:a,height:r}=t.box;switch(this.rotation){case 0:this.x=s,this.y=n,this.width=a,this.height=r;break;case 90:{const[t,e]=this.parentDimensions;this.x=n,this.y=1-s,this.width=a*e/t,this.height=r*t/e;break}case 180:this.x=1-s,this.y=1-n,this.width=a,this.height=r;break;case 270:{const[t,e]=this.parentDimensions;this.x=1-n,this.y=s,this.width=a*e/t,this.height=r*t/e;break}}const{lastPoint:o}=this.#ha.box;this.#ma=[(o[0]-s)/a,(o[1]-n)/r]}static initialize(t,e){kt.initialize(t,e),rs._defaultColor||=e.highlightColors?.values().next().value||"#fff066"}static updateDefaultParams(t,e){switch(t){case d.HIGHLIGHT_DEFAULT_COLOR:rs._defaultColor=e;break;case d.HIGHLIGHT_THICKNESS:rs._defaultThickness=e}}translateInPage(t,e){}get toolbarPosition(){return this.#ma}updateParams(t,e){switch(t){case d.HIGHLIGHT_COLOR:this.#on(e);break;case d.HIGHLIGHT_THICKNESS:this.#Ca(e)}}static get defaultPropertiesToUpdate(){return[[d.HIGHLIGHT_DEFAULT_COLOR,rs._defaultColor],[d.HIGHLIGHT_THICKNESS,rs._defaultThickness]]}get propertiesToUpdate(){return[[d.HIGHLIGHT_COLOR,this.color||rs._defaultColor],[d.HIGHLIGHT_THICKNESS,this.#Ln||rs._defaultThickness],[d.HIGHLIGHT_FREE,this.#ga]]}#on(t){const e=(t,e)=>{this.color=t,this.parent?.drawLayer.changeColor(this.#A,t),this.#n?.updateColor(t),this.#fa=e,this.parent?.drawLayer.changeOpacity(this.#A,e)},i=this.color,s=this.#fa;this.addCommands({cmd:e.bind(this,t,rs._defaultOpacity),undo:e.bind(this,i,s),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:d.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"color_changed",color:this._uiManager.highlightColorNames.get(t)},!0)}#Ca(t){const e=this.#Ln,i=t=>{this.#Ln=t,this.#Ea(t)};this.addCommands({cmd:i.bind(this,t),undo:i.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:d.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"thickness_changed",thickness:t},!0)}async addEditToolbar(){const t=await super.addEditToolbar();return t?(this._uiManager.highlightColors&&(this.#n=new as({editor:this}),t.addColorPicker(this.#n)),t):null}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(this.#Sa())}getBaseTranslation(){return[0,0]}getRect(t,e){return super.getRect(t,e,this.#Sa())}onceAdded(){this.annotationElementId||this.parent.addUndoableEditor(this),this.div.focus()}remove(){this.#Ta(),this._reportTelemetry({action:"deleted"}),super.remove()}rebuild(){this.parent&&(super.rebuild(),null!==this.div&&(this.#wa(),this.isAttachedToDOM||this.parent.add(this)))}setParent(t){let e=!1;this.parent&&!t?this.#Ta():t&&(this.#wa(t),e=!this.parent&&this.div?.classList.contains("selectedEditor")),super.setParent(t),this.show(this._isVisible),e&&this.select()}#Ea(t){if(!this.#ga)return;this.#ya({highlightOutlines:this.#pa.getNewOutline(t/2)}),this.fixAndSetPosition();const[e,i]=this.parentDimensions;this.setDims(this.width*e,this.height*i)}#Ta(){null!==this.#A&&this.parent&&(this.parent.drawLayer.remove(this.#A),this.#A=null,this.parent.drawLayer.remove(this.#ba),this.#ba=null)}#wa(t=this.parent){null===this.#A&&(({id:this.#A,clipPathId:this.#la}=t.drawLayer.highlight(this.#pa,this.color,this.#fa)),this.#ba=t.drawLayer.highlightOutline(this.#ha),this.#ua&&(this.#ua.style.clipPath=this.#la))}static#xa({x:t,y:e,width:i,height:s},n){switch(n){case 90:return{x:1-e-s,y:t,width:s,height:i};case 180:return{x:1-t-i,y:1-e-s,width:i,height:s};case 270:return{x:e,y:1-t-i,width:s,height:i}}return{x:t,y:e,width:i,height:s}}rotate(t){const{drawLayer:e}=this.parent;let i;this.#ga?(t=(t-this.rotation+360)%360,i=rs.#xa(this.#pa.box,t)):i=rs.#xa(this,t),e.rotate(this.#A,t),e.rotate(this.#ba,t),e.updateBox(this.#A,i),e.updateBox(this.#ba,rs.#xa(this.#ha.box,t))}render(){if(this.div)return this.div;const t=super.render();this.#va&&(t.setAttribute("aria-label",this.#va),t.setAttribute("role","mark")),this.#ga?t.classList.add("free"):this.div.addEventListener("keydown",this.#Ma.bind(this),{signal:this._uiManager._signal});const e=this.#ua=document.createElement("div");t.append(e),e.setAttribute("aria-hidden","true"),e.className="internal",e.style.clipPath=this.#la;const[i,s]=this.parentDimensions;return this.setDims(this.width*i,this.height*s),wt(this,this.#ua,["pointerover","pointerleave"]),this.enableEditing(),t}pointerover(){this.parent.drawLayer.addClass(this.#ba,"hovered")}pointerleave(){this.parent.drawLayer.removeClass(this.#ba,"hovered")}#Ma(t){rs._keyboardManager.exec(this,t)}_moveCaret(t){switch(this.parent.unselect(this),t){case 0:case 2:this.#ka(!0);break;case 1:case 3:this.#ka(!1)}}#ka(t){if(!this.#aa)return;const e=window.getSelection();t?e.setPosition(this.#aa,this.#ra):e.setPosition(this.#da,this.#ca)}select(){super.select(),this.#ba&&(this.parent?.drawLayer.removeClass(this.#ba,"hovered"),this.parent?.drawLayer.addClass(this.#ba,"selected"))}unselect(){super.unselect(),this.#ba&&(this.parent?.drawLayer.removeClass(this.#ba,"selected"),this.#ga||this.#ka(!1))}get _mustFixPosition(){return!this.#ga}show(t=this._isVisible){super.show(t),this.parent&&(this.parent.drawLayer.show(this.#A,t),this.parent.drawLayer.show(this.#ba,t))}#Sa(){return this.#ga?this.rotation:0}#Ia(){if(this.#ga)return null;const[t,e]=this.pageDimensions,[i,s]=this.pageTranslation,n=this.#oa,a=new Float32Array(8*n.length);let r=0;for(const{x:o,y:l,width:h,height:d}of n){const n=o*t+i,c=(1-l-d)*e+s;a[r]=a[r+4]=n,a[r+1]=a[r+3]=c,a[r+2]=a[r+6]=n+h*t,a[r+5]=a[r+7]=c+d*e,r+=8}return a}#Pa(t){return this.#pa.serialize(t,this.#Sa())}static startHighlighting(t,e,{target:i,x:s,y:n}){const{x:a,y:r,width:o,height:l}=i.getBoundingClientRect(),h=new AbortController,d=t.combinedSignal(h),c=e=>{h.abort(),this.#Ra(t,e)};window.addEventListener("blur",c,{signal:d}),window.addEventListener("pointerup",c,{signal:d}),window.addEventListener("pointerdown",(t=>{t.preventDefault(),t.stopPropagation()}),{capture:!0,passive:!1,signal:d}),window.addEventListener("contextmenu",ht,{signal:d}),i.addEventListener("pointermove",this.#Da.bind(this,t),{signal:d}),this._freeHighlight=new ss({x:s,y:n},[a,r,o,l],t.scale,this._defaultThickness/2,e,.001),({id:this._freeHighlightId,clipPathId:this._freeHighlightClipId}=t.drawLayer.highlight(this._freeHighlight,this._defaultColor,this._defaultOpacity,!0))}static#Da(t,e){this._freeHighlight.add(e)&&t.drawLayer.updatePath(this._freeHighlightId,this._freeHighlight)}static#Ra(t,e){this._freeHighlight.isEmpty()?t.drawLayer.removeFreeHighlight(this._freeHighlightId):t.createAndAddNewEditor(e,!1,{highlightId:this._freeHighlightId,highlightOutlines:this._freeHighlight.getOutlines(),clipPathId:this._freeHighlightClipId,methodOfCreation:"main_toolbar"}),this._freeHighlightId=-1,this._freeHighlight=null,this._freeHighlightClipId=""}static async deserialize(t,e,i){let s=null;if(t instanceof Gi){const{data:{quadPoints:e,rect:i,rotation:n,id:a,color:r,opacity:o,popupRef:l},parent:{page:{pageNumber:d}}}=t;s=t={annotationType:h.HIGHLIGHT,color:Array.from(r),opacity:o,quadPoints:e,boxes:null,pageIndex:d-1,rect:i.slice(0),rotation:n,id:a,deleted:!1,popupRef:l}}else if(t instanceof Wi){const{data:{inkLists:e,rect:i,rotation:n,id:a,color:r,borderStyle:{rawWidth:o},popupRef:l},parent:{page:{pageNumber:d}}}=t;s=t={annotationType:h.HIGHLIGHT,color:Array.from(r),thickness:o,inkLists:e,boxes:null,pageIndex:d-1,rect:i.slice(0),rotation:n,id:a,deleted:!1,popupRef:l}}const{color:n,quadPoints:a,inkLists:r,opacity:o}=t,l=await super.deserialize(t,e,i);l.color=z.makeHexColor(...n),l.#fa=o||1,r&&(l.#Ln=t.thickness),l.annotationElementId=t.id||null,l._initialData=s;const[d,c]=l.pageDimensions,[u,p]=l.pageTranslation;if(a){const t=l.#oa=[];for(let e=0;et!==e[i]))}renderAnnotationElement(t){return t.updateEdited({rect:this.getRect(0,0)}),null}static canCreateNewEmptyEditor(){return!1}}class os extends kt{#La=0;#Fa=0;#Na=null;#Oa=new Path2D;#Ba=!1;#za=null;#Ha=!1;#ja=!1;#Ua=null;#$a=null;#Wa=0;#Ga=0;#Va=null;static _defaultColor=null;static _defaultOpacity=1;static _defaultThickness=1;static _type="ink";static _editorType=h.INK;constructor(t){super({...t,name:"inkEditor"}),this.color=t.color||null,this.thickness=t.thickness||null,this.opacity=t.opacity||null,this.paths=[],this.bezierPath2D=[],this.allRawPaths=[],this.currentPath=[],this.scaleFactor=1,this.translationX=this.translationY=0,this.x=0,this.y=0,this._willKeepAspectRatio=!0}static initialize(t,e){kt.initialize(t,e)}static updateDefaultParams(t,e){switch(t){case d.INK_THICKNESS:os._defaultThickness=e;break;case d.INK_COLOR:os._defaultColor=e;break;case d.INK_OPACITY:os._defaultOpacity=e/100}}updateParams(t,e){switch(t){case d.INK_THICKNESS:this.#Ca(e);break;case d.INK_COLOR:this.#on(e);break;case d.INK_OPACITY:this.#qa(e)}}static get defaultPropertiesToUpdate(){return[[d.INK_THICKNESS,os._defaultThickness],[d.INK_COLOR,os._defaultColor||kt._defaultLineColor],[d.INK_OPACITY,Math.round(100*os._defaultOpacity)]]}get propertiesToUpdate(){return[[d.INK_THICKNESS,this.thickness||os._defaultThickness],[d.INK_COLOR,this.color||os._defaultColor||kt._defaultLineColor],[d.INK_OPACITY,Math.round(100*(this.opacity??os._defaultOpacity))]]}#Ca(t){const e=t=>{this.thickness=t,this.#Xa()},i=this.thickness;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:d.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0})}#on(t){const e=t=>{this.color=t,this.#Ka()},i=this.color;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:d.INK_COLOR,overwriteIfSameType:!0,keepUndo:!0})}#qa(t){const e=t=>{this.opacity=t,this.#Ka()};t/=100;const i=this.opacity;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:d.INK_OPACITY,overwriteIfSameType:!0,keepUndo:!0})}rebuild(){this.parent&&(super.rebuild(),null!==this.div&&(this.canvas||(this.#Ya(),this.#Qa()),this.isAttachedToDOM||(this.parent.add(this),this.#Ja()),this.#Xa()))}remove(){null!==this.canvas&&(this.isEmpty()||this.commit(),this.canvas.width=this.canvas.height=0,this.canvas.remove(),this.canvas=null,this.#Na&&(clearTimeout(this.#Na),this.#Na=null),this.#Ua?.disconnect(),this.#Ua=null,super.remove())}setParent(t){!this.parent&&t?this._uiManager.removeShouldRescale(this):this.parent&&null===t&&this._uiManager.addShouldRescale(this),super.setParent(t)}onScaleChanging(){const[t,e]=this.parentDimensions,i=this.width*t,s=this.height*e;this.setDimensions(i,s)}enableEditMode(){this.#Ba||null===this.canvas||(super.enableEditMode(),this._isDraggable=!1,this.#Za())}disableEditMode(){this.isInEditMode()&&null!==this.canvas&&(super.disableEditMode(),this._isDraggable=!this.isEmpty(),this.div.classList.remove("editing"),this.#tr())}onceAdded(){this._isDraggable=!this.isEmpty()}isEmpty(){return 0===this.paths.length||1===this.paths.length&&0===this.paths[0].length}#er(){const{parentRotation:t,parentDimensions:[e,i]}=this;switch(t){case 90:return[0,i,i,e];case 180:return[e,i,e,i];case 270:return[e,0,i,e];default:return[0,0,e,i]}}#ir(){const{ctx:t,color:e,opacity:i,thickness:s,parentScale:n,scaleFactor:a}=this;t.lineWidth=s*n/a,t.lineCap="round",t.lineJoin="round",t.miterLimit=10,t.strokeStyle=`${e}${function(t){return Math.round(Math.min(255,Math.max(1,255*t))).toString(16).padStart(2,"0")}(i)}`}#sr(t,e){this.canvas.addEventListener("contextmenu",ht,{signal:this._uiManager._signal}),this.#tr(),this.#za=new AbortController;const i=this._uiManager.combinedSignal(this.#za);this.canvas.addEventListener("pointerleave",this.canvasPointerleave.bind(this),{signal:i}),this.canvas.addEventListener("pointermove",this.canvasPointermove.bind(this),{signal:i}),this.canvas.addEventListener("pointerup",this.canvasPointerup.bind(this),{signal:i}),this.isEditing=!0,this.#ja||(this.#ja=!0,this.#Ja(),this.thickness||=os._defaultThickness,this.color||=os._defaultColor||kt._defaultLineColor,this.opacity??=os._defaultOpacity),this.currentPath.push([t,e]),this.#Ha=!1,this.#ir(),this.#Va=()=>{this.#nr(),this.#Va&&window.requestAnimationFrame(this.#Va)},window.requestAnimationFrame(this.#Va)}#ar(t,e){const[i,s]=this.currentPath.at(-1);if(this.currentPath.length>1&&t===i&&e===s)return;const n=this.currentPath;let a=this.#Oa;if(n.push([t,e]),this.#Ha=!0,n.length<=2)return a.moveTo(...n[0]),void a.lineTo(t,e);3===n.length&&(this.#Oa=a=new Path2D,a.moveTo(...n[0])),this.#rr(a,...n.at(-3),...n.at(-2),t,e)}#or(){if(0===this.currentPath.length)return;const t=this.currentPath.at(-1);this.#Oa.lineTo(...t)}#lr(t,e){let i;if(this.#Va=null,t=Math.min(Math.max(t,0),this.canvas.width),e=Math.min(Math.max(e,0),this.canvas.height),this.#ar(t,e),this.#or(),1!==this.currentPath.length)i=this.#hr();else{const s=[t,e];i=[[s,s.slice(),s.slice(),s]]}const s=this.#Oa,n=this.currentPath;this.currentPath=[],this.#Oa=new Path2D,this.addCommands({cmd:()=>{this.allRawPaths.push(n),this.paths.push(i),this.bezierPath2D.push(s),this._uiManager.rebuild(this)},undo:()=>{this.allRawPaths.pop(),this.paths.pop(),this.bezierPath2D.pop(),0===this.paths.length?this.remove():(this.canvas||(this.#Ya(),this.#Qa()),this.#Xa())},mustExec:!0})}#nr(){if(!this.#Ha)return;this.#Ha=!1;Math.ceil(this.thickness*this.parentScale);const t=this.currentPath.slice(-3),e=t.map((t=>t[0])),i=t.map((t=>t[1])),{ctx:s}=(Math.min(...e),Math.max(...e),Math.min(...i),Math.max(...i),this);s.save(),s.clearRect(0,0,this.canvas.width,this.canvas.height);for(const t of this.bezierPath2D)s.stroke(t);s.stroke(this.#Oa),s.restore()}#rr(t,e,i,s,n,a,r){const o=(e+s)/2,l=(i+n)/2,h=(s+a)/2,d=(n+r)/2;t.bezierCurveTo(o+2*(s-o)/3,l+2*(n-l)/3,h+2*(s-h)/3,d+2*(n-d)/3,h,d)}#hr(){const t=this.currentPath;if(t.length<=2)return[[t[0],t[0],t.at(-1),t.at(-1)]];const e=[];let i,[s,n]=t[0];for(i=1;i{this.#Na=null,this.canvas.removeEventListener("contextmenu",ht)}),10),this.#lr(t.offsetX,t.offsetY),this.addToAnnotationStorage(),this.setInBackground()}#Ya(){this.canvas=document.createElement("canvas"),this.canvas.width=this.canvas.height=0,this.canvas.className="inkEditorCanvas",this.canvas.setAttribute("data-l10n-id","pdfjs-ink-canvas"),this.div.append(this.canvas),this.ctx=this.canvas.getContext("2d")}#Qa(){this.#Ua=new ResizeObserver((t=>{const e=t[0].contentRect;e.width&&e.height&&this.setDimensions(e.width,e.height)})),this.#Ua.observe(this.div),this._uiManager._signal.addEventListener("abort",(()=>{this.#Ua?.disconnect(),this.#Ua=null}),{once:!0})}get isResizable(){return!this.isEmpty()&&this.#Ba}render(){if(this.div)return this.div;let t,e;this.width&&(t=this.x,e=this.y),super.render(),this.div.setAttribute("data-l10n-id","pdfjs-ink");const[i,s,n,a]=this.#er();if(this.setAt(i,s,0,0),this.setDims(n,a),this.#Ya(),this.width){const[i,s]=this.parentDimensions;this.setAspectRatio(this.width*i,this.height*s),this.setAt(t*i,e*s,this.width*i,this.height*s),this.#ja=!0,this.#Ja(),this.setDims(this.width*i,this.height*s),this.#Ka(),this.div.classList.add("disabled")}else this.div.classList.add("editing"),this.enableEditMode();return this.#Qa(),this.div}#Ja(){if(!this.#ja)return;const[t,e]=this.parentDimensions;this.canvas.width=Math.ceil(this.width*t),this.canvas.height=Math.ceil(this.height*e),this.#dr()}setDimensions(t,e){const i=Math.round(t),s=Math.round(e);if(this.#Wa===i&&this.#Ga===s)return;this.#Wa=i,this.#Ga=s,this.canvas.style.visibility="hidden";const[n,a]=this.parentDimensions;this.width=t/n,this.height=e/a,this.fixAndSetPosition(),this.#Ba&&this.#ur(t,e),this.#Ja(),this.#Ka(),this.canvas.style.visibility="visible",this.fixDims()}#ur(t,e){const i=this.#pr(),s=(t-i)/this.#Fa,n=(e-i)/this.#La;this.scaleFactor=Math.min(s,n)}#dr(){const t=this.#pr()/2;this.ctx.setTransform(this.scaleFactor,0,0,this.scaleFactor,this.translationX*this.scaleFactor+t,this.translationY*this.scaleFactor+t)}static#gr(t){const e=new Path2D;for(let i=0,s=t.length;i`image/${t}`)))}static get supportedTypesStr(){return E(this,"supportedTypesStr",this.supportedTypes.join(","))}static isHandlingMimeForPasting(t){return this.supportedTypes.includes(t)}static paste(t,e){e.pasteEditor(h.STAMP,{bitmapFile:t.getAsFile()})}altTextFinish(){this._uiManager.useNewAltTextFlow&&(this.div.hidden=!1),super.altTextFinish()}get telemetryFinalData(){return{type:"stamp",hasAltText:!!this.altTextData?.altText}}static computeTelemetryFinalData(t){const e=t.get("hasAltText");return{hasAltText:e.get(!0)??0,hasNoAltText:e.get(!1)??0}}#kr(t,e=!1){t?(this.#Ar=t.bitmap,e||(this.#yr=t.id,this.#Tr=t.isSvg),t.file&&(this.#Cr=t.file.name),this.#Ya()):this.remove()}#Ir(){if(this.#wr=null,this._uiManager.enableWaiting(!1),this.#Er){if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#Ar)return this._editToolbar.hide(),void this._uiManager.editAltText(this,!0);if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#Ar){this._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:!1,alt_text_type:"empty"}});try{this.mlGuessAltText()}catch{}}this.div.focus()}}async mlGuessAltText(t=null,e=!0){if(this.hasAltTextData())return null;const{mlManager:i}=this._uiManager;if(!i)throw new Error("No ML.");if(!await i.isEnabledFor("altText"))throw new Error("ML isn't enabled for alt text.");const{data:s,width:n,height:a}=t||this.copyCanvas(null,null,!0).imageData,r=await i.guess({name:"altText",request:{data:s,width:n,height:a,channels:s.length/(n*a)}});if(!r)throw new Error("No response from the AI service.");if(r.error)throw new Error("Error from the AI service.");if(r.cancel)return null;if(!r.output)throw new Error("No valid response from the AI service.");const o=r.output;return await this.setGuessedAltText(o),e&&!this.hasAltTextData()&&(this.altTextData={alt:o,decorative:!1}),o}#Pr(){if(this.#yr)return this._uiManager.enableWaiting(!0),void this._uiManager.imageManager.getFromId(this.#yr).then((t=>this.#kr(t,!0))).finally((()=>this.#Ir()));if(this.#_r){const t=this.#_r;return this.#_r=null,this._uiManager.enableWaiting(!0),void(this.#wr=this._uiManager.imageManager.getFromUrl(t).then((t=>this.#kr(t))).finally((()=>this.#Ir())))}if(this.#xr){const t=this.#xr;return this.#xr=null,this._uiManager.enableWaiting(!0),void(this.#wr=this._uiManager.imageManager.getFromFile(t).then((t=>this.#kr(t))).finally((()=>this.#Ir())))}const t=document.createElement("input");t.type="file",t.accept=ls.supportedTypesStr;const e=this._uiManager._signal;this.#wr=new Promise((i=>{t.addEventListener("change",(async()=>{if(t.files&&0!==t.files.length){this._uiManager.enableWaiting(!0);const e=await this._uiManager.imageManager.getFromFile(t.files[0]);this._reportTelemetry({action:"pdfjs.image.image_selected",data:{alt_text_modal:this._uiManager.useNewAltTextFlow}}),this.#kr(e)}else this.remove();i()}),{signal:e}),t.addEventListener("cancel",(()=>{this.remove(),i()}),{signal:e})})).finally((()=>this.#Ir())),t.click()}remove(){this.#yr&&(this.#Ar=null,this._uiManager.imageManager.deleteId(this.#yr),this.#Er?.remove(),this.#Er=null,this.#Ua?.disconnect(),this.#Ua=null,this.#Sr&&(clearTimeout(this.#Sr),this.#Sr=null)),super.remove()}rebuild(){this.parent?(super.rebuild(),null!==this.div&&(this.#yr&&null===this.#Er&&this.#Pr(),this.isAttachedToDOM||this.parent.add(this))):this.#yr&&this.#Pr()}onceAdded(){this._isDraggable=!0,this.div.focus()}isEmpty(){return!(this.#wr||this.#Ar||this.#_r||this.#xr||this.#yr)}get isResizable(){return!0}render(){if(this.div)return this.div;let t,e;if(this.width&&(t=this.x,e=this.y),super.render(),this.div.hidden=!0,this.div.setAttribute("role","figure"),this.addAltTextButton(),this.#Ar?this.#Ya():this.#Pr(),this.width&&!this.annotationElementId){const[i,s]=this.parentDimensions;this.setAt(t*i,e*s,this.width*i,this.height*s)}return this.div}#Ya(){const{div:t}=this;let{width:e,height:i}=this.#Ar;const[s,n]=this.pageDimensions,a=.75;if(this.width)e=this.width*s,i=this.height*n;else if(e>a*s||i>a*n){const t=Math.min(a*s/e,a*n/i);e*=t,i*=t}const[r,o]=this.parentDimensions;this.setDims(e*r/s,i*o/n),this._uiManager.enableWaiting(!1);const l=this.#Er=document.createElement("canvas");l.setAttribute("role","img"),this.addContainer(l),this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&!this.annotationElementId||(t.hidden=!1),this.#Rr(e,i),this.#Qa(),this.#Mr||(this.parent.addUndoableEditor(this),this.#Mr=!0),this._reportTelemetry({action:"inserted_image"}),this.#Cr&&l.setAttribute("aria-label",this.#Cr)}copyCanvas(t,e,i=!1){t||(t=224);const{width:s,height:n}=this.#Ar,a=new vt;let r=this.#Ar,o=s,l=n,h=null;if(e){if(s>e||n>e){const t=Math.min(e/s,e/n);o=Math.floor(s*t),l=Math.floor(n*t)}h=document.createElement("canvas");const t=h.width=Math.ceil(o*a.sx),i=h.height=Math.ceil(l*a.sy);this.#Tr||(r=this.#Dr(t,i));const d=h.getContext("2d");d.filter=this._uiManager.hcmFilter;let c="white",u="#cfcfd8";"none"!==this._uiManager.hcmFilter?u="black":window.matchMedia?.("(prefers-color-scheme: dark)").matches&&(c="#8f8f9d",u="#42414d");const p=15,g=p*a.sx,m=p*a.sy,f=new OffscreenCanvas(2*g,2*m),b=f.getContext("2d");b.fillStyle=c,b.fillRect(0,0,2*g,2*m),b.fillStyle=u,b.fillRect(0,0,g,m),b.fillRect(g,m,g,m),d.fillStyle=d.createPattern(f,"repeat"),d.fillRect(0,0,t,i),d.drawImage(r,0,0,r.width,r.height,0,0,t,i)}let d=null;if(i){let e,i;if(a.symmetric&&r.widtht||n>t){const a=Math.min(t/s,t/n);e=Math.floor(s*a),i=Math.floor(n*a),this.#Tr||(r=this.#Dr(e,i))}const o=new OffscreenCanvas(e,i).getContext("2d",{willReadFrequently:!0});o.drawImage(r,0,0,r.width,r.height,0,0,e,i),d={width:e,height:i,data:o.getImageData(0,0,e,i).data}}return{canvas:h,width:o,height:l,imageData:d}}#Lr(t,e){const[i,s]=this.parentDimensions;this.width=t/i,this.height=e/s,this._initialOptions?.isCentered?this.center():this.fixAndSetPosition(),this._initialOptions=null,null!==this.#Sr&&clearTimeout(this.#Sr),this.#Sr=setTimeout((()=>{this.#Sr=null,this.#Rr(t,e)}),200)}#Dr(t,e){const{width:i,height:s}=this.#Ar;let n=i,a=s,r=this.#Ar;for(;n>2*t||a>2*e;){const i=n,s=a;n>2*t&&(n=n>=16384?Math.floor(n/2)-1:Math.ceil(n/2)),a>2*e&&(a=a>=16384?Math.floor(a/2)-1:Math.ceil(a/2));const o=new OffscreenCanvas(n,a);o.getContext("2d").drawImage(r,0,0,i,s,0,0,n,a),r=o.transferToImageBitmap()}return r}#Rr(t,e){const i=new vt,s=Math.ceil(t*i.sx),n=Math.ceil(e*i.sy),a=this.#Er;if(!a||a.width===s&&a.height===n)return;a.width=s,a.height=n;const r=this.#Tr?this.#Ar:this.#Dr(s,n),o=a.getContext("2d");o.filter=this._uiManager.hcmFilter,o.drawImage(r,0,0,r.width,r.height,0,0,s,n)}getImageForAltText(){return this.#Er}#Fr(t){if(t){if(this.#Tr){const t=this._uiManager.imageManager.getSvgUrl(this.#yr);if(t)return t}const t=document.createElement("canvas");return({width:t.width,height:t.height}=this.#Ar),t.getContext("2d").drawImage(this.#Ar,0,0),t.toDataURL()}if(this.#Tr){const[t,e]=this.pageDimensions,i=Math.round(this.width*t*Y.PDF_TO_CSS_UNITS),s=Math.round(this.height*e*Y.PDF_TO_CSS_UNITS),n=new OffscreenCanvas(i,s);return n.getContext("2d").drawImage(this.#Ar,0,0,this.#Ar.width,this.#Ar.height,0,0,i,s),n.transferToImageBitmap()}return structuredClone(this.#Ar)}#Qa(){this._uiManager._signal&&(this.#Ua=new ResizeObserver((t=>{const e=t[0].contentRect;e.width&&e.height&&this.#Lr(e.width,e.height)})),this.#Ua.observe(this.div),this._uiManager._signal.addEventListener("abort",(()=>{this.#Ua?.disconnect(),this.#Ua=null}),{once:!0}))}static async deserialize(t,e,i){let s=null;if(t instanceof Ki){const{data:{rect:n,rotation:a,id:r,structParent:o,popupRef:l},container:d,parent:{page:{pageNumber:c}}}=t,u=d.querySelector("canvas"),p=i.imageManager.getFromCanvas(d.id,u);u.remove();const g=(await e._structTree.getAriaAttributes(`${$}${r}`))?.get("aria-label")||"";s=t={annotationType:h.STAMP,bitmapId:p.id,bitmap:p.bitmap,pageIndex:c-1,rect:n.slice(0),rotation:a,id:r,deleted:!1,accessibilityData:{decorative:!1,altText:g},isSvg:!1,structParent:o,popupRef:l}}const n=await super.deserialize(t,e,i),{rect:a,bitmap:r,bitmapUrl:o,bitmapId:l,isSvg:d,accessibilityData:c}=t;l&&i.imageManager.isValidId(l)?(n.#yr=l,r&&(n.#Ar=r)):n.#_r=o,n.#Tr=d;const[u,p]=n.pageDimensions;return n.width=(a[2]-a[0])/u,n.height=(a[3]-a[1])/p,n.annotationElementId=t.id||null,c&&(n.altTextData=c),n._initialData=s,n.#Mr=!!s,n}serialize(t=!1,e=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const i={annotationType:h.STAMP,bitmapId:this.#yr,pageIndex:this.pageIndex,rect:this.getRect(0,0),rotation:this.rotation,isSvg:this.#Tr,structTreeParentId:this._structTreeParentId};if(t)return i.bitmapUrl=this.#Fr(!0),i.accessibilityData=this.serializeAltText(!0),i;const{decorative:s,altText:n}=this.serializeAltText(!1);if(!s&&n&&(i.accessibilityData={type:"Figure",alt:n}),this.annotationElementId){const t=this.#gn(i);if(t.isSame)return null;t.isSameAltText?delete i.accessibilityData:i.accessibilityData.structParent=this._initialData.structParent??-1}if(i.id=this.annotationElementId,null===e)return i;e.stamps||=new Map;const a=this.#Tr?(i.rect[2]-i.rect[0])*(i.rect[3]-i.rect[1]):null;if(e.stamps.has(this.#yr)){if(this.#Tr){const t=e.stamps.get(this.#yr);a>t.area&&(t.area=a,t.serialized.bitmap.close(),t.serialized.bitmap=this.#Fr(!1))}}else e.stamps.set(this.#yr,{area:a,serialized:i}),i.bitmap=this.#Fr(!1);return i}#gn(t){const{rect:e,pageIndex:i,accessibilityData:{altText:s}}=this._initialData,n=t.rect.every(((t,i)=>Math.abs(t-e[i])<1)),a=t.pageIndex===i,r=(t.accessibilityData?.alt||"")===s;return{isSame:n&&a&&r,isSameAltText:r}}renderAnnotationElement(t){return t.updateEdited({rect:this.getRect(0,0)}),null}}class hs{#Qs;#Nr=!1;#Or=null;#Br=null;#zr=null;#Hr=new Map;#jr=!1;#Ur=!1;#$r=!1;#Wr=null;#Gr=null;#m;static _initialized=!1;static#H=new Map([Zi,os,ls,rs].map((t=>[t._editorType,t])));constructor({uiManager:t,pageIndex:e,div:i,structTreeLayer:s,accessibilityManager:n,annotationLayer:a,drawLayer:r,textLayer:o,viewport:l,l10n:h}){const d=[...hs.#H.values()];if(!hs._initialized){hs._initialized=!0;for(const e of d)e.initialize(h,t)}t.registerEditorTypes(d),this.#m=t,this.pageIndex=e,this.div=i,this.#Qs=n,this.#Or=a,this.viewport=l,this.#Wr=o,this.drawLayer=r,this._structTree=s,this.#m.addLayer(this)}get isEmpty(){return 0===this.#Hr.size}get isInvisible(){return this.isEmpty&&this.#m.getMode()===h.NONE}updateToolbar(t){this.#m.updateToolbar(t)}updateMode(t=this.#m.getMode()){switch(this.#Vr(),t){case h.NONE:return this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),void this.disableClick();case h.INK:this.addInkEditorIfNeeded(!1),this.disableTextSelection(),this.togglePointerEvents(!0),this.disableClick();break;case h.HIGHLIGHT:this.enableTextSelection(),this.togglePointerEvents(!1),this.disableClick();break;default:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick()}this.toggleAnnotationLayerPointerEvents(!1);const{classList:e}=this.div;for(const i of hs.#H.values())e.toggle(`${i._type}Editing`,t===i._editorType);this.div.hidden=!1}hasTextLayer(t){return t===this.#Wr?.div}addInkEditorIfNeeded(t){if(this.#m.getMode()===h.INK){if(!t)for(const t of this.#Hr.values())if(t.isEmpty())return void t.setInBackground();this.createAndAddNewEditor({offsetX:0,offsetY:0},!1).setInBackground()}}setEditingState(t){this.#m.setEditingState(t)}addCommands(t){this.#m.addCommands(t)}toggleDrawing(t=!1){this.div.classList.toggle("drawing",!t)}togglePointerEvents(t=!1){this.div.classList.toggle("disabled",!t)}toggleAnnotationLayerPointerEvents(t=!1){this.#Or?.div.classList.toggle("disabled",!t)}async enable(){this.div.tabIndex=0,this.togglePointerEvents(!0);const t=new Set;for(const e of this.#Hr.values())e.enableEditing(),e.show(!0),e.annotationElementId&&(this.#m.removeChangedExistingAnnotation(e),t.add(e.annotationElementId));if(!this.#Or)return;const e=this.#Or.getEditableAnnotations();for(const i of e){if(i.hide(),this.#m.isDeletedAnnotationElement(i.data.id))continue;if(t.has(i.data.id))continue;const e=await this.deserialize(i);e&&(this.addOrRebuild(e),e.enableEditing())}}disable(){this.#$r=!0,this.div.tabIndex=-1,this.togglePointerEvents(!1);const t=new Map,e=new Map;for(const i of this.#Hr.values())i.disableEditing(),i.annotationElementId&&(null===i.serialize()?(e.set(i.annotationElementId,i),this.getEditableAnnotation(i.annotationElementId)?.show(),i.remove()):t.set(i.annotationElementId,i));if(this.#Or){const i=this.#Or.getEditableAnnotations();for(const s of i){const{id:i}=s.data;if(this.#m.isDeletedAnnotationElement(i))continue;let n=e.get(i);n?(n.resetAnnotationElement(s),n.show(!1),s.show()):(n=t.get(i),n&&(this.#m.addChangedExistingAnnotation(n),n.renderAnnotationElement(s)&&n.show(!1)),s.show())}}this.#Vr(),this.isEmpty&&(this.div.hidden=!0);const{classList:i}=this.div;for(const t of hs.#H.values())i.remove(`${t._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),this.#$r=!1}getEditableAnnotation(t){return this.#Or?.getEditableAnnotation(t)||null}setActiveEditor(t){this.#m.getActive()!==t&&this.#m.setActiveEditor(t)}enableTextSelection(){if(this.div.tabIndex=-1,this.#Wr?.div&&!this.#Gr){this.#Gr=new AbortController;const t=this.#m.combinedSignal(this.#Gr);this.#Wr.div.addEventListener("pointerdown",this.#qr.bind(this),{signal:t}),this.#Wr.div.classList.add("highlighting")}}disableTextSelection(){this.div.tabIndex=0,this.#Wr?.div&&this.#Gr&&(this.#Gr.abort(),this.#Gr=null,this.#Wr.div.classList.remove("highlighting"))}#qr(t){this.#m.unselectAll();const{target:e}=t;if(e===this.#Wr.div||("img"===e.getAttribute("role")||e.classList.contains("endOfContent"))&&this.#Wr.div.contains(e)){const{isMac:e}=O.platform;if(0!==t.button||t.ctrlKey&&e)return;this.#m.showAllEditors("highlight",!0,!0),this.#Wr.div.classList.add("free"),this.toggleDrawing(),rs.startHighlighting(this,"ltr"===this.#m.direction,{target:this.#Wr.div,x:t.x,y:t.y}),this.#Wr.div.addEventListener("pointerup",(()=>{this.#Wr.div.classList.remove("free"),this.toggleDrawing(!0)}),{once:!0,signal:this.#m._signal}),t.preventDefault()}}enableClick(){if(this.#Br)return;this.#Br=new AbortController;const t=this.#m.combinedSignal(this.#Br);this.div.addEventListener("pointerdown",this.pointerdown.bind(this),{signal:t}),this.div.addEventListener("pointerup",this.pointerup.bind(this),{signal:t})}disableClick(){this.#Br?.abort(),this.#Br=null}attach(t){this.#Hr.set(t.id,t);const{annotationElementId:e}=t;e&&this.#m.isDeletedAnnotationElement(e)&&this.#m.removeDeletedAnnotationElement(t)}detach(t){this.#Hr.delete(t.id),this.#Qs?.removePointerInTextLayer(t.contentDiv),!this.#$r&&t.annotationElementId&&this.#m.addDeletedAnnotationElement(t)}remove(t){this.detach(t),this.#m.removeEditor(t),t.div.remove(),t.isAttachedToDOM=!1,this.#Ur||this.addInkEditorIfNeeded(!1)}changeParent(t){t.parent!==this&&(t.parent&&t.annotationElementId&&(this.#m.addDeletedAnnotationElement(t.annotationElementId),kt.deleteAnnotationElement(t),t.annotationElementId=null),this.attach(t),t.parent?.detach(t),t.setParent(this),t.div&&t.isAttachedToDOM&&(t.div.remove(),this.div.append(t.div)))}add(t){if(t.parent!==this||!t.isAttachedToDOM){if(this.changeParent(t),this.#m.addEditor(t),this.attach(t),!t.isAttachedToDOM){const e=t.render();this.div.append(e),t.isAttachedToDOM=!0}t.fixAndSetPosition(),t.onceAdded(),this.#m.addToAnnotationStorage(t),t._reportTelemetry(t.telemetryInitialData)}}moveEditorInDOM(t){if(!t.isAttachedToDOM)return;const{activeElement:e}=document;t.div.contains(e)&&!this.#zr&&(t._focusEventsAllowed=!1,this.#zr=setTimeout((()=>{this.#zr=null,t.div.contains(document.activeElement)?t._focusEventsAllowed=!0:(t.div.addEventListener("focusin",(()=>{t._focusEventsAllowed=!0}),{once:!0,signal:this.#m._signal}),e.focus())}),0)),t._structTreeParentId=this.#Qs?.moveElementInDOM(this.div,t.div,t.contentDiv,!0)}addOrRebuild(t){t.needsToBeRebuilt()?(t.parent||=this,t.rebuild(),t.show()):this.add(t)}addUndoableEditor(t){this.addCommands({cmd:()=>t._uiManager.rebuild(t),undo:()=>{t.remove()},mustExec:!1})}getNextId(){return this.#m.getId()}get#Xr(){return hs.#H.get(this.#m.getMode())}combinedSignal(t){return this.#m.combinedSignal(t)}#Kr(t){const e=this.#Xr;return e?new e.prototype.constructor(t):null}canCreateNewEmptyEditor(){return this.#Xr?.canCreateNewEmptyEditor()}pasteEditor(t,e){this.#m.updateToolbar(t),this.#m.updateMode(t);const{offsetX:i,offsetY:s}=this.#Yr(),n=this.getNextId(),a=this.#Kr({parent:this,id:n,x:i,y:s,uiManager:this.#m,isCentered:!0,...e});a&&this.add(a)}async deserialize(t){return await(hs.#H.get(t.annotationType??t.annotationEditorType)?.deserialize(t,this,this.#m))||null}createAndAddNewEditor(t,e,i={}){const s=this.getNextId(),n=this.#Kr({parent:this,id:s,x:t.offsetX,y:t.offsetY,uiManager:this.#m,isCentered:e,...i});return n&&this.add(n),n}#Yr(){const{x:t,y:e,width:i,height:s}=this.div.getBoundingClientRect(),n=Math.max(0,t),a=Math.max(0,e),r=(n+Math.min(window.innerWidth,t+i))/2-t,o=(a+Math.min(window.innerHeight,e+s))/2-e,[l,h]=this.viewport.rotation%180==0?[r,o]:[o,r];return{offsetX:l,offsetY:h}}addNewEditor(){this.createAndAddNewEditor(this.#Yr(),!0)}setSelected(t){this.#m.setSelected(t)}toggleSelected(t){this.#m.toggleSelected(t)}isSelected(t){return this.#m.isSelected(t)}unselect(t){this.#m.unselect(t)}pointerup(t){const{isMac:e}=O.platform;0!==t.button||t.ctrlKey&&e||t.target===this.div&&this.#jr&&(this.#jr=!1,this.#Nr?this.#m.getMode()!==h.STAMP?this.createAndAddNewEditor(t,!1):this.#m.unselectAll():this.#Nr=!0)}pointerdown(t){if(this.#m.getMode()===h.HIGHLIGHT&&this.enableTextSelection(),this.#jr)return void(this.#jr=!1);const{isMac:e}=O.platform;if(0!==t.button||t.ctrlKey&&e)return;if(t.target!==this.div)return;this.#jr=!0;const i=this.#m.getActive();this.#Nr=!i||i.isEmpty()}findNewParent(t,e,i){const s=this.#m.findParent(e,i);return null!==s&&s!==this&&(s.changeParent(t),!0)}destroy(){this.#m.getActive()?.parent===this&&(this.#m.commitOrRemove(),this.#m.setActiveEditor(null)),this.#zr&&(clearTimeout(this.#zr),this.#zr=null);for(const t of this.#Hr.values())this.#Qs?.removePointerInTextLayer(t.contentDiv),t.setParent(null),t.isAttachedToDOM=!1,t.div.remove();this.div=null,this.#Hr.clear(),this.#m.removeLayer(this)}#Vr(){this.#Ur=!0;for(const t of this.#Hr.values())t.isEmpty()&&t.remove();this.#Ur=!1}render({viewport:t}){this.viewport=t,bt(this.div,t);for(const t of this.#m.getEditors(this.pageIndex))this.add(t),t.rebuild();this.updateMode()}update({viewport:t}){this.#m.commitOrRemove(),this.#Vr();const e=this.viewport.rotation,i=t.rotation;if(this.viewport=t,bt(this.div,{rotation:i}),e!==i)for(const t of this.#Hr.values())t.rotate(i);this.addInkEditorIfNeeded(!1)}get pageDimensions(){const{pageWidth:t,pageHeight:e}=this.viewport.rawDims;return[t,e]}get scale(){return this.#m.viewParameters.realScale}}class ds{#Ps=null;#A=0;#Qr=new Map;#Jr=new Map;constructor({pageIndex:t}){this.pageIndex=t}setParent(t){if(this.#Ps){if(this.#Ps!==t){if(this.#Qr.size>0)for(const e of this.#Qr.values())e.remove(),t.append(e);this.#Ps=t}}else this.#Ps=t}static get _svgFactory(){return E(this,"_svgFactory",new tt)}static#Zr(t,{x:e=0,y:i=0,width:s=1,height:n=1}={}){const{style:a}=t;a.top=100*i+"%",a.left=100*e+"%",a.width=100*s+"%",a.height=100*n+"%"}#to(t){const e=ds._svgFactory.create(1,1,!0);return this.#Ps.append(e),e.setAttribute("aria-hidden",!0),ds.#Zr(e,t),e}#eo(t,e){const i=ds._svgFactory.createElement("clipPath");t.append(i);const s=`clip_${e}`;i.setAttribute("id",s),i.setAttribute("clipPathUnits","objectBoundingBox");const n=ds._svgFactory.createElement("use");return i.append(n),n.setAttribute("href",`#${e}`),n.classList.add("clip"),s}highlight(t,e,i,s=!1){const n=this.#A++,a=this.#to(t.box);a.classList.add("highlight"),t.free&&a.classList.add("free");const r=ds._svgFactory.createElement("defs");a.append(r);const o=ds._svgFactory.createElement("path");r.append(o);const l=`path_p${this.pageIndex}_${n}`;o.setAttribute("id",l),o.setAttribute("d",t.toSVGPath()),s&&this.#Jr.set(n,o);const h=this.#eo(r,l),d=ds._svgFactory.createElement("use");return a.append(d),a.setAttribute("fill",e),a.setAttribute("fill-opacity",i),d.setAttribute("href",`#${l}`),this.#Qr.set(n,a),{id:n,clipPathId:`url(#${h})`}}highlightOutline(t){const e=this.#A++,i=this.#to(t.box);i.classList.add("highlightOutline");const s=ds._svgFactory.createElement("defs");i.append(s);const n=ds._svgFactory.createElement("path");s.append(n);const a=`path_p${this.pageIndex}_${e}`;let r;if(n.setAttribute("id",a),n.setAttribute("d",t.toSVGPath()),n.setAttribute("vector-effect","non-scaling-stroke"),t.free){i.classList.add("free");const t=ds._svgFactory.createElement("mask");s.append(t),r=`mask_p${this.pageIndex}_${e}`,t.setAttribute("id",r),t.setAttribute("maskUnits","objectBoundingBox");const n=ds._svgFactory.createElement("rect");t.append(n),n.setAttribute("width","1"),n.setAttribute("height","1"),n.setAttribute("fill","white");const o=ds._svgFactory.createElement("use");t.append(o),o.setAttribute("href",`#${a}`),o.setAttribute("stroke","none"),o.setAttribute("fill","black"),o.setAttribute("fill-rule","nonzero"),o.classList.add("mask")}const o=ds._svgFactory.createElement("use");i.append(o),o.setAttribute("href",`#${a}`),r&&o.setAttribute("mask",`url(#${r})`);const l=o.cloneNode();return i.append(l),o.classList.add("mainOutline"),l.classList.add("secondaryOutline"),this.#Qr.set(e,i),e}finalizeLine(t,e){const i=this.#Jr.get(t);this.#Jr.delete(t),this.updateBox(t,e.box),i.setAttribute("d",e.toSVGPath())}updateLine(t,e){this.#Qr.get(t).firstChild.firstChild.setAttribute("d",e.toSVGPath())}removeFreeHighlight(t){this.remove(t),this.#Jr.delete(t)}updatePath(t,e){this.#Jr.get(t).setAttribute("d",e.toSVGPath())}updateBox(t,e){ds.#Zr(this.#Qr.get(t),e)}show(t,e){this.#Qr.get(t).classList.toggle("hidden",!e)}rotate(t,e){this.#Qr.get(t).setAttribute("data-main-rotation",e)}changeColor(t,e){this.#Qr.get(t).setAttribute("fill",e)}changeOpacity(t,e){this.#Qr.get(t).setAttribute("fill-opacity",e)}addClass(t,e){this.#Qr.get(t).classList.add(e)}removeClass(t,e){this.#Qr.get(t).classList.remove(e)}getSVGRoot(t){return this.#Qr.get(t)}remove(t){null!==this.#Ps&&(this.#Qr.get(t).remove(),this.#Qr.delete(t))}destroy(){this.#Ps=null;for(const t of this.#Qr.values())t.remove();this.#Qr.clear()}}var cs=e.AbortException,us=e.AnnotationEditorLayer,ps=e.AnnotationEditorParamsType,gs=e.AnnotationEditorType,ms=e.AnnotationEditorUIManager,fs=e.AnnotationLayer,bs=e.AnnotationMode,vs=e.CMapCompressionType,As=e.ColorPicker,ys=e.DOMSVGFactory,ws=e.DrawLayer,_s=e.FeatureTest,xs=e.GlobalWorkerOptions,Cs=e.ImageKind,Es=e.InvalidPDFException,Ss=e.MissingPDFException,Ts=e.OPS,Ms=e.OutputScale,ks=e.PDFDataRangeTransport,Is=e.PDFDateString,Ps=e.PDFWorker,Rs=e.PasswordResponses,Ds=e.PermissionFlag,Ls=e.PixelsPerInch,Fs=e.RenderingCancelledException,Ns=e.TextLayer,Os=e.UnexpectedResponseException,Bs=e.Util,zs=e.VerbosityLevel,Hs=e.XfaLayer,js=e.build,Us=e.createValidAbsoluteUrl,$s=e.fetchData,Ws=e.getDocument,Gs=e.getFilenameFromUrl,Vs=e.getPdfFilenameFromUrl,qs=e.getXfaPageViewport,Xs=e.isDataScheme,Ks=e.isPdfFile,Ys=e.noContextMenu,Qs=e.normalizeUnicode,Js=e.setLayerDimensions,Zs=e.shadow,tn=e.version;"undefined"!=typeof window&&"Worker"in window&&(xs.workerPort=new Worker(new URL(i.p+i.u(13),i.b),{type:void 0}))}}]); \ No newline at end of file diff --git a/dist/560.index.js.LICENSE.txt b/dist/pdfjs-dist-webpack.chunk.js.LICENSE.txt similarity index 100% rename from dist/560.index.js.LICENSE.txt rename to dist/pdfjs-dist-webpack.chunk.js.LICENSE.txt diff --git a/package-lock.json b/package-lock.json index 70b64ea..e9c843d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@transcom/react-file-viewer", - "version": "1.2.4", + "version": "1.4.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@transcom/react-file-viewer", - "version": "1.2.4", + "version": "1.4.0", "license": "MIT", "dependencies": { "@babel/plugin-proposal-class-static-block": "^7.21.0", diff --git a/package.json b/package.json index 21460d1..72e2954 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@transcom/react-file-viewer", - "version": "1.4.0", + "version": "1.4.1", "description": "Extendable file viewer for web", "main": "dist/index.js", "module": "dist/index.js", diff --git a/src/components/drivers/pdf-viewer.jsx b/src/components/drivers/pdf-viewer.jsx index 29c1d65..967c45d 100644 --- a/src/components/drivers/pdf-viewer.jsx +++ b/src/components/drivers/pdf-viewer.jsx @@ -1,7 +1,6 @@ // Copyright (c) 2017 PlanGrid, Inc. import React from 'react' -import VisibilitySensor from 'react-visibility-sensor' const INCREASE_PERCENTAGE = 0.2 const DEFAULT_SCALE = 1.1 @@ -9,64 +8,105 @@ const DEFAULT_SCALE = 1.1 export class PDFPage extends React.Component { constructor(props) { super(props) - this.state = {} - this.onChange = this.onChange.bind(this) + this.canvas = React.createRef() + this.state = { + isVisible: true, + } + this.renderTask = null // Stores the page rendering task for proper canvas handling } componentDidMount() { - if (this.props.disableVisibilityCheck) this.fetchAndRenderPage() + if (!this.props.disableVisibilityCheck) { + this.observer = new IntersectionObserver(([entry]) => { + if (entry.target === this.canvas.current) { + this.setState({ isVisible: entry.isIntersecting }) + } + }) + if (this.canvas.current) this.observer.observe(this.canvas.current) + } + this.fetchAndRenderPage() } - componentDidUpdate(prevProps, prevState) { + componentDidUpdate(prevProps) { if (this.props.disableVisibilityCheck) { - if (prevProps.zoom !== this.props.zoom) this.fetchAndRenderPage() + if ( + prevProps.zoom !== this.props.zoom || + prevProps.rotation !== this.props.rotation + ) { + this.fetchAndRenderPage() + } return } - // we want to render/re-render in two scenarias - // user scrolls to the pdf - // user zooms in if ( - prevState.isVisible === this.state.isVisible && - prevProps.zoom === this.props.zoom - ) - return - if (this.state.isVisible) this.fetchAndRenderPage() + prevProps.zoom !== this.props.zoom || + prevProps.rotation !== this.props.rotation || + prevProps.index !== this.props.index || + prevProps.isVisible !== this.state.isVisible + ) { + this.fetchAndRenderPage() + } } - onChange(isVisible) { - if (isVisible) this.setState({ isVisible }) + componentWillUnmount() { + if (this.observer) { + this.observer.disconnect() + } + if (this.renderTask) { + this.renderTask.cancel() + this.renderTask = null + } } fetchAndRenderPage() { - const { pdf, index } = this.props - pdf - .getPage(index) - .then(this.renderPage.bind(this)) - .catch((error) => { - console.error(`Error fetching page ${index}:`, error) - }) + // Make sure current render tasks are cancelled before starting a new one + if (this.renderTask) { + this.renderTask.cancel() + this.renderTask = null + } + + if (this.props.disableVisibilityCheck || this.state.isVisible) { + const { pdf, index } = this.props + pdf + .getPage(index) + .then(this.renderPage.bind(this)) + .catch((error) => { + console.error(`Error fetching page ${index}:`, error) + }) + } } renderPage(page) { try { - const { containerWidth, zoom } = this.props + const { containerWidth, zoom, rotation } = this.props const initialViewport = page.getViewport({ scale: DEFAULT_SCALE }) const calculatedScale = containerWidth / initialViewport.width const scale = (calculatedScale > DEFAULT_SCALE ? DEFAULT_SCALE : calculatedScale) + zoom * INCREASE_PERCENTAGE - const viewport = page.getViewport({ scale }) + const viewport = page.getViewport({ scale, rotation }) const { width, height } = viewport - const context = this.canvas.getContext('2d') - this.canvas.width = width - this.canvas.height = height + const canvas = this.canvas.current + const context = canvas.getContext('2d') + canvas.width = width + canvas.height = height - page.render({ + // Store the active render task + this.renderTask = page.render({ canvasContext: context, viewport, }) + + // Handle completion of rendering + this.renderTask.promise + .then(() => { + // Rendering complete, clear the task + this.renderTask = null + }) + .catch((error) => { + console.error(`Error rendering page ${this.props.index}:`, error) + }) } catch (error) { console.error(`Error rendering page ${this.props.index}:`, error) } @@ -76,21 +116,7 @@ export class PDFPage extends React.Component { const { index } = this.props return (
- {this.props.disableVisibilityCheck ? ( - (this.canvas = node)} - width="670" - height="870" - /> - ) : ( - - (this.canvas = node)} - width="670" - height="870" - /> - - )} +
) } @@ -104,18 +130,36 @@ export default class PDFDriver extends React.Component { pdf: null, zoom: 0, percent: 0, + rotationValue: 0, } this.increaseZoom = this.increaseZoom.bind(this) this.reduceZoom = this.reduceZoom.bind(this) this.resetZoom = this.resetZoom.bind(this) + this.rotateLeft = this.rotateLeft.bind(this) + this.rotateRight = this.rotateRight.bind(this) + } + + rotateLeft() { + this.setState((prevState) => ({ + rotationValue: (prevState.rotationValue - 90 + 360) % 360, + })); + } + + rotateRight() { + this.setState((prevState) => ({ + rotationValue: (prevState.rotationValue + 90) % 360, + })); } componentDidMount() { // Dynamic import of ESM into CJS ;(async () => { // sidestep that pdfjs is bundled as esm - const pdfjs = await import('pdfjs-dist/webpack') + const pdfjs = await import( + // Make sure we add comments to this import so the webpack can chunk it properly + /* webpackPrefetch: 0, webpackChunkName: "pdfjs-dist-webpack" */ 'pdfjs-dist/webpack' + ) const { filePath } = this.props const containerWidth = this.container.offsetWidth const loadingTask = pdfjs.getDocument(filePath) @@ -125,6 +169,11 @@ export default class PDFDriver extends React.Component { loadingTask.promise .then((pdf) => { + if (this.pdf) { + // Attempting to mount a new PDF when one already exists + // Destroy the current PDF and reload the new one + this.pdf.destroy() + } this.setState({ pdf, containerWidth }) }) .catch((error) => { @@ -141,10 +190,19 @@ export default class PDFDriver extends React.Component { } componentWillUnmount() { - const { pdf } = this.state - if (pdf) { - pdf.destroy() - this.setState({ pdf: null }) + if (this.pdf) { + this.pdf.destroy() + this.pdf = null + } + } + + componentDidUpdate(prevProps) { + if (this.props.filePath !== prevProps.filePath) { + if (this.pdf) { + this.pdf.destroy() + this.pdf = null + } + this.loadPdf() } } @@ -173,7 +231,7 @@ export default class PDFDriver extends React.Component { } renderPages() { - const { pdf, containerWidth, zoom } = this.state + const { pdf, containerWidth, zoom, rotationValue } = this.state if (!pdf) return null const pages = [...Array(pdf.numPages).keys()].map((i) => i + 1) return pages.map((_, i) => ( @@ -183,6 +241,7 @@ export default class PDFDriver extends React.Component { pdf={pdf} containerWidth={containerWidth} zoom={zoom * INCREASE_PERCENTAGE} + rotation={rotationValue} disableVisibilityCheck={this.props.disableVisibilityCheck} /> )) @@ -202,6 +261,8 @@ export default class PDFDriver extends React.Component { renderControls({ handleZoomIn: this.increaseZoom, handleZoomOut: this.reduceZoom, + handleRotateLeft: this.rotateLeft, + handleRotateRight: this.rotateRight, }) ) : (
@@ -223,6 +284,18 @@ export default class PDFDriver extends React.Component { onClick={this.reduceZoom}> + +
)} diff --git a/webpack.config.js b/webpack.config.js index ee7b419..23e55a5 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -6,8 +6,8 @@ const path = require('path') const BUILD_DIR = path.resolve(__dirname, './dist') const APP_DIR = path.resolve(__dirname, './src') -const BundleAnalyzerPlugin = - require('webpack-bundle-analyzer').BundleAnalyzerPlugin +const BundleAnalyzerPlugin = require('webpack-bundle-analyzer') + .BundleAnalyzerPlugin const config = { entry: `${APP_DIR}/components`, @@ -18,7 +18,8 @@ const config = { filename: 'index.js', library: ['FileViewer'], libraryTarget: 'umd', - publicPath: '/', + publicPath: '/static/react-file-viewer/', + chunkFilename: '[name].chunk.js', }, resolve: { modules: [path.resolve(__dirname, './src'), 'node_modules'], diff --git a/yarn.lock b/yarn.lock index 7ae03da..5f84b30 100644 --- a/yarn.lock +++ b/yarn.lock @@ -8516,9 +8516,9 @@ tslib@^2.0.3, tslib@^2.4.0: integrity sha512-gLXCKdN1/j47AiHiOkJN69hJmcbGTHI0ImLmbYLHykhgeN0jVGola9yVjFgzCUklsZQMW55o+dW7IXv3RCXDzA== tslib@^2.2.0: - version "2.8.0" - resolved "https://registry.yarnpkg.com/tslib/-/tslib-2.8.0.tgz#d124c86c3c05a40a91e6fdea4021bd31d377971b" - integrity sha512-jWVzBLplnCmoaTr13V9dYbiQ99wvZRd0vNWaDRg+aVYRcjDF3nDksxFDE/+fkXnKhpnUUkmx5pK/v8mCtLVqZA== + version "2.8.1" + resolved "https://registry.yarnpkg.com/tslib/-/tslib-2.8.1.tgz#612efe4ed235d567e8aba5f2a5fab70280ade83f" + integrity sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w== tty-browserify@0.0.0: version "0.0.0"